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/OperationKinds.h"
32 #include "clang/AST/Stmt.h"
33 #include "clang/AST/TemplateBase.h"
34 #include "clang/AST/Type.h"
35 #include "clang/AST/TypeLoc.h"
36 #include "clang/AST/UnresolvedSet.h"
37 #include "clang/Analysis/Analyses/FormatString.h"
38 #include "clang/Basic/AddressSpaces.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/OpenCLOptions.h"
45 #include "clang/Basic/OperatorKinds.h"
46 #include "clang/Basic/PartialDiagnostic.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/SyncScope.h"
51 #include "clang/Basic/TargetBuiltins.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/TypeTraits.h"
55 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
56 #include "clang/Sema/Initialization.h"
57 #include "clang/Sema/Lookup.h"
58 #include "clang/Sema/Ownership.h"
59 #include "clang/Sema/Scope.h"
60 #include "clang/Sema/ScopeInfo.h"
61 #include "clang/Sema/Sema.h"
62 #include "clang/Sema/SemaInternal.h"
63 #include "llvm/ADT/APFloat.h"
64 #include "llvm/ADT/APInt.h"
65 #include "llvm/ADT/APSInt.h"
66 #include "llvm/ADT/ArrayRef.h"
67 #include "llvm/ADT/DenseMap.h"
68 #include "llvm/ADT/FoldingSet.h"
69 #include "llvm/ADT/None.h"
70 #include "llvm/ADT/Optional.h"
71 #include "llvm/ADT/STLExtras.h"
72 #include "llvm/ADT/SmallBitVector.h"
73 #include "llvm/ADT/SmallPtrSet.h"
74 #include "llvm/ADT/SmallString.h"
75 #include "llvm/ADT/SmallVector.h"
76 #include "llvm/ADT/StringRef.h"
77 #include "llvm/ADT/StringSwitch.h"
78 #include "llvm/ADT/Triple.h"
79 #include "llvm/Support/AtomicOrdering.h"
80 #include "llvm/Support/Casting.h"
81 #include "llvm/Support/Compiler.h"
82 #include "llvm/Support/ConvertUTF.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/Format.h"
85 #include "llvm/Support/Locale.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include <algorithm>
89 #include <cassert>
90 #include <cstddef>
91 #include <cstdint>
92 #include <functional>
93 #include <limits>
94 #include <string>
95 #include <tuple>
96 #include <utility>
97 
98 using namespace clang;
99 using namespace sema;
100 
101 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
102                                                     unsigned ByteNo) const {
103   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
104                                Context.getTargetInfo());
105 }
106 
107 /// Checks that a call expression's argument count is the desired number.
108 /// This is useful when doing custom type-checking.  Returns true on error.
109 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
110   unsigned argCount = call->getNumArgs();
111   if (argCount == desiredArgCount) return false;
112 
113   if (argCount < desiredArgCount)
114     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
115         << 0 /*function call*/ << desiredArgCount << argCount
116         << call->getSourceRange();
117 
118   // Highlight all the excess arguments.
119   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
120                     call->getArg(argCount - 1)->getLocEnd());
121 
122   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
123     << 0 /*function call*/ << desiredArgCount << argCount
124     << call->getArg(1)->getSourceRange();
125 }
126 
127 /// Check that the first argument to __builtin_annotation is an integer
128 /// and the second argument is a non-wide string literal.
129 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
130   if (checkArgCount(S, TheCall, 2))
131     return true;
132 
133   // First argument should be an integer.
134   Expr *ValArg = TheCall->getArg(0);
135   QualType Ty = ValArg->getType();
136   if (!Ty->isIntegerType()) {
137     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
138       << ValArg->getSourceRange();
139     return true;
140   }
141 
142   // Second argument should be a constant string.
143   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
144   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
145   if (!Literal || !Literal->isAscii()) {
146     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
147       << StrArg->getSourceRange();
148     return true;
149   }
150 
151   TheCall->setType(Ty);
152   return false;
153 }
154 
155 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
156   // We need at least one argument.
157   if (TheCall->getNumArgs() < 1) {
158     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
159         << 0 << 1 << TheCall->getNumArgs()
160         << TheCall->getCallee()->getSourceRange();
161     return true;
162   }
163 
164   // All arguments should be wide string literals.
165   for (Expr *Arg : TheCall->arguments()) {
166     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
167     if (!Literal || !Literal->isWide()) {
168       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
169           << Arg->getSourceRange();
170       return true;
171     }
172   }
173 
174   return false;
175 }
176 
177 /// Check that the argument to __builtin_addressof is a glvalue, and set the
178 /// result type to the corresponding pointer type.
179 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
180   if (checkArgCount(S, TheCall, 1))
181     return true;
182 
183   ExprResult Arg(TheCall->getArg(0));
184   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
185   if (ResultType.isNull())
186     return true;
187 
188   TheCall->setArg(0, Arg.get());
189   TheCall->setType(ResultType);
190   return false;
191 }
192 
193 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
194   if (checkArgCount(S, TheCall, 3))
195     return true;
196 
197   // First two arguments should be integers.
198   for (unsigned I = 0; I < 2; ++I) {
199     Expr *Arg = TheCall->getArg(I);
200     QualType Ty = Arg->getType();
201     if (!Ty->isIntegerType()) {
202       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
203           << Ty << Arg->getSourceRange();
204       return true;
205     }
206   }
207 
208   // Third argument should be a pointer to a non-const integer.
209   // IRGen correctly handles volatile, restrict, and address spaces, and
210   // the other qualifiers aren't possible.
211   {
212     Expr *Arg = TheCall->getArg(2);
213     QualType Ty = Arg->getType();
214     const auto *PtrTy = Ty->getAs<PointerType>();
215     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
216           !PtrTy->getPointeeType().isConstQualified())) {
217       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
218           << Ty << Arg->getSourceRange();
219       return true;
220     }
221   }
222 
223   return false;
224 }
225 
226 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
227 		                  CallExpr *TheCall, unsigned SizeIdx,
228                                   unsigned DstSizeIdx) {
229   if (TheCall->getNumArgs() <= SizeIdx ||
230       TheCall->getNumArgs() <= DstSizeIdx)
231     return;
232 
233   const Expr *SizeArg = TheCall->getArg(SizeIdx);
234   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
235 
236   llvm::APSInt Size, DstSize;
237 
238   // find out if both sizes are known at compile time
239   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
240       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
241     return;
242 
243   if (Size.ule(DstSize))
244     return;
245 
246   // confirmed overflow so generate the diagnostic.
247   IdentifierInfo *FnName = FDecl->getIdentifier();
248   SourceLocation SL = TheCall->getLocStart();
249   SourceRange SR = TheCall->getSourceRange();
250 
251   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
252 }
253 
254 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
255   if (checkArgCount(S, BuiltinCall, 2))
256     return true;
257 
258   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
259   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
260   Expr *Call = BuiltinCall->getArg(0);
261   Expr *Chain = BuiltinCall->getArg(1);
262 
263   if (Call->getStmtClass() != Stmt::CallExprClass) {
264     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
265         << Call->getSourceRange();
266     return true;
267   }
268 
269   auto CE = cast<CallExpr>(Call);
270   if (CE->getCallee()->getType()->isBlockPointerType()) {
271     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
272         << Call->getSourceRange();
273     return true;
274   }
275 
276   const Decl *TargetDecl = CE->getCalleeDecl();
277   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
278     if (FD->getBuiltinID()) {
279       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
280           << Call->getSourceRange();
281       return true;
282     }
283 
284   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
285     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
286         << Call->getSourceRange();
287     return true;
288   }
289 
290   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
291   if (ChainResult.isInvalid())
292     return true;
293   if (!ChainResult.get()->getType()->isPointerType()) {
294     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
295         << Chain->getSourceRange();
296     return true;
297   }
298 
299   QualType ReturnTy = CE->getCallReturnType(S.Context);
300   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
301   QualType BuiltinTy = S.Context.getFunctionType(
302       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
303   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
304 
305   Builtin =
306       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
307 
308   BuiltinCall->setType(CE->getType());
309   BuiltinCall->setValueKind(CE->getValueKind());
310   BuiltinCall->setObjectKind(CE->getObjectKind());
311   BuiltinCall->setCallee(Builtin);
312   BuiltinCall->setArg(1, ChainResult.get());
313 
314   return false;
315 }
316 
317 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
318                                      Scope::ScopeFlags NeededScopeFlags,
319                                      unsigned DiagID) {
320   // Scopes aren't available during instantiation. Fortunately, builtin
321   // functions cannot be template args so they cannot be formed through template
322   // instantiation. Therefore checking once during the parse is sufficient.
323   if (SemaRef.inTemplateInstantiation())
324     return false;
325 
326   Scope *S = SemaRef.getCurScope();
327   while (S && !S->isSEHExceptScope())
328     S = S->getParent();
329   if (!S || !(S->getFlags() & NeededScopeFlags)) {
330     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
331     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
332         << DRE->getDecl()->getIdentifier();
333     return true;
334   }
335 
336   return false;
337 }
338 
339 static inline bool isBlockPointer(Expr *Arg) {
340   return Arg->getType()->isBlockPointerType();
341 }
342 
343 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
344 /// void*, which is a requirement of device side enqueue.
345 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
346   const BlockPointerType *BPT =
347       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
348   ArrayRef<QualType> Params =
349       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
350   unsigned ArgCounter = 0;
351   bool IllegalParams = false;
352   // Iterate through the block parameters until either one is found that is not
353   // a local void*, or the block is valid.
354   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
355        I != E; ++I, ++ArgCounter) {
356     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
357         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
358             LangAS::opencl_local) {
359       // Get the location of the error. If a block literal has been passed
360       // (BlockExpr) then we can point straight to the offending argument,
361       // else we just point to the variable reference.
362       SourceLocation ErrorLoc;
363       if (isa<BlockExpr>(BlockArg)) {
364         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
365         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
366       } else if (isa<DeclRefExpr>(BlockArg)) {
367         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
368       }
369       S.Diag(ErrorLoc,
370              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
371       IllegalParams = true;
372     }
373   }
374 
375   return IllegalParams;
376 }
377 
378 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
379   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
380     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
381           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
382     return true;
383   }
384   return false;
385 }
386 
387 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
388   if (checkArgCount(S, TheCall, 2))
389     return true;
390 
391   if (checkOpenCLSubgroupExt(S, TheCall))
392     return true;
393 
394   // First argument is an ndrange_t type.
395   Expr *NDRangeArg = TheCall->getArg(0);
396   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
397     S.Diag(NDRangeArg->getLocStart(),
398            diag::err_opencl_builtin_expected_type)
399         << TheCall->getDirectCallee() << "'ndrange_t'";
400     return true;
401   }
402 
403   Expr *BlockArg = TheCall->getArg(1);
404   if (!isBlockPointer(BlockArg)) {
405     S.Diag(BlockArg->getLocStart(),
406            diag::err_opencl_builtin_expected_type)
407         << TheCall->getDirectCallee() << "block";
408     return true;
409   }
410   return checkOpenCLBlockArgs(S, BlockArg);
411 }
412 
413 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
414 /// get_kernel_work_group_size
415 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
416 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
417   if (checkArgCount(S, TheCall, 1))
418     return true;
419 
420   Expr *BlockArg = TheCall->getArg(0);
421   if (!isBlockPointer(BlockArg)) {
422     S.Diag(BlockArg->getLocStart(),
423            diag::err_opencl_builtin_expected_type)
424         << TheCall->getDirectCallee() << "block";
425     return true;
426   }
427   return checkOpenCLBlockArgs(S, BlockArg);
428 }
429 
430 /// Diagnose integer type and any valid implicit conversion to it.
431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
432                                       const QualType &IntType);
433 
434 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
435                                             unsigned Start, unsigned End) {
436   bool IllegalParams = false;
437   for (unsigned I = Start; I <= End; ++I)
438     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
439                                               S.Context.getSizeType());
440   return IllegalParams;
441 }
442 
443 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
444 /// 'local void*' parameter of passed block.
445 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
446                                            Expr *BlockArg,
447                                            unsigned NumNonVarArgs) {
448   const BlockPointerType *BPT =
449       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
450   unsigned NumBlockParams =
451       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
452   unsigned TotalNumArgs = TheCall->getNumArgs();
453 
454   // For each argument passed to the block, a corresponding uint needs to
455   // be passed to describe the size of the local memory.
456   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
457     S.Diag(TheCall->getLocStart(),
458            diag::err_opencl_enqueue_kernel_local_size_args);
459     return true;
460   }
461 
462   // Check that the sizes of the local memory are specified by integers.
463   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
464                                          TotalNumArgs - 1);
465 }
466 
467 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
468 /// overload formats specified in Table 6.13.17.1.
469 /// int enqueue_kernel(queue_t queue,
470 ///                    kernel_enqueue_flags_t flags,
471 ///                    const ndrange_t ndrange,
472 ///                    void (^block)(void))
473 /// int enqueue_kernel(queue_t queue,
474 ///                    kernel_enqueue_flags_t flags,
475 ///                    const ndrange_t ndrange,
476 ///                    uint num_events_in_wait_list,
477 ///                    clk_event_t *event_wait_list,
478 ///                    clk_event_t *event_ret,
479 ///                    void (^block)(void))
480 /// int enqueue_kernel(queue_t queue,
481 ///                    kernel_enqueue_flags_t flags,
482 ///                    const ndrange_t ndrange,
483 ///                    void (^block)(local void*, ...),
484 ///                    uint size0, ...)
485 /// int enqueue_kernel(queue_t queue,
486 ///                    kernel_enqueue_flags_t flags,
487 ///                    const ndrange_t ndrange,
488 ///                    uint num_events_in_wait_list,
489 ///                    clk_event_t *event_wait_list,
490 ///                    clk_event_t *event_ret,
491 ///                    void (^block)(local void*, ...),
492 ///                    uint size0, ...)
493 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
494   unsigned NumArgs = TheCall->getNumArgs();
495 
496   if (NumArgs < 4) {
497     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
498     return true;
499   }
500 
501   Expr *Arg0 = TheCall->getArg(0);
502   Expr *Arg1 = TheCall->getArg(1);
503   Expr *Arg2 = TheCall->getArg(2);
504   Expr *Arg3 = TheCall->getArg(3);
505 
506   // First argument always needs to be a queue_t type.
507   if (!Arg0->getType()->isQueueT()) {
508     S.Diag(TheCall->getArg(0)->getLocStart(),
509            diag::err_opencl_builtin_expected_type)
510         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
511     return true;
512   }
513 
514   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
515   if (!Arg1->getType()->isIntegerType()) {
516     S.Diag(TheCall->getArg(1)->getLocStart(),
517            diag::err_opencl_builtin_expected_type)
518         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
519     return true;
520   }
521 
522   // Third argument is always an ndrange_t type.
523   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
524     S.Diag(TheCall->getArg(2)->getLocStart(),
525            diag::err_opencl_builtin_expected_type)
526         << TheCall->getDirectCallee() << "'ndrange_t'";
527     return true;
528   }
529 
530   // With four arguments, there is only one form that the function could be
531   // called in: no events and no variable arguments.
532   if (NumArgs == 4) {
533     // check that the last argument is the right block type.
534     if (!isBlockPointer(Arg3)) {
535       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
536           << TheCall->getDirectCallee() << "block";
537       return true;
538     }
539     // we have a block type, check the prototype
540     const BlockPointerType *BPT =
541         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
542     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
543       S.Diag(Arg3->getLocStart(),
544              diag::err_opencl_enqueue_kernel_blocks_no_args);
545       return true;
546     }
547     return false;
548   }
549   // we can have block + varargs.
550   if (isBlockPointer(Arg3))
551     return (checkOpenCLBlockArgs(S, Arg3) ||
552             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
553   // last two cases with either exactly 7 args or 7 args and varargs.
554   if (NumArgs >= 7) {
555     // check common block argument.
556     Expr *Arg6 = TheCall->getArg(6);
557     if (!isBlockPointer(Arg6)) {
558       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
559           << TheCall->getDirectCallee() << "block";
560       return true;
561     }
562     if (checkOpenCLBlockArgs(S, Arg6))
563       return true;
564 
565     // Forth argument has to be any integer type.
566     if (!Arg3->getType()->isIntegerType()) {
567       S.Diag(TheCall->getArg(3)->getLocStart(),
568              diag::err_opencl_builtin_expected_type)
569           << TheCall->getDirectCallee() << "integer";
570       return true;
571     }
572     // check remaining common arguments.
573     Expr *Arg4 = TheCall->getArg(4);
574     Expr *Arg5 = TheCall->getArg(5);
575 
576     // Fifth argument is always passed as a pointer to clk_event_t.
577     if (!Arg4->isNullPointerConstant(S.Context,
578                                      Expr::NPC_ValueDependentIsNotNull) &&
579         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
580       S.Diag(TheCall->getArg(4)->getLocStart(),
581              diag::err_opencl_builtin_expected_type)
582           << TheCall->getDirectCallee()
583           << S.Context.getPointerType(S.Context.OCLClkEventTy);
584       return true;
585     }
586 
587     // Sixth argument is always passed as a pointer to clk_event_t.
588     if (!Arg5->isNullPointerConstant(S.Context,
589                                      Expr::NPC_ValueDependentIsNotNull) &&
590         !(Arg5->getType()->isPointerType() &&
591           Arg5->getType()->getPointeeType()->isClkEventT())) {
592       S.Diag(TheCall->getArg(5)->getLocStart(),
593              diag::err_opencl_builtin_expected_type)
594           << TheCall->getDirectCallee()
595           << S.Context.getPointerType(S.Context.OCLClkEventTy);
596       return true;
597     }
598 
599     if (NumArgs == 7)
600       return false;
601 
602     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
603   }
604 
605   // None of the specific case has been detected, give generic error
606   S.Diag(TheCall->getLocStart(),
607          diag::err_opencl_enqueue_kernel_incorrect_args);
608   return true;
609 }
610 
611 /// Returns OpenCL access qual.
612 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
613     return D->getAttr<OpenCLAccessAttr>();
614 }
615 
616 /// Returns true if pipe element type is different from the pointer.
617 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
618   const Expr *Arg0 = Call->getArg(0);
619   // First argument type should always be pipe.
620   if (!Arg0->getType()->isPipeType()) {
621     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
622         << Call->getDirectCallee() << Arg0->getSourceRange();
623     return true;
624   }
625   OpenCLAccessAttr *AccessQual =
626       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
627   // Validates the access qualifier is compatible with the call.
628   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
629   // read_only and write_only, and assumed to be read_only if no qualifier is
630   // specified.
631   switch (Call->getDirectCallee()->getBuiltinID()) {
632   case Builtin::BIread_pipe:
633   case Builtin::BIreserve_read_pipe:
634   case Builtin::BIcommit_read_pipe:
635   case Builtin::BIwork_group_reserve_read_pipe:
636   case Builtin::BIsub_group_reserve_read_pipe:
637   case Builtin::BIwork_group_commit_read_pipe:
638   case Builtin::BIsub_group_commit_read_pipe:
639     if (!(!AccessQual || AccessQual->isReadOnly())) {
640       S.Diag(Arg0->getLocStart(),
641              diag::err_opencl_builtin_pipe_invalid_access_modifier)
642           << "read_only" << Arg0->getSourceRange();
643       return true;
644     }
645     break;
646   case Builtin::BIwrite_pipe:
647   case Builtin::BIreserve_write_pipe:
648   case Builtin::BIcommit_write_pipe:
649   case Builtin::BIwork_group_reserve_write_pipe:
650   case Builtin::BIsub_group_reserve_write_pipe:
651   case Builtin::BIwork_group_commit_write_pipe:
652   case Builtin::BIsub_group_commit_write_pipe:
653     if (!(AccessQual && AccessQual->isWriteOnly())) {
654       S.Diag(Arg0->getLocStart(),
655              diag::err_opencl_builtin_pipe_invalid_access_modifier)
656           << "write_only" << Arg0->getSourceRange();
657       return true;
658     }
659     break;
660   default:
661     break;
662   }
663   return false;
664 }
665 
666 /// Returns true if pipe element type is different from the pointer.
667 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
668   const Expr *Arg0 = Call->getArg(0);
669   const Expr *ArgIdx = Call->getArg(Idx);
670   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
671   const QualType EltTy = PipeTy->getElementType();
672   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
673   // The Idx argument should be a pointer and the type of the pointer and
674   // the type of pipe element should also be the same.
675   if (!ArgTy ||
676       !S.Context.hasSameType(
677           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
678     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
679         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
680         << ArgIdx->getType() << ArgIdx->getSourceRange();
681     return true;
682   }
683   return false;
684 }
685 
686 // \brief Performs semantic analysis for the read/write_pipe call.
687 // \param S Reference to the semantic analyzer.
688 // \param Call A pointer to the builtin call.
689 // \return True if a semantic error has been found, false otherwise.
690 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
691   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
692   // functions have two forms.
693   switch (Call->getNumArgs()) {
694   case 2:
695     if (checkOpenCLPipeArg(S, Call))
696       return true;
697     // The call with 2 arguments should be
698     // read/write_pipe(pipe T, T*).
699     // Check packet type T.
700     if (checkOpenCLPipePacketType(S, Call, 1))
701       return true;
702     break;
703 
704   case 4: {
705     if (checkOpenCLPipeArg(S, Call))
706       return true;
707     // The call with 4 arguments should be
708     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
709     // Check reserve_id_t.
710     if (!Call->getArg(1)->getType()->isReserveIDT()) {
711       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
712           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
713           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
714       return true;
715     }
716 
717     // Check the index.
718     const Expr *Arg2 = Call->getArg(2);
719     if (!Arg2->getType()->isIntegerType() &&
720         !Arg2->getType()->isUnsignedIntegerType()) {
721       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
722           << Call->getDirectCallee() << S.Context.UnsignedIntTy
723           << Arg2->getType() << Arg2->getSourceRange();
724       return true;
725     }
726 
727     // Check packet type T.
728     if (checkOpenCLPipePacketType(S, Call, 3))
729       return true;
730   } break;
731   default:
732     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
733         << Call->getDirectCallee() << Call->getSourceRange();
734     return true;
735   }
736 
737   return false;
738 }
739 
740 // \brief Performs a semantic analysis on the {work_group_/sub_group_
741 //        /_}reserve_{read/write}_pipe
742 // \param S Reference to the semantic analyzer.
743 // \param Call The call to the builtin function to be analyzed.
744 // \return True if a semantic error was found, false otherwise.
745 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
746   if (checkArgCount(S, Call, 2))
747     return true;
748 
749   if (checkOpenCLPipeArg(S, Call))
750     return true;
751 
752   // Check the reserve size.
753   if (!Call->getArg(1)->getType()->isIntegerType() &&
754       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
755     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
756         << Call->getDirectCallee() << S.Context.UnsignedIntTy
757         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
758     return true;
759   }
760 
761   // Since return type of reserve_read/write_pipe built-in function is
762   // reserve_id_t, which is not defined in the builtin def file , we used int
763   // as return type and need to override the return type of these functions.
764   Call->setType(S.Context.OCLReserveIDTy);
765 
766   return false;
767 }
768 
769 // \brief Performs a semantic analysis on {work_group_/sub_group_
770 //        /_}commit_{read/write}_pipe
771 // \param S Reference to the semantic analyzer.
772 // \param Call The call to the builtin function to be analyzed.
773 // \return True if a semantic error was found, false otherwise.
774 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
775   if (checkArgCount(S, Call, 2))
776     return true;
777 
778   if (checkOpenCLPipeArg(S, Call))
779     return true;
780 
781   // Check reserve_id_t.
782   if (!Call->getArg(1)->getType()->isReserveIDT()) {
783     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
784         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
785         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
786     return true;
787   }
788 
789   return false;
790 }
791 
792 // \brief Performs a semantic analysis on the call to built-in Pipe
793 //        Query Functions.
794 // \param S Reference to the semantic analyzer.
795 // \param Call The call to the builtin function to be analyzed.
796 // \return True if a semantic error was found, false otherwise.
797 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
798   if (checkArgCount(S, Call, 1))
799     return true;
800 
801   if (!Call->getArg(0)->getType()->isPipeType()) {
802     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
803         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
804     return true;
805   }
806 
807   return false;
808 }
809 
810 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
811 // \brief Performs semantic analysis for the to_global/local/private call.
812 // \param S Reference to the semantic analyzer.
813 // \param BuiltinID ID of the builtin function.
814 // \param Call A pointer to the builtin call.
815 // \return True if a semantic error has been found, false otherwise.
816 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
817                                     CallExpr *Call) {
818   if (Call->getNumArgs() != 1) {
819     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
820         << Call->getDirectCallee() << Call->getSourceRange();
821     return true;
822   }
823 
824   auto RT = Call->getArg(0)->getType();
825   if (!RT->isPointerType() || RT->getPointeeType()
826       .getAddressSpace() == LangAS::opencl_constant) {
827     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
828         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
829     return true;
830   }
831 
832   RT = RT->getPointeeType();
833   auto Qual = RT.getQualifiers();
834   switch (BuiltinID) {
835   case Builtin::BIto_global:
836     Qual.setAddressSpace(LangAS::opencl_global);
837     break;
838   case Builtin::BIto_local:
839     Qual.setAddressSpace(LangAS::opencl_local);
840     break;
841   case Builtin::BIto_private:
842     Qual.setAddressSpace(LangAS::opencl_private);
843     break;
844   default:
845     llvm_unreachable("Invalid builtin function");
846   }
847   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
848       RT.getUnqualifiedType(), Qual)));
849 
850   return false;
851 }
852 
853 ExprResult
854 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
855                                CallExpr *TheCall) {
856   ExprResult TheCallResult(TheCall);
857 
858   // Find out if any arguments are required to be integer constant expressions.
859   unsigned ICEArguments = 0;
860   ASTContext::GetBuiltinTypeError Error;
861   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
862   if (Error != ASTContext::GE_None)
863     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
864 
865   // If any arguments are required to be ICE's, check and diagnose.
866   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
867     // Skip arguments not required to be ICE's.
868     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
869 
870     llvm::APSInt Result;
871     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
872       return true;
873     ICEArguments &= ~(1 << ArgNo);
874   }
875 
876   switch (BuiltinID) {
877   case Builtin::BI__builtin___CFStringMakeConstantString:
878     assert(TheCall->getNumArgs() == 1 &&
879            "Wrong # arguments to builtin CFStringMakeConstantString");
880     if (CheckObjCString(TheCall->getArg(0)))
881       return ExprError();
882     break;
883   case Builtin::BI__builtin_ms_va_start:
884   case Builtin::BI__builtin_stdarg_start:
885   case Builtin::BI__builtin_va_start:
886     if (SemaBuiltinVAStart(BuiltinID, TheCall))
887       return ExprError();
888     break;
889   case Builtin::BI__va_start: {
890     switch (Context.getTargetInfo().getTriple().getArch()) {
891     case llvm::Triple::arm:
892     case llvm::Triple::thumb:
893       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
894         return ExprError();
895       break;
896     default:
897       if (SemaBuiltinVAStart(BuiltinID, TheCall))
898         return ExprError();
899       break;
900     }
901     break;
902   }
903   case Builtin::BI__builtin_isgreater:
904   case Builtin::BI__builtin_isgreaterequal:
905   case Builtin::BI__builtin_isless:
906   case Builtin::BI__builtin_islessequal:
907   case Builtin::BI__builtin_islessgreater:
908   case Builtin::BI__builtin_isunordered:
909     if (SemaBuiltinUnorderedCompare(TheCall))
910       return ExprError();
911     break;
912   case Builtin::BI__builtin_fpclassify:
913     if (SemaBuiltinFPClassification(TheCall, 6))
914       return ExprError();
915     break;
916   case Builtin::BI__builtin_isfinite:
917   case Builtin::BI__builtin_isinf:
918   case Builtin::BI__builtin_isinf_sign:
919   case Builtin::BI__builtin_isnan:
920   case Builtin::BI__builtin_isnormal:
921     if (SemaBuiltinFPClassification(TheCall, 1))
922       return ExprError();
923     break;
924   case Builtin::BI__builtin_shufflevector:
925     return SemaBuiltinShuffleVector(TheCall);
926     // TheCall will be freed by the smart pointer here, but that's fine, since
927     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
928   case Builtin::BI__builtin_prefetch:
929     if (SemaBuiltinPrefetch(TheCall))
930       return ExprError();
931     break;
932   case Builtin::BI__builtin_alloca_with_align:
933     if (SemaBuiltinAllocaWithAlign(TheCall))
934       return ExprError();
935     break;
936   case Builtin::BI__assume:
937   case Builtin::BI__builtin_assume:
938     if (SemaBuiltinAssume(TheCall))
939       return ExprError();
940     break;
941   case Builtin::BI__builtin_assume_aligned:
942     if (SemaBuiltinAssumeAligned(TheCall))
943       return ExprError();
944     break;
945   case Builtin::BI__builtin_object_size:
946     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
947       return ExprError();
948     break;
949   case Builtin::BI__builtin_longjmp:
950     if (SemaBuiltinLongjmp(TheCall))
951       return ExprError();
952     break;
953   case Builtin::BI__builtin_setjmp:
954     if (SemaBuiltinSetjmp(TheCall))
955       return ExprError();
956     break;
957   case Builtin::BI_setjmp:
958   case Builtin::BI_setjmpex:
959     if (checkArgCount(*this, TheCall, 1))
960       return true;
961     break;
962   case Builtin::BI__builtin_classify_type:
963     if (checkArgCount(*this, TheCall, 1)) return true;
964     TheCall->setType(Context.IntTy);
965     break;
966   case Builtin::BI__builtin_constant_p:
967     if (checkArgCount(*this, TheCall, 1)) return true;
968     TheCall->setType(Context.IntTy);
969     break;
970   case Builtin::BI__sync_fetch_and_add:
971   case Builtin::BI__sync_fetch_and_add_1:
972   case Builtin::BI__sync_fetch_and_add_2:
973   case Builtin::BI__sync_fetch_and_add_4:
974   case Builtin::BI__sync_fetch_and_add_8:
975   case Builtin::BI__sync_fetch_and_add_16:
976   case Builtin::BI__sync_fetch_and_sub:
977   case Builtin::BI__sync_fetch_and_sub_1:
978   case Builtin::BI__sync_fetch_and_sub_2:
979   case Builtin::BI__sync_fetch_and_sub_4:
980   case Builtin::BI__sync_fetch_and_sub_8:
981   case Builtin::BI__sync_fetch_and_sub_16:
982   case Builtin::BI__sync_fetch_and_or:
983   case Builtin::BI__sync_fetch_and_or_1:
984   case Builtin::BI__sync_fetch_and_or_2:
985   case Builtin::BI__sync_fetch_and_or_4:
986   case Builtin::BI__sync_fetch_and_or_8:
987   case Builtin::BI__sync_fetch_and_or_16:
988   case Builtin::BI__sync_fetch_and_and:
989   case Builtin::BI__sync_fetch_and_and_1:
990   case Builtin::BI__sync_fetch_and_and_2:
991   case Builtin::BI__sync_fetch_and_and_4:
992   case Builtin::BI__sync_fetch_and_and_8:
993   case Builtin::BI__sync_fetch_and_and_16:
994   case Builtin::BI__sync_fetch_and_xor:
995   case Builtin::BI__sync_fetch_and_xor_1:
996   case Builtin::BI__sync_fetch_and_xor_2:
997   case Builtin::BI__sync_fetch_and_xor_4:
998   case Builtin::BI__sync_fetch_and_xor_8:
999   case Builtin::BI__sync_fetch_and_xor_16:
1000   case Builtin::BI__sync_fetch_and_nand:
1001   case Builtin::BI__sync_fetch_and_nand_1:
1002   case Builtin::BI__sync_fetch_and_nand_2:
1003   case Builtin::BI__sync_fetch_and_nand_4:
1004   case Builtin::BI__sync_fetch_and_nand_8:
1005   case Builtin::BI__sync_fetch_and_nand_16:
1006   case Builtin::BI__sync_add_and_fetch:
1007   case Builtin::BI__sync_add_and_fetch_1:
1008   case Builtin::BI__sync_add_and_fetch_2:
1009   case Builtin::BI__sync_add_and_fetch_4:
1010   case Builtin::BI__sync_add_and_fetch_8:
1011   case Builtin::BI__sync_add_and_fetch_16:
1012   case Builtin::BI__sync_sub_and_fetch:
1013   case Builtin::BI__sync_sub_and_fetch_1:
1014   case Builtin::BI__sync_sub_and_fetch_2:
1015   case Builtin::BI__sync_sub_and_fetch_4:
1016   case Builtin::BI__sync_sub_and_fetch_8:
1017   case Builtin::BI__sync_sub_and_fetch_16:
1018   case Builtin::BI__sync_and_and_fetch:
1019   case Builtin::BI__sync_and_and_fetch_1:
1020   case Builtin::BI__sync_and_and_fetch_2:
1021   case Builtin::BI__sync_and_and_fetch_4:
1022   case Builtin::BI__sync_and_and_fetch_8:
1023   case Builtin::BI__sync_and_and_fetch_16:
1024   case Builtin::BI__sync_or_and_fetch:
1025   case Builtin::BI__sync_or_and_fetch_1:
1026   case Builtin::BI__sync_or_and_fetch_2:
1027   case Builtin::BI__sync_or_and_fetch_4:
1028   case Builtin::BI__sync_or_and_fetch_8:
1029   case Builtin::BI__sync_or_and_fetch_16:
1030   case Builtin::BI__sync_xor_and_fetch:
1031   case Builtin::BI__sync_xor_and_fetch_1:
1032   case Builtin::BI__sync_xor_and_fetch_2:
1033   case Builtin::BI__sync_xor_and_fetch_4:
1034   case Builtin::BI__sync_xor_and_fetch_8:
1035   case Builtin::BI__sync_xor_and_fetch_16:
1036   case Builtin::BI__sync_nand_and_fetch:
1037   case Builtin::BI__sync_nand_and_fetch_1:
1038   case Builtin::BI__sync_nand_and_fetch_2:
1039   case Builtin::BI__sync_nand_and_fetch_4:
1040   case Builtin::BI__sync_nand_and_fetch_8:
1041   case Builtin::BI__sync_nand_and_fetch_16:
1042   case Builtin::BI__sync_val_compare_and_swap:
1043   case Builtin::BI__sync_val_compare_and_swap_1:
1044   case Builtin::BI__sync_val_compare_and_swap_2:
1045   case Builtin::BI__sync_val_compare_and_swap_4:
1046   case Builtin::BI__sync_val_compare_and_swap_8:
1047   case Builtin::BI__sync_val_compare_and_swap_16:
1048   case Builtin::BI__sync_bool_compare_and_swap:
1049   case Builtin::BI__sync_bool_compare_and_swap_1:
1050   case Builtin::BI__sync_bool_compare_and_swap_2:
1051   case Builtin::BI__sync_bool_compare_and_swap_4:
1052   case Builtin::BI__sync_bool_compare_and_swap_8:
1053   case Builtin::BI__sync_bool_compare_and_swap_16:
1054   case Builtin::BI__sync_lock_test_and_set:
1055   case Builtin::BI__sync_lock_test_and_set_1:
1056   case Builtin::BI__sync_lock_test_and_set_2:
1057   case Builtin::BI__sync_lock_test_and_set_4:
1058   case Builtin::BI__sync_lock_test_and_set_8:
1059   case Builtin::BI__sync_lock_test_and_set_16:
1060   case Builtin::BI__sync_lock_release:
1061   case Builtin::BI__sync_lock_release_1:
1062   case Builtin::BI__sync_lock_release_2:
1063   case Builtin::BI__sync_lock_release_4:
1064   case Builtin::BI__sync_lock_release_8:
1065   case Builtin::BI__sync_lock_release_16:
1066   case Builtin::BI__sync_swap:
1067   case Builtin::BI__sync_swap_1:
1068   case Builtin::BI__sync_swap_2:
1069   case Builtin::BI__sync_swap_4:
1070   case Builtin::BI__sync_swap_8:
1071   case Builtin::BI__sync_swap_16:
1072     return SemaBuiltinAtomicOverloaded(TheCallResult);
1073   case Builtin::BI__builtin_nontemporal_load:
1074   case Builtin::BI__builtin_nontemporal_store:
1075     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1076 #define BUILTIN(ID, TYPE, ATTRS)
1077 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1078   case Builtin::BI##ID: \
1079     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1080 #include "clang/Basic/Builtins.def"
1081   case Builtin::BI__annotation:
1082     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1083       return ExprError();
1084     break;
1085   case Builtin::BI__builtin_annotation:
1086     if (SemaBuiltinAnnotation(*this, TheCall))
1087       return ExprError();
1088     break;
1089   case Builtin::BI__builtin_addressof:
1090     if (SemaBuiltinAddressof(*this, TheCall))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__builtin_add_overflow:
1094   case Builtin::BI__builtin_sub_overflow:
1095   case Builtin::BI__builtin_mul_overflow:
1096     if (SemaBuiltinOverflow(*this, TheCall))
1097       return ExprError();
1098     break;
1099   case Builtin::BI__builtin_operator_new:
1100   case Builtin::BI__builtin_operator_delete:
1101     if (!getLangOpts().CPlusPlus) {
1102       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1103         << (BuiltinID == Builtin::BI__builtin_operator_new
1104                 ? "__builtin_operator_new"
1105                 : "__builtin_operator_delete")
1106         << "C++";
1107       return ExprError();
1108     }
1109     // CodeGen assumes it can find the global new and delete to call,
1110     // so ensure that they are declared.
1111     DeclareGlobalNewDelete();
1112     break;
1113 
1114   // check secure string manipulation functions where overflows
1115   // are detectable at compile time
1116   case Builtin::BI__builtin___memcpy_chk:
1117   case Builtin::BI__builtin___memmove_chk:
1118   case Builtin::BI__builtin___memset_chk:
1119   case Builtin::BI__builtin___strlcat_chk:
1120   case Builtin::BI__builtin___strlcpy_chk:
1121   case Builtin::BI__builtin___strncat_chk:
1122   case Builtin::BI__builtin___strncpy_chk:
1123   case Builtin::BI__builtin___stpncpy_chk:
1124     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1125     break;
1126   case Builtin::BI__builtin___memccpy_chk:
1127     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1128     break;
1129   case Builtin::BI__builtin___snprintf_chk:
1130   case Builtin::BI__builtin___vsnprintf_chk:
1131     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1132     break;
1133   case Builtin::BI__builtin_call_with_static_chain:
1134     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1135       return ExprError();
1136     break;
1137   case Builtin::BI__exception_code:
1138   case Builtin::BI_exception_code:
1139     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1140                                  diag::err_seh___except_block))
1141       return ExprError();
1142     break;
1143   case Builtin::BI__exception_info:
1144   case Builtin::BI_exception_info:
1145     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1146                                  diag::err_seh___except_filter))
1147       return ExprError();
1148     break;
1149   case Builtin::BI__GetExceptionInfo:
1150     if (checkArgCount(*this, TheCall, 1))
1151       return ExprError();
1152 
1153     if (CheckCXXThrowOperand(
1154             TheCall->getLocStart(),
1155             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1156             TheCall))
1157       return ExprError();
1158 
1159     TheCall->setType(Context.VoidPtrTy);
1160     break;
1161   // OpenCL v2.0, s6.13.16 - Pipe functions
1162   case Builtin::BIread_pipe:
1163   case Builtin::BIwrite_pipe:
1164     // Since those two functions are declared with var args, we need a semantic
1165     // check for the argument.
1166     if (SemaBuiltinRWPipe(*this, TheCall))
1167       return ExprError();
1168     TheCall->setType(Context.IntTy);
1169     break;
1170   case Builtin::BIreserve_read_pipe:
1171   case Builtin::BIreserve_write_pipe:
1172   case Builtin::BIwork_group_reserve_read_pipe:
1173   case Builtin::BIwork_group_reserve_write_pipe:
1174     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1175       return ExprError();
1176     break;
1177   case Builtin::BIsub_group_reserve_read_pipe:
1178   case Builtin::BIsub_group_reserve_write_pipe:
1179     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1180         SemaBuiltinReserveRWPipe(*this, TheCall))
1181       return ExprError();
1182     break;
1183   case Builtin::BIcommit_read_pipe:
1184   case Builtin::BIcommit_write_pipe:
1185   case Builtin::BIwork_group_commit_read_pipe:
1186   case Builtin::BIwork_group_commit_write_pipe:
1187     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1188       return ExprError();
1189     break;
1190   case Builtin::BIsub_group_commit_read_pipe:
1191   case Builtin::BIsub_group_commit_write_pipe:
1192     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1193         SemaBuiltinCommitRWPipe(*this, TheCall))
1194       return ExprError();
1195     break;
1196   case Builtin::BIget_pipe_num_packets:
1197   case Builtin::BIget_pipe_max_packets:
1198     if (SemaBuiltinPipePackets(*this, TheCall))
1199       return ExprError();
1200     TheCall->setType(Context.UnsignedIntTy);
1201     break;
1202   case Builtin::BIto_global:
1203   case Builtin::BIto_local:
1204   case Builtin::BIto_private:
1205     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1206       return ExprError();
1207     break;
1208   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1209   case Builtin::BIenqueue_kernel:
1210     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1211       return ExprError();
1212     break;
1213   case Builtin::BIget_kernel_work_group_size:
1214   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1215     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1216       return ExprError();
1217     break;
1218     break;
1219   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1220   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1221     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1222       return ExprError();
1223     break;
1224   case Builtin::BI__builtin_os_log_format:
1225   case Builtin::BI__builtin_os_log_format_buffer_size:
1226     if (SemaBuiltinOSLogFormat(TheCall))
1227       return ExprError();
1228     break;
1229   }
1230 
1231   // Since the target specific builtins for each arch overlap, only check those
1232   // of the arch we are compiling for.
1233   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1234     switch (Context.getTargetInfo().getTriple().getArch()) {
1235       case llvm::Triple::arm:
1236       case llvm::Triple::armeb:
1237       case llvm::Triple::thumb:
1238       case llvm::Triple::thumbeb:
1239         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1240           return ExprError();
1241         break;
1242       case llvm::Triple::aarch64:
1243       case llvm::Triple::aarch64_be:
1244         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1245           return ExprError();
1246         break;
1247       case llvm::Triple::mips:
1248       case llvm::Triple::mipsel:
1249       case llvm::Triple::mips64:
1250       case llvm::Triple::mips64el:
1251         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1252           return ExprError();
1253         break;
1254       case llvm::Triple::systemz:
1255         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1256           return ExprError();
1257         break;
1258       case llvm::Triple::x86:
1259       case llvm::Triple::x86_64:
1260         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1261           return ExprError();
1262         break;
1263       case llvm::Triple::ppc:
1264       case llvm::Triple::ppc64:
1265       case llvm::Triple::ppc64le:
1266         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1267           return ExprError();
1268         break;
1269       default:
1270         break;
1271     }
1272   }
1273 
1274   return TheCallResult;
1275 }
1276 
1277 // Get the valid immediate range for the specified NEON type code.
1278 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1279   NeonTypeFlags Type(t);
1280   int IsQuad = ForceQuad ? true : Type.isQuad();
1281   switch (Type.getEltType()) {
1282   case NeonTypeFlags::Int8:
1283   case NeonTypeFlags::Poly8:
1284     return shift ? 7 : (8 << IsQuad) - 1;
1285   case NeonTypeFlags::Int16:
1286   case NeonTypeFlags::Poly16:
1287     return shift ? 15 : (4 << IsQuad) - 1;
1288   case NeonTypeFlags::Int32:
1289     return shift ? 31 : (2 << IsQuad) - 1;
1290   case NeonTypeFlags::Int64:
1291   case NeonTypeFlags::Poly64:
1292     return shift ? 63 : (1 << IsQuad) - 1;
1293   case NeonTypeFlags::Poly128:
1294     return shift ? 127 : (1 << IsQuad) - 1;
1295   case NeonTypeFlags::Float16:
1296     assert(!shift && "cannot shift float types!");
1297     return (4 << IsQuad) - 1;
1298   case NeonTypeFlags::Float32:
1299     assert(!shift && "cannot shift float types!");
1300     return (2 << IsQuad) - 1;
1301   case NeonTypeFlags::Float64:
1302     assert(!shift && "cannot shift float types!");
1303     return (1 << IsQuad) - 1;
1304   }
1305   llvm_unreachable("Invalid NeonTypeFlag!");
1306 }
1307 
1308 /// getNeonEltType - Return the QualType corresponding to the elements of
1309 /// the vector type specified by the NeonTypeFlags.  This is used to check
1310 /// the pointer arguments for Neon load/store intrinsics.
1311 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1312                                bool IsPolyUnsigned, bool IsInt64Long) {
1313   switch (Flags.getEltType()) {
1314   case NeonTypeFlags::Int8:
1315     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1316   case NeonTypeFlags::Int16:
1317     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1318   case NeonTypeFlags::Int32:
1319     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1320   case NeonTypeFlags::Int64:
1321     if (IsInt64Long)
1322       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1323     else
1324       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1325                                 : Context.LongLongTy;
1326   case NeonTypeFlags::Poly8:
1327     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1328   case NeonTypeFlags::Poly16:
1329     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1330   case NeonTypeFlags::Poly64:
1331     if (IsInt64Long)
1332       return Context.UnsignedLongTy;
1333     else
1334       return Context.UnsignedLongLongTy;
1335   case NeonTypeFlags::Poly128:
1336     break;
1337   case NeonTypeFlags::Float16:
1338     return Context.HalfTy;
1339   case NeonTypeFlags::Float32:
1340     return Context.FloatTy;
1341   case NeonTypeFlags::Float64:
1342     return Context.DoubleTy;
1343   }
1344   llvm_unreachable("Invalid NeonTypeFlag!");
1345 }
1346 
1347 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1348   llvm::APSInt Result;
1349   uint64_t mask = 0;
1350   unsigned TV = 0;
1351   int PtrArgNum = -1;
1352   bool HasConstPtr = false;
1353   switch (BuiltinID) {
1354 #define GET_NEON_OVERLOAD_CHECK
1355 #include "clang/Basic/arm_neon.inc"
1356 #undef GET_NEON_OVERLOAD_CHECK
1357   }
1358 
1359   // For NEON intrinsics which are overloaded on vector element type, validate
1360   // the immediate which specifies which variant to emit.
1361   unsigned ImmArg = TheCall->getNumArgs()-1;
1362   if (mask) {
1363     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1364       return true;
1365 
1366     TV = Result.getLimitedValue(64);
1367     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1368       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1369         << TheCall->getArg(ImmArg)->getSourceRange();
1370   }
1371 
1372   if (PtrArgNum >= 0) {
1373     // Check that pointer arguments have the specified type.
1374     Expr *Arg = TheCall->getArg(PtrArgNum);
1375     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1376       Arg = ICE->getSubExpr();
1377     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1378     QualType RHSTy = RHS.get()->getType();
1379 
1380     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1381     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1382                           Arch == llvm::Triple::aarch64_be;
1383     bool IsInt64Long =
1384         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1385     QualType EltTy =
1386         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1387     if (HasConstPtr)
1388       EltTy = EltTy.withConst();
1389     QualType LHSTy = Context.getPointerType(EltTy);
1390     AssignConvertType ConvTy;
1391     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1392     if (RHS.isInvalid())
1393       return true;
1394     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1395                                  RHS.get(), AA_Assigning))
1396       return true;
1397   }
1398 
1399   // For NEON intrinsics which take an immediate value as part of the
1400   // instruction, range check them here.
1401   unsigned i = 0, l = 0, u = 0;
1402   switch (BuiltinID) {
1403   default:
1404     return false;
1405 #define GET_NEON_IMMEDIATE_CHECK
1406 #include "clang/Basic/arm_neon.inc"
1407 #undef GET_NEON_IMMEDIATE_CHECK
1408   }
1409 
1410   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1411 }
1412 
1413 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1414                                         unsigned MaxWidth) {
1415   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1416           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1417           BuiltinID == ARM::BI__builtin_arm_strex ||
1418           BuiltinID == ARM::BI__builtin_arm_stlex ||
1419           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1420           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1421           BuiltinID == AArch64::BI__builtin_arm_strex ||
1422           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1423          "unexpected ARM builtin");
1424   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1425                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1426                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1427                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1428 
1429   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1430 
1431   // Ensure that we have the proper number of arguments.
1432   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1433     return true;
1434 
1435   // Inspect the pointer argument of the atomic builtin.  This should always be
1436   // a pointer type, whose element is an integral scalar or pointer type.
1437   // Because it is a pointer type, we don't have to worry about any implicit
1438   // casts here.
1439   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1440   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1441   if (PointerArgRes.isInvalid())
1442     return true;
1443   PointerArg = PointerArgRes.get();
1444 
1445   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1446   if (!pointerType) {
1447     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1448       << PointerArg->getType() << PointerArg->getSourceRange();
1449     return true;
1450   }
1451 
1452   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1453   // task is to insert the appropriate casts into the AST. First work out just
1454   // what the appropriate type is.
1455   QualType ValType = pointerType->getPointeeType();
1456   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1457   if (IsLdrex)
1458     AddrType.addConst();
1459 
1460   // Issue a warning if the cast is dodgy.
1461   CastKind CastNeeded = CK_NoOp;
1462   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1463     CastNeeded = CK_BitCast;
1464     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1465       << PointerArg->getType()
1466       << Context.getPointerType(AddrType)
1467       << AA_Passing << PointerArg->getSourceRange();
1468   }
1469 
1470   // Finally, do the cast and replace the argument with the corrected version.
1471   AddrType = Context.getPointerType(AddrType);
1472   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1473   if (PointerArgRes.isInvalid())
1474     return true;
1475   PointerArg = PointerArgRes.get();
1476 
1477   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1478 
1479   // In general, we allow ints, floats and pointers to be loaded and stored.
1480   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1481       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1482     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1483       << PointerArg->getType() << PointerArg->getSourceRange();
1484     return true;
1485   }
1486 
1487   // But ARM doesn't have instructions to deal with 128-bit versions.
1488   if (Context.getTypeSize(ValType) > MaxWidth) {
1489     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1490     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1491       << PointerArg->getType() << PointerArg->getSourceRange();
1492     return true;
1493   }
1494 
1495   switch (ValType.getObjCLifetime()) {
1496   case Qualifiers::OCL_None:
1497   case Qualifiers::OCL_ExplicitNone:
1498     // okay
1499     break;
1500 
1501   case Qualifiers::OCL_Weak:
1502   case Qualifiers::OCL_Strong:
1503   case Qualifiers::OCL_Autoreleasing:
1504     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1505       << ValType << PointerArg->getSourceRange();
1506     return true;
1507   }
1508 
1509   if (IsLdrex) {
1510     TheCall->setType(ValType);
1511     return false;
1512   }
1513 
1514   // Initialize the argument to be stored.
1515   ExprResult ValArg = TheCall->getArg(0);
1516   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1517       Context, ValType, /*consume*/ false);
1518   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1519   if (ValArg.isInvalid())
1520     return true;
1521   TheCall->setArg(0, ValArg.get());
1522 
1523   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1524   // but the custom checker bypasses all default analysis.
1525   TheCall->setType(Context.IntTy);
1526   return false;
1527 }
1528 
1529 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1530   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1531       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1532       BuiltinID == ARM::BI__builtin_arm_strex ||
1533       BuiltinID == ARM::BI__builtin_arm_stlex) {
1534     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1535   }
1536 
1537   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1538     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1539       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1540   }
1541 
1542   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1543       BuiltinID == ARM::BI__builtin_arm_wsr64)
1544     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1545 
1546   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1547       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1548       BuiltinID == ARM::BI__builtin_arm_wsr ||
1549       BuiltinID == ARM::BI__builtin_arm_wsrp)
1550     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1551 
1552   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1553     return true;
1554 
1555   // For intrinsics which take an immediate value as part of the instruction,
1556   // range check them here.
1557   unsigned i = 0, l = 0, u = 0;
1558   switch (BuiltinID) {
1559   default: return false;
1560   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1561   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1562   case ARM::BI__builtin_arm_vcvtr_f:
1563   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1564   case ARM::BI__builtin_arm_dmb:
1565   case ARM::BI__builtin_arm_dsb:
1566   case ARM::BI__builtin_arm_isb:
1567   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1568   }
1569 
1570   // FIXME: VFP Intrinsics should error if VFP not present.
1571   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1572 }
1573 
1574 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1575                                          CallExpr *TheCall) {
1576   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1577       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1578       BuiltinID == AArch64::BI__builtin_arm_strex ||
1579       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1580     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1581   }
1582 
1583   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1584     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1585       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1586       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1587       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1588   }
1589 
1590   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1591       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1592     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1593 
1594   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1595       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1596       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1597       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1598     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1599 
1600   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1601     return true;
1602 
1603   // For intrinsics which take an immediate value as part of the instruction,
1604   // range check them here.
1605   unsigned i = 0, l = 0, u = 0;
1606   switch (BuiltinID) {
1607   default: return false;
1608   case AArch64::BI__builtin_arm_dmb:
1609   case AArch64::BI__builtin_arm_dsb:
1610   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1611   }
1612 
1613   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1614 }
1615 
1616 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1617 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1618 // ordering for DSP is unspecified. MSA is ordered by the data format used
1619 // by the underlying instruction i.e., df/m, df/n and then by size.
1620 //
1621 // FIXME: The size tests here should instead be tablegen'd along with the
1622 //        definitions from include/clang/Basic/BuiltinsMips.def.
1623 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1624 //        be too.
1625 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1626   unsigned i = 0, l = 0, u = 0, m = 0;
1627   switch (BuiltinID) {
1628   default: return false;
1629   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1630   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1631   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1632   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1633   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1634   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1635   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1636   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1637   // df/m field.
1638   // These intrinsics take an unsigned 3 bit immediate.
1639   case Mips::BI__builtin_msa_bclri_b:
1640   case Mips::BI__builtin_msa_bnegi_b:
1641   case Mips::BI__builtin_msa_bseti_b:
1642   case Mips::BI__builtin_msa_sat_s_b:
1643   case Mips::BI__builtin_msa_sat_u_b:
1644   case Mips::BI__builtin_msa_slli_b:
1645   case Mips::BI__builtin_msa_srai_b:
1646   case Mips::BI__builtin_msa_srari_b:
1647   case Mips::BI__builtin_msa_srli_b:
1648   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1649   case Mips::BI__builtin_msa_binsli_b:
1650   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1651   // These intrinsics take an unsigned 4 bit immediate.
1652   case Mips::BI__builtin_msa_bclri_h:
1653   case Mips::BI__builtin_msa_bnegi_h:
1654   case Mips::BI__builtin_msa_bseti_h:
1655   case Mips::BI__builtin_msa_sat_s_h:
1656   case Mips::BI__builtin_msa_sat_u_h:
1657   case Mips::BI__builtin_msa_slli_h:
1658   case Mips::BI__builtin_msa_srai_h:
1659   case Mips::BI__builtin_msa_srari_h:
1660   case Mips::BI__builtin_msa_srli_h:
1661   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1662   case Mips::BI__builtin_msa_binsli_h:
1663   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1664   // These intrinsics take an unsigned 5 bit immedate.
1665   // The first block of intrinsics actually have an unsigned 5 bit field,
1666   // not a df/n field.
1667   case Mips::BI__builtin_msa_clei_u_b:
1668   case Mips::BI__builtin_msa_clei_u_h:
1669   case Mips::BI__builtin_msa_clei_u_w:
1670   case Mips::BI__builtin_msa_clei_u_d:
1671   case Mips::BI__builtin_msa_clti_u_b:
1672   case Mips::BI__builtin_msa_clti_u_h:
1673   case Mips::BI__builtin_msa_clti_u_w:
1674   case Mips::BI__builtin_msa_clti_u_d:
1675   case Mips::BI__builtin_msa_maxi_u_b:
1676   case Mips::BI__builtin_msa_maxi_u_h:
1677   case Mips::BI__builtin_msa_maxi_u_w:
1678   case Mips::BI__builtin_msa_maxi_u_d:
1679   case Mips::BI__builtin_msa_mini_u_b:
1680   case Mips::BI__builtin_msa_mini_u_h:
1681   case Mips::BI__builtin_msa_mini_u_w:
1682   case Mips::BI__builtin_msa_mini_u_d:
1683   case Mips::BI__builtin_msa_addvi_b:
1684   case Mips::BI__builtin_msa_addvi_h:
1685   case Mips::BI__builtin_msa_addvi_w:
1686   case Mips::BI__builtin_msa_addvi_d:
1687   case Mips::BI__builtin_msa_bclri_w:
1688   case Mips::BI__builtin_msa_bnegi_w:
1689   case Mips::BI__builtin_msa_bseti_w:
1690   case Mips::BI__builtin_msa_sat_s_w:
1691   case Mips::BI__builtin_msa_sat_u_w:
1692   case Mips::BI__builtin_msa_slli_w:
1693   case Mips::BI__builtin_msa_srai_w:
1694   case Mips::BI__builtin_msa_srari_w:
1695   case Mips::BI__builtin_msa_srli_w:
1696   case Mips::BI__builtin_msa_srlri_w:
1697   case Mips::BI__builtin_msa_subvi_b:
1698   case Mips::BI__builtin_msa_subvi_h:
1699   case Mips::BI__builtin_msa_subvi_w:
1700   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1701   case Mips::BI__builtin_msa_binsli_w:
1702   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1703   // These intrinsics take an unsigned 6 bit immediate.
1704   case Mips::BI__builtin_msa_bclri_d:
1705   case Mips::BI__builtin_msa_bnegi_d:
1706   case Mips::BI__builtin_msa_bseti_d:
1707   case Mips::BI__builtin_msa_sat_s_d:
1708   case Mips::BI__builtin_msa_sat_u_d:
1709   case Mips::BI__builtin_msa_slli_d:
1710   case Mips::BI__builtin_msa_srai_d:
1711   case Mips::BI__builtin_msa_srari_d:
1712   case Mips::BI__builtin_msa_srli_d:
1713   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1714   case Mips::BI__builtin_msa_binsli_d:
1715   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1716   // These intrinsics take a signed 5 bit immediate.
1717   case Mips::BI__builtin_msa_ceqi_b:
1718   case Mips::BI__builtin_msa_ceqi_h:
1719   case Mips::BI__builtin_msa_ceqi_w:
1720   case Mips::BI__builtin_msa_ceqi_d:
1721   case Mips::BI__builtin_msa_clti_s_b:
1722   case Mips::BI__builtin_msa_clti_s_h:
1723   case Mips::BI__builtin_msa_clti_s_w:
1724   case Mips::BI__builtin_msa_clti_s_d:
1725   case Mips::BI__builtin_msa_clei_s_b:
1726   case Mips::BI__builtin_msa_clei_s_h:
1727   case Mips::BI__builtin_msa_clei_s_w:
1728   case Mips::BI__builtin_msa_clei_s_d:
1729   case Mips::BI__builtin_msa_maxi_s_b:
1730   case Mips::BI__builtin_msa_maxi_s_h:
1731   case Mips::BI__builtin_msa_maxi_s_w:
1732   case Mips::BI__builtin_msa_maxi_s_d:
1733   case Mips::BI__builtin_msa_mini_s_b:
1734   case Mips::BI__builtin_msa_mini_s_h:
1735   case Mips::BI__builtin_msa_mini_s_w:
1736   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1737   // These intrinsics take an unsigned 8 bit immediate.
1738   case Mips::BI__builtin_msa_andi_b:
1739   case Mips::BI__builtin_msa_nori_b:
1740   case Mips::BI__builtin_msa_ori_b:
1741   case Mips::BI__builtin_msa_shf_b:
1742   case Mips::BI__builtin_msa_shf_h:
1743   case Mips::BI__builtin_msa_shf_w:
1744   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1745   case Mips::BI__builtin_msa_bseli_b:
1746   case Mips::BI__builtin_msa_bmnzi_b:
1747   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1748   // df/n format
1749   // These intrinsics take an unsigned 4 bit immediate.
1750   case Mips::BI__builtin_msa_copy_s_b:
1751   case Mips::BI__builtin_msa_copy_u_b:
1752   case Mips::BI__builtin_msa_insve_b:
1753   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1754   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1755   // These intrinsics take an unsigned 3 bit immediate.
1756   case Mips::BI__builtin_msa_copy_s_h:
1757   case Mips::BI__builtin_msa_copy_u_h:
1758   case Mips::BI__builtin_msa_insve_h:
1759   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1760   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1761   // These intrinsics take an unsigned 2 bit immediate.
1762   case Mips::BI__builtin_msa_copy_s_w:
1763   case Mips::BI__builtin_msa_copy_u_w:
1764   case Mips::BI__builtin_msa_insve_w:
1765   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1766   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1767   // These intrinsics take an unsigned 1 bit immediate.
1768   case Mips::BI__builtin_msa_copy_s_d:
1769   case Mips::BI__builtin_msa_copy_u_d:
1770   case Mips::BI__builtin_msa_insve_d:
1771   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1772   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1773   // Memory offsets and immediate loads.
1774   // These intrinsics take a signed 10 bit immediate.
1775   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1776   case Mips::BI__builtin_msa_ldi_h:
1777   case Mips::BI__builtin_msa_ldi_w:
1778   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1779   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1780   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1781   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1782   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1783   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1784   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1785   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1786   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1787   }
1788 
1789   if (!m)
1790     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1791 
1792   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1793          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1794 }
1795 
1796 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1797   unsigned i = 0, l = 0, u = 0;
1798   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1799                       BuiltinID == PPC::BI__builtin_divdeu ||
1800                       BuiltinID == PPC::BI__builtin_bpermd;
1801   bool IsTarget64Bit = Context.getTargetInfo()
1802                               .getTypeWidth(Context
1803                                             .getTargetInfo()
1804                                             .getIntPtrType()) == 64;
1805   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1806                        BuiltinID == PPC::BI__builtin_divweu ||
1807                        BuiltinID == PPC::BI__builtin_divde ||
1808                        BuiltinID == PPC::BI__builtin_divdeu;
1809 
1810   if (Is64BitBltin && !IsTarget64Bit)
1811       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1812              << TheCall->getSourceRange();
1813 
1814   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1815       (BuiltinID == PPC::BI__builtin_bpermd &&
1816        !Context.getTargetInfo().hasFeature("bpermd")))
1817     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1818            << TheCall->getSourceRange();
1819 
1820   switch (BuiltinID) {
1821   default: return false;
1822   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1823   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1824     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1825            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1826   case PPC::BI__builtin_tbegin:
1827   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1828   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1829   case PPC::BI__builtin_tabortwc:
1830   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1831   case PPC::BI__builtin_tabortwci:
1832   case PPC::BI__builtin_tabortdci:
1833     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1834            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1835   case PPC::BI__builtin_vsx_xxpermdi:
1836   case PPC::BI__builtin_vsx_xxsldwi:
1837     return SemaBuiltinVSX(TheCall);
1838   }
1839   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1840 }
1841 
1842 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1843                                            CallExpr *TheCall) {
1844   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1845     Expr *Arg = TheCall->getArg(0);
1846     llvm::APSInt AbortCode(32);
1847     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1848         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1849       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1850              << Arg->getSourceRange();
1851   }
1852 
1853   // For intrinsics which take an immediate value as part of the instruction,
1854   // range check them here.
1855   unsigned i = 0, l = 0, u = 0;
1856   switch (BuiltinID) {
1857   default: return false;
1858   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1859   case SystemZ::BI__builtin_s390_verimb:
1860   case SystemZ::BI__builtin_s390_verimh:
1861   case SystemZ::BI__builtin_s390_verimf:
1862   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1863   case SystemZ::BI__builtin_s390_vfaeb:
1864   case SystemZ::BI__builtin_s390_vfaeh:
1865   case SystemZ::BI__builtin_s390_vfaef:
1866   case SystemZ::BI__builtin_s390_vfaebs:
1867   case SystemZ::BI__builtin_s390_vfaehs:
1868   case SystemZ::BI__builtin_s390_vfaefs:
1869   case SystemZ::BI__builtin_s390_vfaezb:
1870   case SystemZ::BI__builtin_s390_vfaezh:
1871   case SystemZ::BI__builtin_s390_vfaezf:
1872   case SystemZ::BI__builtin_s390_vfaezbs:
1873   case SystemZ::BI__builtin_s390_vfaezhs:
1874   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1875   case SystemZ::BI__builtin_s390_vfisb:
1876   case SystemZ::BI__builtin_s390_vfidb:
1877     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1878            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1879   case SystemZ::BI__builtin_s390_vftcisb:
1880   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1881   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1882   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1883   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1884   case SystemZ::BI__builtin_s390_vstrcb:
1885   case SystemZ::BI__builtin_s390_vstrch:
1886   case SystemZ::BI__builtin_s390_vstrcf:
1887   case SystemZ::BI__builtin_s390_vstrczb:
1888   case SystemZ::BI__builtin_s390_vstrczh:
1889   case SystemZ::BI__builtin_s390_vstrczf:
1890   case SystemZ::BI__builtin_s390_vstrcbs:
1891   case SystemZ::BI__builtin_s390_vstrchs:
1892   case SystemZ::BI__builtin_s390_vstrcfs:
1893   case SystemZ::BI__builtin_s390_vstrczbs:
1894   case SystemZ::BI__builtin_s390_vstrczhs:
1895   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1896   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1897   case SystemZ::BI__builtin_s390_vfminsb:
1898   case SystemZ::BI__builtin_s390_vfmaxsb:
1899   case SystemZ::BI__builtin_s390_vfmindb:
1900   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1901   }
1902   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1903 }
1904 
1905 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1906 /// This checks that the target supports __builtin_cpu_supports and
1907 /// that the string argument is constant and valid.
1908 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1909   Expr *Arg = TheCall->getArg(0);
1910 
1911   // Check if the argument is a string literal.
1912   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1913     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1914            << Arg->getSourceRange();
1915 
1916   // Check the contents of the string.
1917   StringRef Feature =
1918       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1919   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1920     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1921            << Arg->getSourceRange();
1922   return false;
1923 }
1924 
1925 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1926 /// This checks that the target supports __builtin_cpu_is and
1927 /// that the string argument is constant and valid.
1928 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1929   Expr *Arg = TheCall->getArg(0);
1930 
1931   // Check if the argument is a string literal.
1932   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1933     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1934            << Arg->getSourceRange();
1935 
1936   // Check the contents of the string.
1937   StringRef Feature =
1938       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1939   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1940     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1941            << Arg->getSourceRange();
1942   return false;
1943 }
1944 
1945 // Check if the rounding mode is legal.
1946 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1947   // Indicates if this instruction has rounding control or just SAE.
1948   bool HasRC = false;
1949 
1950   unsigned ArgNum = 0;
1951   switch (BuiltinID) {
1952   default:
1953     return false;
1954   case X86::BI__builtin_ia32_vcvttsd2si32:
1955   case X86::BI__builtin_ia32_vcvttsd2si64:
1956   case X86::BI__builtin_ia32_vcvttsd2usi32:
1957   case X86::BI__builtin_ia32_vcvttsd2usi64:
1958   case X86::BI__builtin_ia32_vcvttss2si32:
1959   case X86::BI__builtin_ia32_vcvttss2si64:
1960   case X86::BI__builtin_ia32_vcvttss2usi32:
1961   case X86::BI__builtin_ia32_vcvttss2usi64:
1962     ArgNum = 1;
1963     break;
1964   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1965   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1966   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1967   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1968   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1969   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1970   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1971   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1972   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1973   case X86::BI__builtin_ia32_exp2pd_mask:
1974   case X86::BI__builtin_ia32_exp2ps_mask:
1975   case X86::BI__builtin_ia32_getexppd512_mask:
1976   case X86::BI__builtin_ia32_getexpps512_mask:
1977   case X86::BI__builtin_ia32_rcp28pd_mask:
1978   case X86::BI__builtin_ia32_rcp28ps_mask:
1979   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1980   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1981   case X86::BI__builtin_ia32_vcomisd:
1982   case X86::BI__builtin_ia32_vcomiss:
1983   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1984     ArgNum = 3;
1985     break;
1986   case X86::BI__builtin_ia32_cmppd512_mask:
1987   case X86::BI__builtin_ia32_cmpps512_mask:
1988   case X86::BI__builtin_ia32_cmpsd_mask:
1989   case X86::BI__builtin_ia32_cmpss_mask:
1990   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1991   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1992   case X86::BI__builtin_ia32_getexpss128_round_mask:
1993   case X86::BI__builtin_ia32_maxpd512_mask:
1994   case X86::BI__builtin_ia32_maxps512_mask:
1995   case X86::BI__builtin_ia32_maxsd_round_mask:
1996   case X86::BI__builtin_ia32_maxss_round_mask:
1997   case X86::BI__builtin_ia32_minpd512_mask:
1998   case X86::BI__builtin_ia32_minps512_mask:
1999   case X86::BI__builtin_ia32_minsd_round_mask:
2000   case X86::BI__builtin_ia32_minss_round_mask:
2001   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2002   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2003   case X86::BI__builtin_ia32_reducepd512_mask:
2004   case X86::BI__builtin_ia32_reduceps512_mask:
2005   case X86::BI__builtin_ia32_rndscalepd_mask:
2006   case X86::BI__builtin_ia32_rndscaleps_mask:
2007   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2008   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2009     ArgNum = 4;
2010     break;
2011   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2012   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2013   case X86::BI__builtin_ia32_fixupimmps512_mask:
2014   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2015   case X86::BI__builtin_ia32_fixupimmsd_mask:
2016   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2017   case X86::BI__builtin_ia32_fixupimmss_mask:
2018   case X86::BI__builtin_ia32_fixupimmss_maskz:
2019   case X86::BI__builtin_ia32_rangepd512_mask:
2020   case X86::BI__builtin_ia32_rangeps512_mask:
2021   case X86::BI__builtin_ia32_rangesd128_round_mask:
2022   case X86::BI__builtin_ia32_rangess128_round_mask:
2023   case X86::BI__builtin_ia32_reducesd_mask:
2024   case X86::BI__builtin_ia32_reducess_mask:
2025   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2026   case X86::BI__builtin_ia32_rndscaless_round_mask:
2027     ArgNum = 5;
2028     break;
2029   case X86::BI__builtin_ia32_vcvtsd2si64:
2030   case X86::BI__builtin_ia32_vcvtsd2si32:
2031   case X86::BI__builtin_ia32_vcvtsd2usi32:
2032   case X86::BI__builtin_ia32_vcvtsd2usi64:
2033   case X86::BI__builtin_ia32_vcvtss2si32:
2034   case X86::BI__builtin_ia32_vcvtss2si64:
2035   case X86::BI__builtin_ia32_vcvtss2usi32:
2036   case X86::BI__builtin_ia32_vcvtss2usi64:
2037     ArgNum = 1;
2038     HasRC = true;
2039     break;
2040   case X86::BI__builtin_ia32_cvtsi2sd64:
2041   case X86::BI__builtin_ia32_cvtsi2ss32:
2042   case X86::BI__builtin_ia32_cvtsi2ss64:
2043   case X86::BI__builtin_ia32_cvtusi2sd64:
2044   case X86::BI__builtin_ia32_cvtusi2ss32:
2045   case X86::BI__builtin_ia32_cvtusi2ss64:
2046     ArgNum = 2;
2047     HasRC = true;
2048     break;
2049   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2050   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2051   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2052   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2053   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2054   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2055   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2056   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2057   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2058   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2059   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2060   case X86::BI__builtin_ia32_sqrtpd512_mask:
2061   case X86::BI__builtin_ia32_sqrtps512_mask:
2062     ArgNum = 3;
2063     HasRC = true;
2064     break;
2065   case X86::BI__builtin_ia32_addpd512_mask:
2066   case X86::BI__builtin_ia32_addps512_mask:
2067   case X86::BI__builtin_ia32_divpd512_mask:
2068   case X86::BI__builtin_ia32_divps512_mask:
2069   case X86::BI__builtin_ia32_mulpd512_mask:
2070   case X86::BI__builtin_ia32_mulps512_mask:
2071   case X86::BI__builtin_ia32_subpd512_mask:
2072   case X86::BI__builtin_ia32_subps512_mask:
2073   case X86::BI__builtin_ia32_addss_round_mask:
2074   case X86::BI__builtin_ia32_addsd_round_mask:
2075   case X86::BI__builtin_ia32_divss_round_mask:
2076   case X86::BI__builtin_ia32_divsd_round_mask:
2077   case X86::BI__builtin_ia32_mulss_round_mask:
2078   case X86::BI__builtin_ia32_mulsd_round_mask:
2079   case X86::BI__builtin_ia32_subss_round_mask:
2080   case X86::BI__builtin_ia32_subsd_round_mask:
2081   case X86::BI__builtin_ia32_scalefpd512_mask:
2082   case X86::BI__builtin_ia32_scalefps512_mask:
2083   case X86::BI__builtin_ia32_scalefsd_round_mask:
2084   case X86::BI__builtin_ia32_scalefss_round_mask:
2085   case X86::BI__builtin_ia32_getmantpd512_mask:
2086   case X86::BI__builtin_ia32_getmantps512_mask:
2087   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2088   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2089   case X86::BI__builtin_ia32_sqrtss_round_mask:
2090   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2091   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2092   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2093   case X86::BI__builtin_ia32_vfmaddps512_mask:
2094   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2095   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2096   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2097   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2098   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2099   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2100   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2101   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2102   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2103   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2104   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2105   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2106   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2107   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2108   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2109   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2110   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2111   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2112   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2113   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2114   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2115   case X86::BI__builtin_ia32_vfmaddss3_mask:
2116   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2117   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2118     ArgNum = 4;
2119     HasRC = true;
2120     break;
2121   case X86::BI__builtin_ia32_getmantsd_round_mask:
2122   case X86::BI__builtin_ia32_getmantss_round_mask:
2123     ArgNum = 5;
2124     HasRC = true;
2125     break;
2126   }
2127 
2128   llvm::APSInt Result;
2129 
2130   // We can't check the value of a dependent argument.
2131   Expr *Arg = TheCall->getArg(ArgNum);
2132   if (Arg->isTypeDependent() || Arg->isValueDependent())
2133     return false;
2134 
2135   // Check constant-ness first.
2136   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2137     return true;
2138 
2139   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2140   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2141   // combined with ROUND_NO_EXC.
2142   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2143       Result == 8/*ROUND_NO_EXC*/ ||
2144       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2145     return false;
2146 
2147   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2148     << Arg->getSourceRange();
2149 }
2150 
2151 // Check if the gather/scatter scale is legal.
2152 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2153                                              CallExpr *TheCall) {
2154   unsigned ArgNum = 0;
2155   switch (BuiltinID) {
2156   default:
2157     return false;
2158   case X86::BI__builtin_ia32_gatherpfdpd:
2159   case X86::BI__builtin_ia32_gatherpfdps:
2160   case X86::BI__builtin_ia32_gatherpfqpd:
2161   case X86::BI__builtin_ia32_gatherpfqps:
2162   case X86::BI__builtin_ia32_scatterpfdpd:
2163   case X86::BI__builtin_ia32_scatterpfdps:
2164   case X86::BI__builtin_ia32_scatterpfqpd:
2165   case X86::BI__builtin_ia32_scatterpfqps:
2166     ArgNum = 3;
2167     break;
2168   case X86::BI__builtin_ia32_gatherd_pd:
2169   case X86::BI__builtin_ia32_gatherd_pd256:
2170   case X86::BI__builtin_ia32_gatherq_pd:
2171   case X86::BI__builtin_ia32_gatherq_pd256:
2172   case X86::BI__builtin_ia32_gatherd_ps:
2173   case X86::BI__builtin_ia32_gatherd_ps256:
2174   case X86::BI__builtin_ia32_gatherq_ps:
2175   case X86::BI__builtin_ia32_gatherq_ps256:
2176   case X86::BI__builtin_ia32_gatherd_q:
2177   case X86::BI__builtin_ia32_gatherd_q256:
2178   case X86::BI__builtin_ia32_gatherq_q:
2179   case X86::BI__builtin_ia32_gatherq_q256:
2180   case X86::BI__builtin_ia32_gatherd_d:
2181   case X86::BI__builtin_ia32_gatherd_d256:
2182   case X86::BI__builtin_ia32_gatherq_d:
2183   case X86::BI__builtin_ia32_gatherq_d256:
2184   case X86::BI__builtin_ia32_gather3div2df:
2185   case X86::BI__builtin_ia32_gather3div2di:
2186   case X86::BI__builtin_ia32_gather3div4df:
2187   case X86::BI__builtin_ia32_gather3div4di:
2188   case X86::BI__builtin_ia32_gather3div4sf:
2189   case X86::BI__builtin_ia32_gather3div4si:
2190   case X86::BI__builtin_ia32_gather3div8sf:
2191   case X86::BI__builtin_ia32_gather3div8si:
2192   case X86::BI__builtin_ia32_gather3siv2df:
2193   case X86::BI__builtin_ia32_gather3siv2di:
2194   case X86::BI__builtin_ia32_gather3siv4df:
2195   case X86::BI__builtin_ia32_gather3siv4di:
2196   case X86::BI__builtin_ia32_gather3siv4sf:
2197   case X86::BI__builtin_ia32_gather3siv4si:
2198   case X86::BI__builtin_ia32_gather3siv8sf:
2199   case X86::BI__builtin_ia32_gather3siv8si:
2200   case X86::BI__builtin_ia32_gathersiv8df:
2201   case X86::BI__builtin_ia32_gathersiv16sf:
2202   case X86::BI__builtin_ia32_gatherdiv8df:
2203   case X86::BI__builtin_ia32_gatherdiv16sf:
2204   case X86::BI__builtin_ia32_gathersiv8di:
2205   case X86::BI__builtin_ia32_gathersiv16si:
2206   case X86::BI__builtin_ia32_gatherdiv8di:
2207   case X86::BI__builtin_ia32_gatherdiv16si:
2208   case X86::BI__builtin_ia32_scatterdiv2df:
2209   case X86::BI__builtin_ia32_scatterdiv2di:
2210   case X86::BI__builtin_ia32_scatterdiv4df:
2211   case X86::BI__builtin_ia32_scatterdiv4di:
2212   case X86::BI__builtin_ia32_scatterdiv4sf:
2213   case X86::BI__builtin_ia32_scatterdiv4si:
2214   case X86::BI__builtin_ia32_scatterdiv8sf:
2215   case X86::BI__builtin_ia32_scatterdiv8si:
2216   case X86::BI__builtin_ia32_scattersiv2df:
2217   case X86::BI__builtin_ia32_scattersiv2di:
2218   case X86::BI__builtin_ia32_scattersiv4df:
2219   case X86::BI__builtin_ia32_scattersiv4di:
2220   case X86::BI__builtin_ia32_scattersiv4sf:
2221   case X86::BI__builtin_ia32_scattersiv4si:
2222   case X86::BI__builtin_ia32_scattersiv8sf:
2223   case X86::BI__builtin_ia32_scattersiv8si:
2224   case X86::BI__builtin_ia32_scattersiv8df:
2225   case X86::BI__builtin_ia32_scattersiv16sf:
2226   case X86::BI__builtin_ia32_scatterdiv8df:
2227   case X86::BI__builtin_ia32_scatterdiv16sf:
2228   case X86::BI__builtin_ia32_scattersiv8di:
2229   case X86::BI__builtin_ia32_scattersiv16si:
2230   case X86::BI__builtin_ia32_scatterdiv8di:
2231   case X86::BI__builtin_ia32_scatterdiv16si:
2232     ArgNum = 4;
2233     break;
2234   }
2235 
2236   llvm::APSInt Result;
2237 
2238   // We can't check the value of a dependent argument.
2239   Expr *Arg = TheCall->getArg(ArgNum);
2240   if (Arg->isTypeDependent() || Arg->isValueDependent())
2241     return false;
2242 
2243   // Check constant-ness first.
2244   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2245     return true;
2246 
2247   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2248     return false;
2249 
2250   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2251     << Arg->getSourceRange();
2252 }
2253 
2254 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2255   if (BuiltinID == X86::BI__builtin_cpu_supports)
2256     return SemaBuiltinCpuSupports(*this, TheCall);
2257 
2258   if (BuiltinID == X86::BI__builtin_cpu_is)
2259     return SemaBuiltinCpuIs(*this, TheCall);
2260 
2261   // If the intrinsic has rounding or SAE make sure its valid.
2262   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2263     return true;
2264 
2265   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2266   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2267     return true;
2268 
2269   // For intrinsics which take an immediate value as part of the instruction,
2270   // range check them here.
2271   int i = 0, l = 0, u = 0;
2272   switch (BuiltinID) {
2273   default:
2274     return false;
2275   case X86::BI_mm_prefetch:
2276     i = 1; l = 0; u = 3;
2277     break;
2278   case X86::BI__builtin_ia32_sha1rnds4:
2279   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2280   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2281   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2282   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2283     i = 2; l = 0; u = 3;
2284     break;
2285   case X86::BI__builtin_ia32_vpermil2pd:
2286   case X86::BI__builtin_ia32_vpermil2pd256:
2287   case X86::BI__builtin_ia32_vpermil2ps:
2288   case X86::BI__builtin_ia32_vpermil2ps256:
2289     i = 3; l = 0; u = 3;
2290     break;
2291   case X86::BI__builtin_ia32_cmpb128_mask:
2292   case X86::BI__builtin_ia32_cmpw128_mask:
2293   case X86::BI__builtin_ia32_cmpd128_mask:
2294   case X86::BI__builtin_ia32_cmpq128_mask:
2295   case X86::BI__builtin_ia32_cmpb256_mask:
2296   case X86::BI__builtin_ia32_cmpw256_mask:
2297   case X86::BI__builtin_ia32_cmpd256_mask:
2298   case X86::BI__builtin_ia32_cmpq256_mask:
2299   case X86::BI__builtin_ia32_cmpb512_mask:
2300   case X86::BI__builtin_ia32_cmpw512_mask:
2301   case X86::BI__builtin_ia32_cmpd512_mask:
2302   case X86::BI__builtin_ia32_cmpq512_mask:
2303   case X86::BI__builtin_ia32_ucmpb128_mask:
2304   case X86::BI__builtin_ia32_ucmpw128_mask:
2305   case X86::BI__builtin_ia32_ucmpd128_mask:
2306   case X86::BI__builtin_ia32_ucmpq128_mask:
2307   case X86::BI__builtin_ia32_ucmpb256_mask:
2308   case X86::BI__builtin_ia32_ucmpw256_mask:
2309   case X86::BI__builtin_ia32_ucmpd256_mask:
2310   case X86::BI__builtin_ia32_ucmpq256_mask:
2311   case X86::BI__builtin_ia32_ucmpb512_mask:
2312   case X86::BI__builtin_ia32_ucmpw512_mask:
2313   case X86::BI__builtin_ia32_ucmpd512_mask:
2314   case X86::BI__builtin_ia32_ucmpq512_mask:
2315   case X86::BI__builtin_ia32_vpcomub:
2316   case X86::BI__builtin_ia32_vpcomuw:
2317   case X86::BI__builtin_ia32_vpcomud:
2318   case X86::BI__builtin_ia32_vpcomuq:
2319   case X86::BI__builtin_ia32_vpcomb:
2320   case X86::BI__builtin_ia32_vpcomw:
2321   case X86::BI__builtin_ia32_vpcomd:
2322   case X86::BI__builtin_ia32_vpcomq:
2323     i = 2; l = 0; u = 7;
2324     break;
2325   case X86::BI__builtin_ia32_roundps:
2326   case X86::BI__builtin_ia32_roundpd:
2327   case X86::BI__builtin_ia32_roundps256:
2328   case X86::BI__builtin_ia32_roundpd256:
2329     i = 1; l = 0; u = 15;
2330     break;
2331   case X86::BI__builtin_ia32_roundss:
2332   case X86::BI__builtin_ia32_roundsd:
2333   case X86::BI__builtin_ia32_rangepd128_mask:
2334   case X86::BI__builtin_ia32_rangepd256_mask:
2335   case X86::BI__builtin_ia32_rangepd512_mask:
2336   case X86::BI__builtin_ia32_rangeps128_mask:
2337   case X86::BI__builtin_ia32_rangeps256_mask:
2338   case X86::BI__builtin_ia32_rangeps512_mask:
2339   case X86::BI__builtin_ia32_getmantsd_round_mask:
2340   case X86::BI__builtin_ia32_getmantss_round_mask:
2341     i = 2; l = 0; u = 15;
2342     break;
2343   case X86::BI__builtin_ia32_cmpps:
2344   case X86::BI__builtin_ia32_cmpss:
2345   case X86::BI__builtin_ia32_cmppd:
2346   case X86::BI__builtin_ia32_cmpsd:
2347   case X86::BI__builtin_ia32_cmpps256:
2348   case X86::BI__builtin_ia32_cmppd256:
2349   case X86::BI__builtin_ia32_cmpps128_mask:
2350   case X86::BI__builtin_ia32_cmppd128_mask:
2351   case X86::BI__builtin_ia32_cmpps256_mask:
2352   case X86::BI__builtin_ia32_cmppd256_mask:
2353   case X86::BI__builtin_ia32_cmpps512_mask:
2354   case X86::BI__builtin_ia32_cmppd512_mask:
2355   case X86::BI__builtin_ia32_cmpsd_mask:
2356   case X86::BI__builtin_ia32_cmpss_mask:
2357     i = 2; l = 0; u = 31;
2358     break;
2359   case X86::BI__builtin_ia32_xabort:
2360     i = 0; l = -128; u = 255;
2361     break;
2362   case X86::BI__builtin_ia32_pshufw:
2363   case X86::BI__builtin_ia32_aeskeygenassist128:
2364     i = 1; l = -128; u = 255;
2365     break;
2366   case X86::BI__builtin_ia32_vcvtps2ph:
2367   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2368   case X86::BI__builtin_ia32_vcvtps2ph256:
2369   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2370   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2371   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2372   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2373   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2374   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2375   case X86::BI__builtin_ia32_rndscaleps_mask:
2376   case X86::BI__builtin_ia32_rndscalepd_mask:
2377   case X86::BI__builtin_ia32_reducepd128_mask:
2378   case X86::BI__builtin_ia32_reducepd256_mask:
2379   case X86::BI__builtin_ia32_reducepd512_mask:
2380   case X86::BI__builtin_ia32_reduceps128_mask:
2381   case X86::BI__builtin_ia32_reduceps256_mask:
2382   case X86::BI__builtin_ia32_reduceps512_mask:
2383   case X86::BI__builtin_ia32_prold512_mask:
2384   case X86::BI__builtin_ia32_prolq512_mask:
2385   case X86::BI__builtin_ia32_prold128_mask:
2386   case X86::BI__builtin_ia32_prold256_mask:
2387   case X86::BI__builtin_ia32_prolq128_mask:
2388   case X86::BI__builtin_ia32_prolq256_mask:
2389   case X86::BI__builtin_ia32_prord128_mask:
2390   case X86::BI__builtin_ia32_prord256_mask:
2391   case X86::BI__builtin_ia32_prorq128_mask:
2392   case X86::BI__builtin_ia32_prorq256_mask:
2393   case X86::BI__builtin_ia32_fpclasspd128_mask:
2394   case X86::BI__builtin_ia32_fpclasspd256_mask:
2395   case X86::BI__builtin_ia32_fpclassps128_mask:
2396   case X86::BI__builtin_ia32_fpclassps256_mask:
2397   case X86::BI__builtin_ia32_fpclassps512_mask:
2398   case X86::BI__builtin_ia32_fpclasspd512_mask:
2399   case X86::BI__builtin_ia32_fpclasssd_mask:
2400   case X86::BI__builtin_ia32_fpclassss_mask:
2401     i = 1; l = 0; u = 255;
2402     break;
2403   case X86::BI__builtin_ia32_palignr:
2404   case X86::BI__builtin_ia32_insertps128:
2405   case X86::BI__builtin_ia32_dpps:
2406   case X86::BI__builtin_ia32_dppd:
2407   case X86::BI__builtin_ia32_dpps256:
2408   case X86::BI__builtin_ia32_mpsadbw128:
2409   case X86::BI__builtin_ia32_mpsadbw256:
2410   case X86::BI__builtin_ia32_pcmpistrm128:
2411   case X86::BI__builtin_ia32_pcmpistri128:
2412   case X86::BI__builtin_ia32_pcmpistria128:
2413   case X86::BI__builtin_ia32_pcmpistric128:
2414   case X86::BI__builtin_ia32_pcmpistrio128:
2415   case X86::BI__builtin_ia32_pcmpistris128:
2416   case X86::BI__builtin_ia32_pcmpistriz128:
2417   case X86::BI__builtin_ia32_pclmulqdq128:
2418   case X86::BI__builtin_ia32_vperm2f128_pd256:
2419   case X86::BI__builtin_ia32_vperm2f128_ps256:
2420   case X86::BI__builtin_ia32_vperm2f128_si256:
2421   case X86::BI__builtin_ia32_permti256:
2422     i = 2; l = -128; u = 255;
2423     break;
2424   case X86::BI__builtin_ia32_palignr128:
2425   case X86::BI__builtin_ia32_palignr256:
2426   case X86::BI__builtin_ia32_palignr512_mask:
2427   case X86::BI__builtin_ia32_vcomisd:
2428   case X86::BI__builtin_ia32_vcomiss:
2429   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2430   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2431   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2432   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2433   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2434   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2435   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2436     i = 2; l = 0; u = 255;
2437     break;
2438   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2439   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2440   case X86::BI__builtin_ia32_fixupimmps512_mask:
2441   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2442   case X86::BI__builtin_ia32_fixupimmsd_mask:
2443   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2444   case X86::BI__builtin_ia32_fixupimmss_mask:
2445   case X86::BI__builtin_ia32_fixupimmss_maskz:
2446   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2447   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2448   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2449   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2450   case X86::BI__builtin_ia32_fixupimmps128_mask:
2451   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2452   case X86::BI__builtin_ia32_fixupimmps256_mask:
2453   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2454   case X86::BI__builtin_ia32_pternlogd512_mask:
2455   case X86::BI__builtin_ia32_pternlogd512_maskz:
2456   case X86::BI__builtin_ia32_pternlogq512_mask:
2457   case X86::BI__builtin_ia32_pternlogq512_maskz:
2458   case X86::BI__builtin_ia32_pternlogd128_mask:
2459   case X86::BI__builtin_ia32_pternlogd128_maskz:
2460   case X86::BI__builtin_ia32_pternlogd256_mask:
2461   case X86::BI__builtin_ia32_pternlogd256_maskz:
2462   case X86::BI__builtin_ia32_pternlogq128_mask:
2463   case X86::BI__builtin_ia32_pternlogq128_maskz:
2464   case X86::BI__builtin_ia32_pternlogq256_mask:
2465   case X86::BI__builtin_ia32_pternlogq256_maskz:
2466     i = 3; l = 0; u = 255;
2467     break;
2468   case X86::BI__builtin_ia32_gatherpfdpd:
2469   case X86::BI__builtin_ia32_gatherpfdps:
2470   case X86::BI__builtin_ia32_gatherpfqpd:
2471   case X86::BI__builtin_ia32_gatherpfqps:
2472   case X86::BI__builtin_ia32_scatterpfdpd:
2473   case X86::BI__builtin_ia32_scatterpfdps:
2474   case X86::BI__builtin_ia32_scatterpfqpd:
2475   case X86::BI__builtin_ia32_scatterpfqps:
2476     i = 4; l = 2; u = 3;
2477     break;
2478   case X86::BI__builtin_ia32_pcmpestrm128:
2479   case X86::BI__builtin_ia32_pcmpestri128:
2480   case X86::BI__builtin_ia32_pcmpestria128:
2481   case X86::BI__builtin_ia32_pcmpestric128:
2482   case X86::BI__builtin_ia32_pcmpestrio128:
2483   case X86::BI__builtin_ia32_pcmpestris128:
2484   case X86::BI__builtin_ia32_pcmpestriz128:
2485     i = 4; l = -128; u = 255;
2486     break;
2487   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2488   case X86::BI__builtin_ia32_rndscaless_round_mask:
2489     i = 4; l = 0; u = 255;
2490     break;
2491   }
2492   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2493 }
2494 
2495 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2496 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2497 /// Returns true when the format fits the function and the FormatStringInfo has
2498 /// been populated.
2499 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2500                                FormatStringInfo *FSI) {
2501   FSI->HasVAListArg = Format->getFirstArg() == 0;
2502   FSI->FormatIdx = Format->getFormatIdx() - 1;
2503   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2504 
2505   // The way the format attribute works in GCC, the implicit this argument
2506   // of member functions is counted. However, it doesn't appear in our own
2507   // lists, so decrement format_idx in that case.
2508   if (IsCXXMember) {
2509     if(FSI->FormatIdx == 0)
2510       return false;
2511     --FSI->FormatIdx;
2512     if (FSI->FirstDataArg != 0)
2513       --FSI->FirstDataArg;
2514   }
2515   return true;
2516 }
2517 
2518 /// Checks if a the given expression evaluates to null.
2519 ///
2520 /// \brief Returns true if the value evaluates to null.
2521 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2522   // If the expression has non-null type, it doesn't evaluate to null.
2523   if (auto nullability
2524         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2525     if (*nullability == NullabilityKind::NonNull)
2526       return false;
2527   }
2528 
2529   // As a special case, transparent unions initialized with zero are
2530   // considered null for the purposes of the nonnull attribute.
2531   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2532     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2533       if (const CompoundLiteralExpr *CLE =
2534           dyn_cast<CompoundLiteralExpr>(Expr))
2535         if (const InitListExpr *ILE =
2536             dyn_cast<InitListExpr>(CLE->getInitializer()))
2537           Expr = ILE->getInit(0);
2538   }
2539 
2540   bool Result;
2541   return (!Expr->isValueDependent() &&
2542           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2543           !Result);
2544 }
2545 
2546 static void CheckNonNullArgument(Sema &S,
2547                                  const Expr *ArgExpr,
2548                                  SourceLocation CallSiteLoc) {
2549   if (CheckNonNullExpr(S, ArgExpr))
2550     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2551            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2552 }
2553 
2554 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2555   FormatStringInfo FSI;
2556   if ((GetFormatStringType(Format) == FST_NSString) &&
2557       getFormatStringInfo(Format, false, &FSI)) {
2558     Idx = FSI.FormatIdx;
2559     return true;
2560   }
2561   return false;
2562 }
2563 
2564 /// \brief Diagnose use of %s directive in an NSString which is being passed
2565 /// as formatting string to formatting method.
2566 static void
2567 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2568                                         const NamedDecl *FDecl,
2569                                         Expr **Args,
2570                                         unsigned NumArgs) {
2571   unsigned Idx = 0;
2572   bool Format = false;
2573   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2574   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2575     Idx = 2;
2576     Format = true;
2577   }
2578   else
2579     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2580       if (S.GetFormatNSStringIdx(I, Idx)) {
2581         Format = true;
2582         break;
2583       }
2584     }
2585   if (!Format || NumArgs <= Idx)
2586     return;
2587   const Expr *FormatExpr = Args[Idx];
2588   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2589     FormatExpr = CSCE->getSubExpr();
2590   const StringLiteral *FormatString;
2591   if (const ObjCStringLiteral *OSL =
2592       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2593     FormatString = OSL->getString();
2594   else
2595     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2596   if (!FormatString)
2597     return;
2598   if (S.FormatStringHasSArg(FormatString)) {
2599     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2600       << "%s" << 1 << 1;
2601     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2602       << FDecl->getDeclName();
2603   }
2604 }
2605 
2606 /// Determine whether the given type has a non-null nullability annotation.
2607 static bool isNonNullType(ASTContext &ctx, QualType type) {
2608   if (auto nullability = type->getNullability(ctx))
2609     return *nullability == NullabilityKind::NonNull;
2610 
2611   return false;
2612 }
2613 
2614 static void CheckNonNullArguments(Sema &S,
2615                                   const NamedDecl *FDecl,
2616                                   const FunctionProtoType *Proto,
2617                                   ArrayRef<const Expr *> Args,
2618                                   SourceLocation CallSiteLoc) {
2619   assert((FDecl || Proto) && "Need a function declaration or prototype");
2620 
2621   // Check the attributes attached to the method/function itself.
2622   llvm::SmallBitVector NonNullArgs;
2623   if (FDecl) {
2624     // Handle the nonnull attribute on the function/method declaration itself.
2625     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2626       if (!NonNull->args_size()) {
2627         // Easy case: all pointer arguments are nonnull.
2628         for (const auto *Arg : Args)
2629           if (S.isValidPointerAttrType(Arg->getType()))
2630             CheckNonNullArgument(S, Arg, CallSiteLoc);
2631         return;
2632       }
2633 
2634       for (unsigned Val : NonNull->args()) {
2635         if (Val >= Args.size())
2636           continue;
2637         if (NonNullArgs.empty())
2638           NonNullArgs.resize(Args.size());
2639         NonNullArgs.set(Val);
2640       }
2641     }
2642   }
2643 
2644   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2645     // Handle the nonnull attribute on the parameters of the
2646     // function/method.
2647     ArrayRef<ParmVarDecl*> parms;
2648     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2649       parms = FD->parameters();
2650     else
2651       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2652 
2653     unsigned ParamIndex = 0;
2654     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2655          I != E; ++I, ++ParamIndex) {
2656       const ParmVarDecl *PVD = *I;
2657       if (PVD->hasAttr<NonNullAttr>() ||
2658           isNonNullType(S.Context, PVD->getType())) {
2659         if (NonNullArgs.empty())
2660           NonNullArgs.resize(Args.size());
2661 
2662         NonNullArgs.set(ParamIndex);
2663       }
2664     }
2665   } else {
2666     // If we have a non-function, non-method declaration but no
2667     // function prototype, try to dig out the function prototype.
2668     if (!Proto) {
2669       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2670         QualType type = VD->getType().getNonReferenceType();
2671         if (auto pointerType = type->getAs<PointerType>())
2672           type = pointerType->getPointeeType();
2673         else if (auto blockType = type->getAs<BlockPointerType>())
2674           type = blockType->getPointeeType();
2675         // FIXME: data member pointers?
2676 
2677         // Dig out the function prototype, if there is one.
2678         Proto = type->getAs<FunctionProtoType>();
2679       }
2680     }
2681 
2682     // Fill in non-null argument information from the nullability
2683     // information on the parameter types (if we have them).
2684     if (Proto) {
2685       unsigned Index = 0;
2686       for (auto paramType : Proto->getParamTypes()) {
2687         if (isNonNullType(S.Context, paramType)) {
2688           if (NonNullArgs.empty())
2689             NonNullArgs.resize(Args.size());
2690 
2691           NonNullArgs.set(Index);
2692         }
2693 
2694         ++Index;
2695       }
2696     }
2697   }
2698 
2699   // Check for non-null arguments.
2700   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2701        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2702     if (NonNullArgs[ArgIndex])
2703       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2704   }
2705 }
2706 
2707 /// Handles the checks for format strings, non-POD arguments to vararg
2708 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2709 /// attributes.
2710 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2711                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2712                      bool IsMemberFunction, SourceLocation Loc,
2713                      SourceRange Range, VariadicCallType CallType) {
2714   // FIXME: We should check as much as we can in the template definition.
2715   if (CurContext->isDependentContext())
2716     return;
2717 
2718   // Printf and scanf checking.
2719   llvm::SmallBitVector CheckedVarArgs;
2720   if (FDecl) {
2721     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2722       // Only create vector if there are format attributes.
2723       CheckedVarArgs.resize(Args.size());
2724 
2725       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2726                            CheckedVarArgs);
2727     }
2728   }
2729 
2730   // Refuse POD arguments that weren't caught by the format string
2731   // checks above.
2732   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2733   if (CallType != VariadicDoesNotApply &&
2734       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2735     unsigned NumParams = Proto ? Proto->getNumParams()
2736                        : FDecl && isa<FunctionDecl>(FDecl)
2737                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2738                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2739                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2740                        : 0;
2741 
2742     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2743       // Args[ArgIdx] can be null in malformed code.
2744       if (const Expr *Arg = Args[ArgIdx]) {
2745         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2746           checkVariadicArgument(Arg, CallType);
2747       }
2748     }
2749   }
2750 
2751   if (FDecl || Proto) {
2752     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2753 
2754     // Type safety checking.
2755     if (FDecl) {
2756       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2757         CheckArgumentWithTypeTag(I, Args, Loc);
2758     }
2759   }
2760 
2761   if (FD)
2762     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2763 }
2764 
2765 /// CheckConstructorCall - Check a constructor call for correctness and safety
2766 /// properties not enforced by the C type system.
2767 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2768                                 ArrayRef<const Expr *> Args,
2769                                 const FunctionProtoType *Proto,
2770                                 SourceLocation Loc) {
2771   VariadicCallType CallType =
2772     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2773   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2774             Loc, SourceRange(), CallType);
2775 }
2776 
2777 /// CheckFunctionCall - Check a direct function call for various correctness
2778 /// and safety properties not strictly enforced by the C type system.
2779 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2780                              const FunctionProtoType *Proto) {
2781   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2782                               isa<CXXMethodDecl>(FDecl);
2783   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2784                           IsMemberOperatorCall;
2785   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2786                                                   TheCall->getCallee());
2787   Expr** Args = TheCall->getArgs();
2788   unsigned NumArgs = TheCall->getNumArgs();
2789 
2790   Expr *ImplicitThis = nullptr;
2791   if (IsMemberOperatorCall) {
2792     // If this is a call to a member operator, hide the first argument
2793     // from checkCall.
2794     // FIXME: Our choice of AST representation here is less than ideal.
2795     ImplicitThis = Args[0];
2796     ++Args;
2797     --NumArgs;
2798   } else if (IsMemberFunction)
2799     ImplicitThis =
2800         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2801 
2802   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2803             IsMemberFunction, TheCall->getRParenLoc(),
2804             TheCall->getCallee()->getSourceRange(), CallType);
2805 
2806   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2807   // None of the checks below are needed for functions that don't have
2808   // simple names (e.g., C++ conversion functions).
2809   if (!FnInfo)
2810     return false;
2811 
2812   CheckAbsoluteValueFunction(TheCall, FDecl);
2813   CheckMaxUnsignedZero(TheCall, FDecl);
2814 
2815   if (getLangOpts().ObjC1)
2816     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2817 
2818   unsigned CMId = FDecl->getMemoryFunctionKind();
2819   if (CMId == 0)
2820     return false;
2821 
2822   // Handle memory setting and copying functions.
2823   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2824     CheckStrlcpycatArguments(TheCall, FnInfo);
2825   else if (CMId == Builtin::BIstrncat)
2826     CheckStrncatArguments(TheCall, FnInfo);
2827   else
2828     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2829 
2830   return false;
2831 }
2832 
2833 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2834                                ArrayRef<const Expr *> Args) {
2835   VariadicCallType CallType =
2836       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2837 
2838   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2839             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2840             CallType);
2841 
2842   return false;
2843 }
2844 
2845 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2846                             const FunctionProtoType *Proto) {
2847   QualType Ty;
2848   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2849     Ty = V->getType().getNonReferenceType();
2850   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2851     Ty = F->getType().getNonReferenceType();
2852   else
2853     return false;
2854 
2855   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2856       !Ty->isFunctionProtoType())
2857     return false;
2858 
2859   VariadicCallType CallType;
2860   if (!Proto || !Proto->isVariadic()) {
2861     CallType = VariadicDoesNotApply;
2862   } else if (Ty->isBlockPointerType()) {
2863     CallType = VariadicBlock;
2864   } else { // Ty->isFunctionPointerType()
2865     CallType = VariadicFunction;
2866   }
2867 
2868   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2869             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2870             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2871             TheCall->getCallee()->getSourceRange(), CallType);
2872 
2873   return false;
2874 }
2875 
2876 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2877 /// such as function pointers returned from functions.
2878 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2879   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2880                                                   TheCall->getCallee());
2881   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2882             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2883             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2884             TheCall->getCallee()->getSourceRange(), CallType);
2885 
2886   return false;
2887 }
2888 
2889 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2890   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2891     return false;
2892 
2893   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2894   switch (Op) {
2895   case AtomicExpr::AO__c11_atomic_init:
2896   case AtomicExpr::AO__opencl_atomic_init:
2897     llvm_unreachable("There is no ordering argument for an init");
2898 
2899   case AtomicExpr::AO__c11_atomic_load:
2900   case AtomicExpr::AO__opencl_atomic_load:
2901   case AtomicExpr::AO__atomic_load_n:
2902   case AtomicExpr::AO__atomic_load:
2903     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2904            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2905 
2906   case AtomicExpr::AO__c11_atomic_store:
2907   case AtomicExpr::AO__opencl_atomic_store:
2908   case AtomicExpr::AO__atomic_store:
2909   case AtomicExpr::AO__atomic_store_n:
2910     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2911            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2912            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2913 
2914   default:
2915     return true;
2916   }
2917 }
2918 
2919 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2920                                          AtomicExpr::AtomicOp Op) {
2921   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2922   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2923 
2924   // All the non-OpenCL operations take one of the following forms.
2925   // The OpenCL operations take the __c11 forms with one extra argument for
2926   // synchronization scope.
2927   enum {
2928     // C    __c11_atomic_init(A *, C)
2929     Init,
2930 
2931     // C    __c11_atomic_load(A *, int)
2932     Load,
2933 
2934     // void __atomic_load(A *, CP, int)
2935     LoadCopy,
2936 
2937     // void __atomic_store(A *, CP, int)
2938     Copy,
2939 
2940     // C    __c11_atomic_add(A *, M, int)
2941     Arithmetic,
2942 
2943     // C    __atomic_exchange_n(A *, CP, int)
2944     Xchg,
2945 
2946     // void __atomic_exchange(A *, C *, CP, int)
2947     GNUXchg,
2948 
2949     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2950     C11CmpXchg,
2951 
2952     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2953     GNUCmpXchg
2954   } Form = Init;
2955 
2956   const unsigned NumForm = GNUCmpXchg + 1;
2957   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2958   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2959   // where:
2960   //   C is an appropriate type,
2961   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2962   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2963   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2964   //   the int parameters are for orderings.
2965 
2966   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2967       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2968       "need to update code for modified forms");
2969   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2970                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2971                         AtomicExpr::AO__atomic_load,
2972                 "need to update code for modified C11 atomics");
2973   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2974                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2975   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2976                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2977                IsOpenCL;
2978   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2979              Op == AtomicExpr::AO__atomic_store_n ||
2980              Op == AtomicExpr::AO__atomic_exchange_n ||
2981              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2982   bool IsAddSub = false;
2983 
2984   switch (Op) {
2985   case AtomicExpr::AO__c11_atomic_init:
2986   case AtomicExpr::AO__opencl_atomic_init:
2987     Form = Init;
2988     break;
2989 
2990   case AtomicExpr::AO__c11_atomic_load:
2991   case AtomicExpr::AO__opencl_atomic_load:
2992   case AtomicExpr::AO__atomic_load_n:
2993     Form = Load;
2994     break;
2995 
2996   case AtomicExpr::AO__atomic_load:
2997     Form = LoadCopy;
2998     break;
2999 
3000   case AtomicExpr::AO__c11_atomic_store:
3001   case AtomicExpr::AO__opencl_atomic_store:
3002   case AtomicExpr::AO__atomic_store:
3003   case AtomicExpr::AO__atomic_store_n:
3004     Form = Copy;
3005     break;
3006 
3007   case AtomicExpr::AO__c11_atomic_fetch_add:
3008   case AtomicExpr::AO__c11_atomic_fetch_sub:
3009   case AtomicExpr::AO__opencl_atomic_fetch_add:
3010   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3011   case AtomicExpr::AO__opencl_atomic_fetch_min:
3012   case AtomicExpr::AO__opencl_atomic_fetch_max:
3013   case AtomicExpr::AO__atomic_fetch_add:
3014   case AtomicExpr::AO__atomic_fetch_sub:
3015   case AtomicExpr::AO__atomic_add_fetch:
3016   case AtomicExpr::AO__atomic_sub_fetch:
3017     IsAddSub = true;
3018     // Fall through.
3019   case AtomicExpr::AO__c11_atomic_fetch_and:
3020   case AtomicExpr::AO__c11_atomic_fetch_or:
3021   case AtomicExpr::AO__c11_atomic_fetch_xor:
3022   case AtomicExpr::AO__opencl_atomic_fetch_and:
3023   case AtomicExpr::AO__opencl_atomic_fetch_or:
3024   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3025   case AtomicExpr::AO__atomic_fetch_and:
3026   case AtomicExpr::AO__atomic_fetch_or:
3027   case AtomicExpr::AO__atomic_fetch_xor:
3028   case AtomicExpr::AO__atomic_fetch_nand:
3029   case AtomicExpr::AO__atomic_and_fetch:
3030   case AtomicExpr::AO__atomic_or_fetch:
3031   case AtomicExpr::AO__atomic_xor_fetch:
3032   case AtomicExpr::AO__atomic_nand_fetch:
3033     Form = Arithmetic;
3034     break;
3035 
3036   case AtomicExpr::AO__c11_atomic_exchange:
3037   case AtomicExpr::AO__opencl_atomic_exchange:
3038   case AtomicExpr::AO__atomic_exchange_n:
3039     Form = Xchg;
3040     break;
3041 
3042   case AtomicExpr::AO__atomic_exchange:
3043     Form = GNUXchg;
3044     break;
3045 
3046   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3047   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3048   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3049   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3050     Form = C11CmpXchg;
3051     break;
3052 
3053   case AtomicExpr::AO__atomic_compare_exchange:
3054   case AtomicExpr::AO__atomic_compare_exchange_n:
3055     Form = GNUCmpXchg;
3056     break;
3057   }
3058 
3059   unsigned AdjustedNumArgs = NumArgs[Form];
3060   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3061     ++AdjustedNumArgs;
3062   // Check we have the right number of arguments.
3063   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3064     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3065       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3066       << TheCall->getCallee()->getSourceRange();
3067     return ExprError();
3068   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3069     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3070          diag::err_typecheck_call_too_many_args)
3071       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3072       << TheCall->getCallee()->getSourceRange();
3073     return ExprError();
3074   }
3075 
3076   // Inspect the first argument of the atomic operation.
3077   Expr *Ptr = TheCall->getArg(0);
3078   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3079   if (ConvertedPtr.isInvalid())
3080     return ExprError();
3081 
3082   Ptr = ConvertedPtr.get();
3083   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3084   if (!pointerType) {
3085     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3086       << Ptr->getType() << Ptr->getSourceRange();
3087     return ExprError();
3088   }
3089 
3090   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3091   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3092   QualType ValType = AtomTy; // 'C'
3093   if (IsC11) {
3094     if (!AtomTy->isAtomicType()) {
3095       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3096         << Ptr->getType() << Ptr->getSourceRange();
3097       return ExprError();
3098     }
3099     if (AtomTy.isConstQualified() ||
3100         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3101       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3102           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3103           << Ptr->getSourceRange();
3104       return ExprError();
3105     }
3106     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3107   } else if (Form != Load && Form != LoadCopy) {
3108     if (ValType.isConstQualified()) {
3109       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3110         << Ptr->getType() << Ptr->getSourceRange();
3111       return ExprError();
3112     }
3113   }
3114 
3115   // For an arithmetic operation, the implied arithmetic must be well-formed.
3116   if (Form == Arithmetic) {
3117     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3118     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3119       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3120         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3121       return ExprError();
3122     }
3123     if (!IsAddSub && !ValType->isIntegerType()) {
3124       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3125         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3126       return ExprError();
3127     }
3128     if (IsC11 && ValType->isPointerType() &&
3129         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3130                             diag::err_incomplete_type)) {
3131       return ExprError();
3132     }
3133   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3134     // For __atomic_*_n operations, the value type must be a scalar integral or
3135     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3136     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3137       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3138     return ExprError();
3139   }
3140 
3141   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3142       !AtomTy->isScalarType()) {
3143     // For GNU atomics, require a trivially-copyable type. This is not part of
3144     // the GNU atomics specification, but we enforce it for sanity.
3145     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3146       << Ptr->getType() << Ptr->getSourceRange();
3147     return ExprError();
3148   }
3149 
3150   switch (ValType.getObjCLifetime()) {
3151   case Qualifiers::OCL_None:
3152   case Qualifiers::OCL_ExplicitNone:
3153     // okay
3154     break;
3155 
3156   case Qualifiers::OCL_Weak:
3157   case Qualifiers::OCL_Strong:
3158   case Qualifiers::OCL_Autoreleasing:
3159     // FIXME: Can this happen? By this point, ValType should be known
3160     // to be trivially copyable.
3161     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3162       << ValType << Ptr->getSourceRange();
3163     return ExprError();
3164   }
3165 
3166   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3167   // volatile-ness of the pointee-type inject itself into the result or the
3168   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3169   ValType.removeLocalVolatile();
3170   ValType.removeLocalConst();
3171   QualType ResultType = ValType;
3172   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3173       Form == Init)
3174     ResultType = Context.VoidTy;
3175   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3176     ResultType = Context.BoolTy;
3177 
3178   // The type of a parameter passed 'by value'. In the GNU atomics, such
3179   // arguments are actually passed as pointers.
3180   QualType ByValType = ValType; // 'CP'
3181   if (!IsC11 && !IsN)
3182     ByValType = Ptr->getType();
3183 
3184   // The first argument --- the pointer --- has a fixed type; we
3185   // deduce the types of the rest of the arguments accordingly.  Walk
3186   // the remaining arguments, converting them to the deduced value type.
3187   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3188     QualType Ty;
3189     if (i < NumVals[Form] + 1) {
3190       switch (i) {
3191       case 1:
3192         // The second argument is the non-atomic operand. For arithmetic, this
3193         // is always passed by value, and for a compare_exchange it is always
3194         // passed by address. For the rest, GNU uses by-address and C11 uses
3195         // by-value.
3196         assert(Form != Load);
3197         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3198           Ty = ValType;
3199         else if (Form == Copy || Form == Xchg)
3200           Ty = ByValType;
3201         else if (Form == Arithmetic)
3202           Ty = Context.getPointerDiffType();
3203         else {
3204           Expr *ValArg = TheCall->getArg(i);
3205           // Treat this argument as _Nonnull as we want to show a warning if
3206           // NULL is passed into it.
3207           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3208           LangAS AS = LangAS::Default;
3209           // Keep address space of non-atomic pointer type.
3210           if (const PointerType *PtrTy =
3211                   ValArg->getType()->getAs<PointerType>()) {
3212             AS = PtrTy->getPointeeType().getAddressSpace();
3213           }
3214           Ty = Context.getPointerType(
3215               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3216         }
3217         break;
3218       case 2:
3219         // The third argument to compare_exchange / GNU exchange is a
3220         // (pointer to a) desired value.
3221         Ty = ByValType;
3222         break;
3223       case 3:
3224         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3225         Ty = Context.BoolTy;
3226         break;
3227       }
3228     } else {
3229       // The order(s) and scope are always converted to int.
3230       Ty = Context.IntTy;
3231     }
3232 
3233     InitializedEntity Entity =
3234         InitializedEntity::InitializeParameter(Context, Ty, false);
3235     ExprResult Arg = TheCall->getArg(i);
3236     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3237     if (Arg.isInvalid())
3238       return true;
3239     TheCall->setArg(i, Arg.get());
3240   }
3241 
3242   // Permute the arguments into a 'consistent' order.
3243   SmallVector<Expr*, 5> SubExprs;
3244   SubExprs.push_back(Ptr);
3245   switch (Form) {
3246   case Init:
3247     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3248     SubExprs.push_back(TheCall->getArg(1)); // Val1
3249     break;
3250   case Load:
3251     SubExprs.push_back(TheCall->getArg(1)); // Order
3252     break;
3253   case LoadCopy:
3254   case Copy:
3255   case Arithmetic:
3256   case Xchg:
3257     SubExprs.push_back(TheCall->getArg(2)); // Order
3258     SubExprs.push_back(TheCall->getArg(1)); // Val1
3259     break;
3260   case GNUXchg:
3261     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3262     SubExprs.push_back(TheCall->getArg(3)); // Order
3263     SubExprs.push_back(TheCall->getArg(1)); // Val1
3264     SubExprs.push_back(TheCall->getArg(2)); // Val2
3265     break;
3266   case C11CmpXchg:
3267     SubExprs.push_back(TheCall->getArg(3)); // Order
3268     SubExprs.push_back(TheCall->getArg(1)); // Val1
3269     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3270     SubExprs.push_back(TheCall->getArg(2)); // Val2
3271     break;
3272   case GNUCmpXchg:
3273     SubExprs.push_back(TheCall->getArg(4)); // Order
3274     SubExprs.push_back(TheCall->getArg(1)); // Val1
3275     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3276     SubExprs.push_back(TheCall->getArg(2)); // Val2
3277     SubExprs.push_back(TheCall->getArg(3)); // Weak
3278     break;
3279   }
3280 
3281   if (SubExprs.size() >= 2 && Form != Init) {
3282     llvm::APSInt Result(32);
3283     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3284         !isValidOrderingForOp(Result.getSExtValue(), Op))
3285       Diag(SubExprs[1]->getLocStart(),
3286            diag::warn_atomic_op_has_invalid_memory_order)
3287           << SubExprs[1]->getSourceRange();
3288   }
3289 
3290   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3291     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3292     llvm::APSInt Result(32);
3293     if (Scope->isIntegerConstantExpr(Result, Context) &&
3294         !ScopeModel->isValid(Result.getZExtValue())) {
3295       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3296           << Scope->getSourceRange();
3297     }
3298     SubExprs.push_back(Scope);
3299   }
3300 
3301   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3302                                             SubExprs, ResultType, Op,
3303                                             TheCall->getRParenLoc());
3304 
3305   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3306        Op == AtomicExpr::AO__c11_atomic_store ||
3307        Op == AtomicExpr::AO__opencl_atomic_load ||
3308        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3309       Context.AtomicUsesUnsupportedLibcall(AE))
3310     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3311         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3312             Op == AtomicExpr::AO__opencl_atomic_load)
3313                 ? 0 : 1);
3314 
3315   return AE;
3316 }
3317 
3318 /// checkBuiltinArgument - Given a call to a builtin function, perform
3319 /// normal type-checking on the given argument, updating the call in
3320 /// place.  This is useful when a builtin function requires custom
3321 /// type-checking for some of its arguments but not necessarily all of
3322 /// them.
3323 ///
3324 /// Returns true on error.
3325 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3326   FunctionDecl *Fn = E->getDirectCallee();
3327   assert(Fn && "builtin call without direct callee!");
3328 
3329   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3330   InitializedEntity Entity =
3331     InitializedEntity::InitializeParameter(S.Context, Param);
3332 
3333   ExprResult Arg = E->getArg(0);
3334   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3335   if (Arg.isInvalid())
3336     return true;
3337 
3338   E->setArg(ArgIndex, Arg.get());
3339   return false;
3340 }
3341 
3342 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3343 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3344 /// type of its first argument.  The main ActOnCallExpr routines have already
3345 /// promoted the types of arguments because all of these calls are prototyped as
3346 /// void(...).
3347 ///
3348 /// This function goes through and does final semantic checking for these
3349 /// builtins,
3350 ExprResult
3351 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3352   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3353   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3354   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3355 
3356   // Ensure that we have at least one argument to do type inference from.
3357   if (TheCall->getNumArgs() < 1) {
3358     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3359       << 0 << 1 << TheCall->getNumArgs()
3360       << TheCall->getCallee()->getSourceRange();
3361     return ExprError();
3362   }
3363 
3364   // Inspect the first argument of the atomic builtin.  This should always be
3365   // a pointer type, whose element is an integral scalar or pointer type.
3366   // Because it is a pointer type, we don't have to worry about any implicit
3367   // casts here.
3368   // FIXME: We don't allow floating point scalars as input.
3369   Expr *FirstArg = TheCall->getArg(0);
3370   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3371   if (FirstArgResult.isInvalid())
3372     return ExprError();
3373   FirstArg = FirstArgResult.get();
3374   TheCall->setArg(0, FirstArg);
3375 
3376   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3377   if (!pointerType) {
3378     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3379       << FirstArg->getType() << FirstArg->getSourceRange();
3380     return ExprError();
3381   }
3382 
3383   QualType ValType = pointerType->getPointeeType();
3384   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3385       !ValType->isBlockPointerType()) {
3386     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3387       << FirstArg->getType() << FirstArg->getSourceRange();
3388     return ExprError();
3389   }
3390 
3391   switch (ValType.getObjCLifetime()) {
3392   case Qualifiers::OCL_None:
3393   case Qualifiers::OCL_ExplicitNone:
3394     // okay
3395     break;
3396 
3397   case Qualifiers::OCL_Weak:
3398   case Qualifiers::OCL_Strong:
3399   case Qualifiers::OCL_Autoreleasing:
3400     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3401       << ValType << FirstArg->getSourceRange();
3402     return ExprError();
3403   }
3404 
3405   // Strip any qualifiers off ValType.
3406   ValType = ValType.getUnqualifiedType();
3407 
3408   // The majority of builtins return a value, but a few have special return
3409   // types, so allow them to override appropriately below.
3410   QualType ResultType = ValType;
3411 
3412   // We need to figure out which concrete builtin this maps onto.  For example,
3413   // __sync_fetch_and_add with a 2 byte object turns into
3414   // __sync_fetch_and_add_2.
3415 #define BUILTIN_ROW(x) \
3416   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3417     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3418 
3419   static const unsigned BuiltinIndices[][5] = {
3420     BUILTIN_ROW(__sync_fetch_and_add),
3421     BUILTIN_ROW(__sync_fetch_and_sub),
3422     BUILTIN_ROW(__sync_fetch_and_or),
3423     BUILTIN_ROW(__sync_fetch_and_and),
3424     BUILTIN_ROW(__sync_fetch_and_xor),
3425     BUILTIN_ROW(__sync_fetch_and_nand),
3426 
3427     BUILTIN_ROW(__sync_add_and_fetch),
3428     BUILTIN_ROW(__sync_sub_and_fetch),
3429     BUILTIN_ROW(__sync_and_and_fetch),
3430     BUILTIN_ROW(__sync_or_and_fetch),
3431     BUILTIN_ROW(__sync_xor_and_fetch),
3432     BUILTIN_ROW(__sync_nand_and_fetch),
3433 
3434     BUILTIN_ROW(__sync_val_compare_and_swap),
3435     BUILTIN_ROW(__sync_bool_compare_and_swap),
3436     BUILTIN_ROW(__sync_lock_test_and_set),
3437     BUILTIN_ROW(__sync_lock_release),
3438     BUILTIN_ROW(__sync_swap)
3439   };
3440 #undef BUILTIN_ROW
3441 
3442   // Determine the index of the size.
3443   unsigned SizeIndex;
3444   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3445   case 1: SizeIndex = 0; break;
3446   case 2: SizeIndex = 1; break;
3447   case 4: SizeIndex = 2; break;
3448   case 8: SizeIndex = 3; break;
3449   case 16: SizeIndex = 4; break;
3450   default:
3451     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3452       << FirstArg->getType() << FirstArg->getSourceRange();
3453     return ExprError();
3454   }
3455 
3456   // Each of these builtins has one pointer argument, followed by some number of
3457   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3458   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3459   // as the number of fixed args.
3460   unsigned BuiltinID = FDecl->getBuiltinID();
3461   unsigned BuiltinIndex, NumFixed = 1;
3462   bool WarnAboutSemanticsChange = false;
3463   switch (BuiltinID) {
3464   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3465   case Builtin::BI__sync_fetch_and_add:
3466   case Builtin::BI__sync_fetch_and_add_1:
3467   case Builtin::BI__sync_fetch_and_add_2:
3468   case Builtin::BI__sync_fetch_and_add_4:
3469   case Builtin::BI__sync_fetch_and_add_8:
3470   case Builtin::BI__sync_fetch_and_add_16:
3471     BuiltinIndex = 0;
3472     break;
3473 
3474   case Builtin::BI__sync_fetch_and_sub:
3475   case Builtin::BI__sync_fetch_and_sub_1:
3476   case Builtin::BI__sync_fetch_and_sub_2:
3477   case Builtin::BI__sync_fetch_and_sub_4:
3478   case Builtin::BI__sync_fetch_and_sub_8:
3479   case Builtin::BI__sync_fetch_and_sub_16:
3480     BuiltinIndex = 1;
3481     break;
3482 
3483   case Builtin::BI__sync_fetch_and_or:
3484   case Builtin::BI__sync_fetch_and_or_1:
3485   case Builtin::BI__sync_fetch_and_or_2:
3486   case Builtin::BI__sync_fetch_and_or_4:
3487   case Builtin::BI__sync_fetch_and_or_8:
3488   case Builtin::BI__sync_fetch_and_or_16:
3489     BuiltinIndex = 2;
3490     break;
3491 
3492   case Builtin::BI__sync_fetch_and_and:
3493   case Builtin::BI__sync_fetch_and_and_1:
3494   case Builtin::BI__sync_fetch_and_and_2:
3495   case Builtin::BI__sync_fetch_and_and_4:
3496   case Builtin::BI__sync_fetch_and_and_8:
3497   case Builtin::BI__sync_fetch_and_and_16:
3498     BuiltinIndex = 3;
3499     break;
3500 
3501   case Builtin::BI__sync_fetch_and_xor:
3502   case Builtin::BI__sync_fetch_and_xor_1:
3503   case Builtin::BI__sync_fetch_and_xor_2:
3504   case Builtin::BI__sync_fetch_and_xor_4:
3505   case Builtin::BI__sync_fetch_and_xor_8:
3506   case Builtin::BI__sync_fetch_and_xor_16:
3507     BuiltinIndex = 4;
3508     break;
3509 
3510   case Builtin::BI__sync_fetch_and_nand:
3511   case Builtin::BI__sync_fetch_and_nand_1:
3512   case Builtin::BI__sync_fetch_and_nand_2:
3513   case Builtin::BI__sync_fetch_and_nand_4:
3514   case Builtin::BI__sync_fetch_and_nand_8:
3515   case Builtin::BI__sync_fetch_and_nand_16:
3516     BuiltinIndex = 5;
3517     WarnAboutSemanticsChange = true;
3518     break;
3519 
3520   case Builtin::BI__sync_add_and_fetch:
3521   case Builtin::BI__sync_add_and_fetch_1:
3522   case Builtin::BI__sync_add_and_fetch_2:
3523   case Builtin::BI__sync_add_and_fetch_4:
3524   case Builtin::BI__sync_add_and_fetch_8:
3525   case Builtin::BI__sync_add_and_fetch_16:
3526     BuiltinIndex = 6;
3527     break;
3528 
3529   case Builtin::BI__sync_sub_and_fetch:
3530   case Builtin::BI__sync_sub_and_fetch_1:
3531   case Builtin::BI__sync_sub_and_fetch_2:
3532   case Builtin::BI__sync_sub_and_fetch_4:
3533   case Builtin::BI__sync_sub_and_fetch_8:
3534   case Builtin::BI__sync_sub_and_fetch_16:
3535     BuiltinIndex = 7;
3536     break;
3537 
3538   case Builtin::BI__sync_and_and_fetch:
3539   case Builtin::BI__sync_and_and_fetch_1:
3540   case Builtin::BI__sync_and_and_fetch_2:
3541   case Builtin::BI__sync_and_and_fetch_4:
3542   case Builtin::BI__sync_and_and_fetch_8:
3543   case Builtin::BI__sync_and_and_fetch_16:
3544     BuiltinIndex = 8;
3545     break;
3546 
3547   case Builtin::BI__sync_or_and_fetch:
3548   case Builtin::BI__sync_or_and_fetch_1:
3549   case Builtin::BI__sync_or_and_fetch_2:
3550   case Builtin::BI__sync_or_and_fetch_4:
3551   case Builtin::BI__sync_or_and_fetch_8:
3552   case Builtin::BI__sync_or_and_fetch_16:
3553     BuiltinIndex = 9;
3554     break;
3555 
3556   case Builtin::BI__sync_xor_and_fetch:
3557   case Builtin::BI__sync_xor_and_fetch_1:
3558   case Builtin::BI__sync_xor_and_fetch_2:
3559   case Builtin::BI__sync_xor_and_fetch_4:
3560   case Builtin::BI__sync_xor_and_fetch_8:
3561   case Builtin::BI__sync_xor_and_fetch_16:
3562     BuiltinIndex = 10;
3563     break;
3564 
3565   case Builtin::BI__sync_nand_and_fetch:
3566   case Builtin::BI__sync_nand_and_fetch_1:
3567   case Builtin::BI__sync_nand_and_fetch_2:
3568   case Builtin::BI__sync_nand_and_fetch_4:
3569   case Builtin::BI__sync_nand_and_fetch_8:
3570   case Builtin::BI__sync_nand_and_fetch_16:
3571     BuiltinIndex = 11;
3572     WarnAboutSemanticsChange = true;
3573     break;
3574 
3575   case Builtin::BI__sync_val_compare_and_swap:
3576   case Builtin::BI__sync_val_compare_and_swap_1:
3577   case Builtin::BI__sync_val_compare_and_swap_2:
3578   case Builtin::BI__sync_val_compare_and_swap_4:
3579   case Builtin::BI__sync_val_compare_and_swap_8:
3580   case Builtin::BI__sync_val_compare_and_swap_16:
3581     BuiltinIndex = 12;
3582     NumFixed = 2;
3583     break;
3584 
3585   case Builtin::BI__sync_bool_compare_and_swap:
3586   case Builtin::BI__sync_bool_compare_and_swap_1:
3587   case Builtin::BI__sync_bool_compare_and_swap_2:
3588   case Builtin::BI__sync_bool_compare_and_swap_4:
3589   case Builtin::BI__sync_bool_compare_and_swap_8:
3590   case Builtin::BI__sync_bool_compare_and_swap_16:
3591     BuiltinIndex = 13;
3592     NumFixed = 2;
3593     ResultType = Context.BoolTy;
3594     break;
3595 
3596   case Builtin::BI__sync_lock_test_and_set:
3597   case Builtin::BI__sync_lock_test_and_set_1:
3598   case Builtin::BI__sync_lock_test_and_set_2:
3599   case Builtin::BI__sync_lock_test_and_set_4:
3600   case Builtin::BI__sync_lock_test_and_set_8:
3601   case Builtin::BI__sync_lock_test_and_set_16:
3602     BuiltinIndex = 14;
3603     break;
3604 
3605   case Builtin::BI__sync_lock_release:
3606   case Builtin::BI__sync_lock_release_1:
3607   case Builtin::BI__sync_lock_release_2:
3608   case Builtin::BI__sync_lock_release_4:
3609   case Builtin::BI__sync_lock_release_8:
3610   case Builtin::BI__sync_lock_release_16:
3611     BuiltinIndex = 15;
3612     NumFixed = 0;
3613     ResultType = Context.VoidTy;
3614     break;
3615 
3616   case Builtin::BI__sync_swap:
3617   case Builtin::BI__sync_swap_1:
3618   case Builtin::BI__sync_swap_2:
3619   case Builtin::BI__sync_swap_4:
3620   case Builtin::BI__sync_swap_8:
3621   case Builtin::BI__sync_swap_16:
3622     BuiltinIndex = 16;
3623     break;
3624   }
3625 
3626   // Now that we know how many fixed arguments we expect, first check that we
3627   // have at least that many.
3628   if (TheCall->getNumArgs() < 1+NumFixed) {
3629     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3630       << 0 << 1+NumFixed << TheCall->getNumArgs()
3631       << TheCall->getCallee()->getSourceRange();
3632     return ExprError();
3633   }
3634 
3635   if (WarnAboutSemanticsChange) {
3636     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3637       << TheCall->getCallee()->getSourceRange();
3638   }
3639 
3640   // Get the decl for the concrete builtin from this, we can tell what the
3641   // concrete integer type we should convert to is.
3642   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3643   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3644   FunctionDecl *NewBuiltinDecl;
3645   if (NewBuiltinID == BuiltinID)
3646     NewBuiltinDecl = FDecl;
3647   else {
3648     // Perform builtin lookup to avoid redeclaring it.
3649     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3650     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3651     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3652     assert(Res.getFoundDecl());
3653     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3654     if (!NewBuiltinDecl)
3655       return ExprError();
3656   }
3657 
3658   // The first argument --- the pointer --- has a fixed type; we
3659   // deduce the types of the rest of the arguments accordingly.  Walk
3660   // the remaining arguments, converting them to the deduced value type.
3661   for (unsigned i = 0; i != NumFixed; ++i) {
3662     ExprResult Arg = TheCall->getArg(i+1);
3663 
3664     // GCC does an implicit conversion to the pointer or integer ValType.  This
3665     // can fail in some cases (1i -> int**), check for this error case now.
3666     // Initialize the argument.
3667     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3668                                                    ValType, /*consume*/ false);
3669     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3670     if (Arg.isInvalid())
3671       return ExprError();
3672 
3673     // Okay, we have something that *can* be converted to the right type.  Check
3674     // to see if there is a potentially weird extension going on here.  This can
3675     // happen when you do an atomic operation on something like an char* and
3676     // pass in 42.  The 42 gets converted to char.  This is even more strange
3677     // for things like 45.123 -> char, etc.
3678     // FIXME: Do this check.
3679     TheCall->setArg(i+1, Arg.get());
3680   }
3681 
3682   ASTContext& Context = this->getASTContext();
3683 
3684   // Create a new DeclRefExpr to refer to the new decl.
3685   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3686       Context,
3687       DRE->getQualifierLoc(),
3688       SourceLocation(),
3689       NewBuiltinDecl,
3690       /*enclosing*/ false,
3691       DRE->getLocation(),
3692       Context.BuiltinFnTy,
3693       DRE->getValueKind());
3694 
3695   // Set the callee in the CallExpr.
3696   // FIXME: This loses syntactic information.
3697   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3698   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3699                                               CK_BuiltinFnToFnPtr);
3700   TheCall->setCallee(PromotedCall.get());
3701 
3702   // Change the result type of the call to match the original value type. This
3703   // is arbitrary, but the codegen for these builtins ins design to handle it
3704   // gracefully.
3705   TheCall->setType(ResultType);
3706 
3707   return TheCallResult;
3708 }
3709 
3710 /// SemaBuiltinNontemporalOverloaded - We have a call to
3711 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3712 /// overloaded function based on the pointer type of its last argument.
3713 ///
3714 /// This function goes through and does final semantic checking for these
3715 /// builtins.
3716 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3717   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3718   DeclRefExpr *DRE =
3719       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3720   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3721   unsigned BuiltinID = FDecl->getBuiltinID();
3722   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3723           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3724          "Unexpected nontemporal load/store builtin!");
3725   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3726   unsigned numArgs = isStore ? 2 : 1;
3727 
3728   // Ensure that we have the proper number of arguments.
3729   if (checkArgCount(*this, TheCall, numArgs))
3730     return ExprError();
3731 
3732   // Inspect the last argument of the nontemporal builtin.  This should always
3733   // be a pointer type, from which we imply the type of the memory access.
3734   // Because it is a pointer type, we don't have to worry about any implicit
3735   // casts here.
3736   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3737   ExprResult PointerArgResult =
3738       DefaultFunctionArrayLvalueConversion(PointerArg);
3739 
3740   if (PointerArgResult.isInvalid())
3741     return ExprError();
3742   PointerArg = PointerArgResult.get();
3743   TheCall->setArg(numArgs - 1, PointerArg);
3744 
3745   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3746   if (!pointerType) {
3747     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3748         << PointerArg->getType() << PointerArg->getSourceRange();
3749     return ExprError();
3750   }
3751 
3752   QualType ValType = pointerType->getPointeeType();
3753 
3754   // Strip any qualifiers off ValType.
3755   ValType = ValType.getUnqualifiedType();
3756   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3757       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3758       !ValType->isVectorType()) {
3759     Diag(DRE->getLocStart(),
3760          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3761         << PointerArg->getType() << PointerArg->getSourceRange();
3762     return ExprError();
3763   }
3764 
3765   if (!isStore) {
3766     TheCall->setType(ValType);
3767     return TheCallResult;
3768   }
3769 
3770   ExprResult ValArg = TheCall->getArg(0);
3771   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3772       Context, ValType, /*consume*/ false);
3773   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3774   if (ValArg.isInvalid())
3775     return ExprError();
3776 
3777   TheCall->setArg(0, ValArg.get());
3778   TheCall->setType(Context.VoidTy);
3779   return TheCallResult;
3780 }
3781 
3782 /// CheckObjCString - Checks that the argument to the builtin
3783 /// CFString constructor is correct
3784 /// Note: It might also make sense to do the UTF-16 conversion here (would
3785 /// simplify the backend).
3786 bool Sema::CheckObjCString(Expr *Arg) {
3787   Arg = Arg->IgnoreParenCasts();
3788   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3789 
3790   if (!Literal || !Literal->isAscii()) {
3791     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3792       << Arg->getSourceRange();
3793     return true;
3794   }
3795 
3796   if (Literal->containsNonAsciiOrNull()) {
3797     StringRef String = Literal->getString();
3798     unsigned NumBytes = String.size();
3799     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3800     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3801     llvm::UTF16 *ToPtr = &ToBuf[0];
3802 
3803     llvm::ConversionResult Result =
3804         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3805                                  ToPtr + NumBytes, llvm::strictConversion);
3806     // Check for conversion failure.
3807     if (Result != llvm::conversionOK)
3808       Diag(Arg->getLocStart(),
3809            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3810   }
3811   return false;
3812 }
3813 
3814 /// CheckObjCString - Checks that the format string argument to the os_log()
3815 /// and os_trace() functions is correct, and converts it to const char *.
3816 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3817   Arg = Arg->IgnoreParenCasts();
3818   auto *Literal = dyn_cast<StringLiteral>(Arg);
3819   if (!Literal) {
3820     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3821       Literal = ObjcLiteral->getString();
3822     }
3823   }
3824 
3825   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3826     return ExprError(
3827         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3828         << Arg->getSourceRange());
3829   }
3830 
3831   ExprResult Result(Literal);
3832   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3833   InitializedEntity Entity =
3834       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3835   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3836   return Result;
3837 }
3838 
3839 /// Check that the user is calling the appropriate va_start builtin for the
3840 /// target and calling convention.
3841 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3842   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3843   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3844   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3845   bool IsWindows = TT.isOSWindows();
3846   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3847   if (IsX64 || IsAArch64) {
3848     CallingConv CC = CC_C;
3849     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3850       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3851     if (IsMSVAStart) {
3852       // Don't allow this in System V ABI functions.
3853       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3854         return S.Diag(Fn->getLocStart(),
3855                       diag::err_ms_va_start_used_in_sysv_function);
3856     } else {
3857       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3858       // On x64 Windows, don't allow this in System V ABI functions.
3859       // (Yes, that means there's no corresponding way to support variadic
3860       // System V ABI functions on Windows.)
3861       if ((IsWindows && CC == CC_X86_64SysV) ||
3862           (!IsWindows && CC == CC_Win64))
3863         return S.Diag(Fn->getLocStart(),
3864                       diag::err_va_start_used_in_wrong_abi_function)
3865                << !IsWindows;
3866     }
3867     return false;
3868   }
3869 
3870   if (IsMSVAStart)
3871     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3872   return false;
3873 }
3874 
3875 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3876                                              ParmVarDecl **LastParam = nullptr) {
3877   // Determine whether the current function, block, or obj-c method is variadic
3878   // and get its parameter list.
3879   bool IsVariadic = false;
3880   ArrayRef<ParmVarDecl *> Params;
3881   DeclContext *Caller = S.CurContext;
3882   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3883     IsVariadic = Block->isVariadic();
3884     Params = Block->parameters();
3885   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3886     IsVariadic = FD->isVariadic();
3887     Params = FD->parameters();
3888   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3889     IsVariadic = MD->isVariadic();
3890     // FIXME: This isn't correct for methods (results in bogus warning).
3891     Params = MD->parameters();
3892   } else if (isa<CapturedDecl>(Caller)) {
3893     // We don't support va_start in a CapturedDecl.
3894     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3895     return true;
3896   } else {
3897     // This must be some other declcontext that parses exprs.
3898     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3899     return true;
3900   }
3901 
3902   if (!IsVariadic) {
3903     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3904     return true;
3905   }
3906 
3907   if (LastParam)
3908     *LastParam = Params.empty() ? nullptr : Params.back();
3909 
3910   return false;
3911 }
3912 
3913 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3914 /// for validity.  Emit an error and return true on failure; return false
3915 /// on success.
3916 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3917   Expr *Fn = TheCall->getCallee();
3918 
3919   if (checkVAStartABI(*this, BuiltinID, Fn))
3920     return true;
3921 
3922   if (TheCall->getNumArgs() > 2) {
3923     Diag(TheCall->getArg(2)->getLocStart(),
3924          diag::err_typecheck_call_too_many_args)
3925       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3926       << Fn->getSourceRange()
3927       << SourceRange(TheCall->getArg(2)->getLocStart(),
3928                      (*(TheCall->arg_end()-1))->getLocEnd());
3929     return true;
3930   }
3931 
3932   if (TheCall->getNumArgs() < 2) {
3933     return Diag(TheCall->getLocEnd(),
3934       diag::err_typecheck_call_too_few_args_at_least)
3935       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3936   }
3937 
3938   // Type-check the first argument normally.
3939   if (checkBuiltinArgument(*this, TheCall, 0))
3940     return true;
3941 
3942   // Check that the current function is variadic, and get its last parameter.
3943   ParmVarDecl *LastParam;
3944   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3945     return true;
3946 
3947   // Verify that the second argument to the builtin is the last argument of the
3948   // current function or method.
3949   bool SecondArgIsLastNamedArgument = false;
3950   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3951 
3952   // These are valid if SecondArgIsLastNamedArgument is false after the next
3953   // block.
3954   QualType Type;
3955   SourceLocation ParamLoc;
3956   bool IsCRegister = false;
3957 
3958   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3959     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3960       SecondArgIsLastNamedArgument = PV == LastParam;
3961 
3962       Type = PV->getType();
3963       ParamLoc = PV->getLocation();
3964       IsCRegister =
3965           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3966     }
3967   }
3968 
3969   if (!SecondArgIsLastNamedArgument)
3970     Diag(TheCall->getArg(1)->getLocStart(),
3971          diag::warn_second_arg_of_va_start_not_last_named_param);
3972   else if (IsCRegister || Type->isReferenceType() ||
3973            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3974              // Promotable integers are UB, but enumerations need a bit of
3975              // extra checking to see what their promotable type actually is.
3976              if (!Type->isPromotableIntegerType())
3977                return false;
3978              if (!Type->isEnumeralType())
3979                return true;
3980              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3981              return !(ED &&
3982                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3983            }()) {
3984     unsigned Reason = 0;
3985     if (Type->isReferenceType())  Reason = 1;
3986     else if (IsCRegister)         Reason = 2;
3987     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3988     Diag(ParamLoc, diag::note_parameter_type) << Type;
3989   }
3990 
3991   TheCall->setType(Context.VoidTy);
3992   return false;
3993 }
3994 
3995 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3996   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3997   //                 const char *named_addr);
3998 
3999   Expr *Func = Call->getCallee();
4000 
4001   if (Call->getNumArgs() < 3)
4002     return Diag(Call->getLocEnd(),
4003                 diag::err_typecheck_call_too_few_args_at_least)
4004            << 0 /*function call*/ << 3 << Call->getNumArgs();
4005 
4006   // Type-check the first argument normally.
4007   if (checkBuiltinArgument(*this, Call, 0))
4008     return true;
4009 
4010   // Check that the current function is variadic.
4011   if (checkVAStartIsInVariadicFunction(*this, Func))
4012     return true;
4013 
4014   // __va_start on Windows does not validate the parameter qualifiers
4015 
4016   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4017   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4018 
4019   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4020   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4021 
4022   const QualType &ConstCharPtrTy =
4023       Context.getPointerType(Context.CharTy.withConst());
4024   if (!Arg1Ty->isPointerType() ||
4025       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4026     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4027         << Arg1->getType() << ConstCharPtrTy
4028         << 1 /* different class */
4029         << 0 /* qualifier difference */
4030         << 3 /* parameter mismatch */
4031         << 2 << Arg1->getType() << ConstCharPtrTy;
4032 
4033   const QualType SizeTy = Context.getSizeType();
4034   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4035     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4036         << Arg2->getType() << SizeTy
4037         << 1 /* different class */
4038         << 0 /* qualifier difference */
4039         << 3 /* parameter mismatch */
4040         << 3 << Arg2->getType() << SizeTy;
4041 
4042   return false;
4043 }
4044 
4045 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4046 /// friends.  This is declared to take (...), so we have to check everything.
4047 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4048   if (TheCall->getNumArgs() < 2)
4049     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4050       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4051   if (TheCall->getNumArgs() > 2)
4052     return Diag(TheCall->getArg(2)->getLocStart(),
4053                 diag::err_typecheck_call_too_many_args)
4054       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4055       << SourceRange(TheCall->getArg(2)->getLocStart(),
4056                      (*(TheCall->arg_end()-1))->getLocEnd());
4057 
4058   ExprResult OrigArg0 = TheCall->getArg(0);
4059   ExprResult OrigArg1 = TheCall->getArg(1);
4060 
4061   // Do standard promotions between the two arguments, returning their common
4062   // type.
4063   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4064   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4065     return true;
4066 
4067   // Make sure any conversions are pushed back into the call; this is
4068   // type safe since unordered compare builtins are declared as "_Bool
4069   // foo(...)".
4070   TheCall->setArg(0, OrigArg0.get());
4071   TheCall->setArg(1, OrigArg1.get());
4072 
4073   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4074     return false;
4075 
4076   // If the common type isn't a real floating type, then the arguments were
4077   // invalid for this operation.
4078   if (Res.isNull() || !Res->isRealFloatingType())
4079     return Diag(OrigArg0.get()->getLocStart(),
4080                 diag::err_typecheck_call_invalid_ordered_compare)
4081       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4082       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4083 
4084   return false;
4085 }
4086 
4087 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4088 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4089 /// to check everything. We expect the last argument to be a floating point
4090 /// value.
4091 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4092   if (TheCall->getNumArgs() < NumArgs)
4093     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4094       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4095   if (TheCall->getNumArgs() > NumArgs)
4096     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4097                 diag::err_typecheck_call_too_many_args)
4098       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4099       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4100                      (*(TheCall->arg_end()-1))->getLocEnd());
4101 
4102   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4103 
4104   if (OrigArg->isTypeDependent())
4105     return false;
4106 
4107   // This operation requires a non-_Complex floating-point number.
4108   if (!OrigArg->getType()->isRealFloatingType())
4109     return Diag(OrigArg->getLocStart(),
4110                 diag::err_typecheck_call_invalid_unary_fp)
4111       << OrigArg->getType() << OrigArg->getSourceRange();
4112 
4113   // If this is an implicit conversion from float -> float or double, remove it.
4114   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4115     // Only remove standard FloatCasts, leaving other casts inplace
4116     if (Cast->getCastKind() == CK_FloatingCast) {
4117       Expr *CastArg = Cast->getSubExpr();
4118       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4119           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4120                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4121                "promotion from float to either float or double is the only expected cast here");
4122         Cast->setSubExpr(nullptr);
4123         TheCall->setArg(NumArgs-1, CastArg);
4124       }
4125     }
4126   }
4127 
4128   return false;
4129 }
4130 
4131 // Customized Sema Checking for VSX builtins that have the following signature:
4132 // vector [...] builtinName(vector [...], vector [...], const int);
4133 // Which takes the same type of vectors (any legal vector type) for the first
4134 // two arguments and takes compile time constant for the third argument.
4135 // Example builtins are :
4136 // vector double vec_xxpermdi(vector double, vector double, int);
4137 // vector short vec_xxsldwi(vector short, vector short, int);
4138 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4139   unsigned ExpectedNumArgs = 3;
4140   if (TheCall->getNumArgs() < ExpectedNumArgs)
4141     return Diag(TheCall->getLocEnd(),
4142                 diag::err_typecheck_call_too_few_args_at_least)
4143            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4144            << TheCall->getSourceRange();
4145 
4146   if (TheCall->getNumArgs() > ExpectedNumArgs)
4147     return Diag(TheCall->getLocEnd(),
4148                 diag::err_typecheck_call_too_many_args_at_most)
4149            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4150            << TheCall->getSourceRange();
4151 
4152   // Check the third argument is a compile time constant
4153   llvm::APSInt Value;
4154   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4155     return Diag(TheCall->getLocStart(),
4156                 diag::err_vsx_builtin_nonconstant_argument)
4157            << 3 /* argument index */ << TheCall->getDirectCallee()
4158            << SourceRange(TheCall->getArg(2)->getLocStart(),
4159                           TheCall->getArg(2)->getLocEnd());
4160 
4161   QualType Arg1Ty = TheCall->getArg(0)->getType();
4162   QualType Arg2Ty = TheCall->getArg(1)->getType();
4163 
4164   // Check the type of argument 1 and argument 2 are vectors.
4165   SourceLocation BuiltinLoc = TheCall->getLocStart();
4166   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4167       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4168     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4169            << TheCall->getDirectCallee()
4170            << SourceRange(TheCall->getArg(0)->getLocStart(),
4171                           TheCall->getArg(1)->getLocEnd());
4172   }
4173 
4174   // Check the first two arguments are the same type.
4175   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4176     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4177            << TheCall->getDirectCallee()
4178            << SourceRange(TheCall->getArg(0)->getLocStart(),
4179                           TheCall->getArg(1)->getLocEnd());
4180   }
4181 
4182   // When default clang type checking is turned off and the customized type
4183   // checking is used, the returning type of the function must be explicitly
4184   // set. Otherwise it is _Bool by default.
4185   TheCall->setType(Arg1Ty);
4186 
4187   return false;
4188 }
4189 
4190 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4191 // This is declared to take (...), so we have to check everything.
4192 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4193   if (TheCall->getNumArgs() < 2)
4194     return ExprError(Diag(TheCall->getLocEnd(),
4195                           diag::err_typecheck_call_too_few_args_at_least)
4196                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4197                      << TheCall->getSourceRange());
4198 
4199   // Determine which of the following types of shufflevector we're checking:
4200   // 1) unary, vector mask: (lhs, mask)
4201   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4202   QualType resType = TheCall->getArg(0)->getType();
4203   unsigned numElements = 0;
4204 
4205   if (!TheCall->getArg(0)->isTypeDependent() &&
4206       !TheCall->getArg(1)->isTypeDependent()) {
4207     QualType LHSType = TheCall->getArg(0)->getType();
4208     QualType RHSType = TheCall->getArg(1)->getType();
4209 
4210     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4211       return ExprError(Diag(TheCall->getLocStart(),
4212                             diag::err_vec_builtin_non_vector)
4213                        << TheCall->getDirectCallee()
4214                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4215                                       TheCall->getArg(1)->getLocEnd()));
4216 
4217     numElements = LHSType->getAs<VectorType>()->getNumElements();
4218     unsigned numResElements = TheCall->getNumArgs() - 2;
4219 
4220     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4221     // with mask.  If so, verify that RHS is an integer vector type with the
4222     // same number of elts as lhs.
4223     if (TheCall->getNumArgs() == 2) {
4224       if (!RHSType->hasIntegerRepresentation() ||
4225           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4226         return ExprError(Diag(TheCall->getLocStart(),
4227                               diag::err_vec_builtin_incompatible_vector)
4228                          << TheCall->getDirectCallee()
4229                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4230                                         TheCall->getArg(1)->getLocEnd()));
4231     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4232       return ExprError(Diag(TheCall->getLocStart(),
4233                             diag::err_vec_builtin_incompatible_vector)
4234                        << TheCall->getDirectCallee()
4235                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4236                                       TheCall->getArg(1)->getLocEnd()));
4237     } else if (numElements != numResElements) {
4238       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4239       resType = Context.getVectorType(eltType, numResElements,
4240                                       VectorType::GenericVector);
4241     }
4242   }
4243 
4244   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4245     if (TheCall->getArg(i)->isTypeDependent() ||
4246         TheCall->getArg(i)->isValueDependent())
4247       continue;
4248 
4249     llvm::APSInt Result(32);
4250     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4251       return ExprError(Diag(TheCall->getLocStart(),
4252                             diag::err_shufflevector_nonconstant_argument)
4253                        << TheCall->getArg(i)->getSourceRange());
4254 
4255     // Allow -1 which will be translated to undef in the IR.
4256     if (Result.isSigned() && Result.isAllOnesValue())
4257       continue;
4258 
4259     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4260       return ExprError(Diag(TheCall->getLocStart(),
4261                             diag::err_shufflevector_argument_too_large)
4262                        << TheCall->getArg(i)->getSourceRange());
4263   }
4264 
4265   SmallVector<Expr*, 32> exprs;
4266 
4267   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4268     exprs.push_back(TheCall->getArg(i));
4269     TheCall->setArg(i, nullptr);
4270   }
4271 
4272   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4273                                          TheCall->getCallee()->getLocStart(),
4274                                          TheCall->getRParenLoc());
4275 }
4276 
4277 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4278 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4279                                        SourceLocation BuiltinLoc,
4280                                        SourceLocation RParenLoc) {
4281   ExprValueKind VK = VK_RValue;
4282   ExprObjectKind OK = OK_Ordinary;
4283   QualType DstTy = TInfo->getType();
4284   QualType SrcTy = E->getType();
4285 
4286   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4287     return ExprError(Diag(BuiltinLoc,
4288                           diag::err_convertvector_non_vector)
4289                      << E->getSourceRange());
4290   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4291     return ExprError(Diag(BuiltinLoc,
4292                           diag::err_convertvector_non_vector_type));
4293 
4294   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4295     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4296     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4297     if (SrcElts != DstElts)
4298       return ExprError(Diag(BuiltinLoc,
4299                             diag::err_convertvector_incompatible_vector)
4300                        << E->getSourceRange());
4301   }
4302 
4303   return new (Context)
4304       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4305 }
4306 
4307 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4308 // This is declared to take (const void*, ...) and can take two
4309 // optional constant int args.
4310 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4311   unsigned NumArgs = TheCall->getNumArgs();
4312 
4313   if (NumArgs > 3)
4314     return Diag(TheCall->getLocEnd(),
4315              diag::err_typecheck_call_too_many_args_at_most)
4316              << 0 /*function call*/ << 3 << NumArgs
4317              << TheCall->getSourceRange();
4318 
4319   // Argument 0 is checked for us and the remaining arguments must be
4320   // constant integers.
4321   for (unsigned i = 1; i != NumArgs; ++i)
4322     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4323       return true;
4324 
4325   return false;
4326 }
4327 
4328 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4329 // __assume does not evaluate its arguments, and should warn if its argument
4330 // has side effects.
4331 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4332   Expr *Arg = TheCall->getArg(0);
4333   if (Arg->isInstantiationDependent()) return false;
4334 
4335   if (Arg->HasSideEffects(Context))
4336     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4337       << Arg->getSourceRange()
4338       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4339 
4340   return false;
4341 }
4342 
4343 /// Handle __builtin_alloca_with_align. This is declared
4344 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4345 /// than 8.
4346 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4347   // The alignment must be a constant integer.
4348   Expr *Arg = TheCall->getArg(1);
4349 
4350   // We can't check the value of a dependent argument.
4351   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4352     if (const auto *UE =
4353             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4354       if (UE->getKind() == UETT_AlignOf)
4355         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4356           << Arg->getSourceRange();
4357 
4358     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4359 
4360     if (!Result.isPowerOf2())
4361       return Diag(TheCall->getLocStart(),
4362                   diag::err_alignment_not_power_of_two)
4363            << Arg->getSourceRange();
4364 
4365     if (Result < Context.getCharWidth())
4366       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4367            << (unsigned)Context.getCharWidth()
4368            << Arg->getSourceRange();
4369 
4370     if (Result > std::numeric_limits<int32_t>::max())
4371       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4372            << std::numeric_limits<int32_t>::max()
4373            << Arg->getSourceRange();
4374   }
4375 
4376   return false;
4377 }
4378 
4379 /// Handle __builtin_assume_aligned. This is declared
4380 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4381 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4382   unsigned NumArgs = TheCall->getNumArgs();
4383 
4384   if (NumArgs > 3)
4385     return Diag(TheCall->getLocEnd(),
4386              diag::err_typecheck_call_too_many_args_at_most)
4387              << 0 /*function call*/ << 3 << NumArgs
4388              << TheCall->getSourceRange();
4389 
4390   // The alignment must be a constant integer.
4391   Expr *Arg = TheCall->getArg(1);
4392 
4393   // We can't check the value of a dependent argument.
4394   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4395     llvm::APSInt Result;
4396     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4397       return true;
4398 
4399     if (!Result.isPowerOf2())
4400       return Diag(TheCall->getLocStart(),
4401                   diag::err_alignment_not_power_of_two)
4402            << Arg->getSourceRange();
4403   }
4404 
4405   if (NumArgs > 2) {
4406     ExprResult Arg(TheCall->getArg(2));
4407     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4408       Context.getSizeType(), false);
4409     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4410     if (Arg.isInvalid()) return true;
4411     TheCall->setArg(2, Arg.get());
4412   }
4413 
4414   return false;
4415 }
4416 
4417 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4418   unsigned BuiltinID =
4419       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4420   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4421 
4422   unsigned NumArgs = TheCall->getNumArgs();
4423   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4424   if (NumArgs < NumRequiredArgs) {
4425     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4426            << 0 /* function call */ << NumRequiredArgs << NumArgs
4427            << TheCall->getSourceRange();
4428   }
4429   if (NumArgs >= NumRequiredArgs + 0x100) {
4430     return Diag(TheCall->getLocEnd(),
4431                 diag::err_typecheck_call_too_many_args_at_most)
4432            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4433            << TheCall->getSourceRange();
4434   }
4435   unsigned i = 0;
4436 
4437   // For formatting call, check buffer arg.
4438   if (!IsSizeCall) {
4439     ExprResult Arg(TheCall->getArg(i));
4440     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4441         Context, Context.VoidPtrTy, false);
4442     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4443     if (Arg.isInvalid())
4444       return true;
4445     TheCall->setArg(i, Arg.get());
4446     i++;
4447   }
4448 
4449   // Check string literal arg.
4450   unsigned FormatIdx = i;
4451   {
4452     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4453     if (Arg.isInvalid())
4454       return true;
4455     TheCall->setArg(i, Arg.get());
4456     i++;
4457   }
4458 
4459   // Make sure variadic args are scalar.
4460   unsigned FirstDataArg = i;
4461   while (i < NumArgs) {
4462     ExprResult Arg = DefaultVariadicArgumentPromotion(
4463         TheCall->getArg(i), VariadicFunction, nullptr);
4464     if (Arg.isInvalid())
4465       return true;
4466     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4467     if (ArgSize.getQuantity() >= 0x100) {
4468       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4469              << i << (int)ArgSize.getQuantity() << 0xff
4470              << TheCall->getSourceRange();
4471     }
4472     TheCall->setArg(i, Arg.get());
4473     i++;
4474   }
4475 
4476   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4477   // call to avoid duplicate diagnostics.
4478   if (!IsSizeCall) {
4479     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4480     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4481     bool Success = CheckFormatArguments(
4482         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4483         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4484         CheckedVarArgs);
4485     if (!Success)
4486       return true;
4487   }
4488 
4489   if (IsSizeCall) {
4490     TheCall->setType(Context.getSizeType());
4491   } else {
4492     TheCall->setType(Context.VoidPtrTy);
4493   }
4494   return false;
4495 }
4496 
4497 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4498 /// TheCall is a constant expression.
4499 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4500                                   llvm::APSInt &Result) {
4501   Expr *Arg = TheCall->getArg(ArgNum);
4502   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4503   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4504 
4505   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4506 
4507   if (!Arg->isIntegerConstantExpr(Result, Context))
4508     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4509                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4510 
4511   return false;
4512 }
4513 
4514 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4515 /// TheCall is a constant expression in the range [Low, High].
4516 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4517                                        int Low, int High) {
4518   llvm::APSInt Result;
4519 
4520   // We can't check the value of a dependent argument.
4521   Expr *Arg = TheCall->getArg(ArgNum);
4522   if (Arg->isTypeDependent() || Arg->isValueDependent())
4523     return false;
4524 
4525   // Check constant-ness first.
4526   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4527     return true;
4528 
4529   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4530     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4531       << Low << High << Arg->getSourceRange();
4532 
4533   return false;
4534 }
4535 
4536 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4537 /// TheCall is a constant expression is a multiple of Num..
4538 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4539                                           unsigned Num) {
4540   llvm::APSInt Result;
4541 
4542   // We can't check the value of a dependent argument.
4543   Expr *Arg = TheCall->getArg(ArgNum);
4544   if (Arg->isTypeDependent() || Arg->isValueDependent())
4545     return false;
4546 
4547   // Check constant-ness first.
4548   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4549     return true;
4550 
4551   if (Result.getSExtValue() % Num != 0)
4552     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4553       << Num << Arg->getSourceRange();
4554 
4555   return false;
4556 }
4557 
4558 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4559 /// TheCall is an ARM/AArch64 special register string literal.
4560 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4561                                     int ArgNum, unsigned ExpectedFieldNum,
4562                                     bool AllowName) {
4563   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4564                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4565                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4566                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4567                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4568                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4569   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4570                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4571                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4572                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4573                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4574                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4575   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4576 
4577   // We can't check the value of a dependent argument.
4578   Expr *Arg = TheCall->getArg(ArgNum);
4579   if (Arg->isTypeDependent() || Arg->isValueDependent())
4580     return false;
4581 
4582   // Check if the argument is a string literal.
4583   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4584     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4585            << Arg->getSourceRange();
4586 
4587   // Check the type of special register given.
4588   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4589   SmallVector<StringRef, 6> Fields;
4590   Reg.split(Fields, ":");
4591 
4592   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4593     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4594            << Arg->getSourceRange();
4595 
4596   // If the string is the name of a register then we cannot check that it is
4597   // valid here but if the string is of one the forms described in ACLE then we
4598   // can check that the supplied fields are integers and within the valid
4599   // ranges.
4600   if (Fields.size() > 1) {
4601     bool FiveFields = Fields.size() == 5;
4602 
4603     bool ValidString = true;
4604     if (IsARMBuiltin) {
4605       ValidString &= Fields[0].startswith_lower("cp") ||
4606                      Fields[0].startswith_lower("p");
4607       if (ValidString)
4608         Fields[0] =
4609           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4610 
4611       ValidString &= Fields[2].startswith_lower("c");
4612       if (ValidString)
4613         Fields[2] = Fields[2].drop_front(1);
4614 
4615       if (FiveFields) {
4616         ValidString &= Fields[3].startswith_lower("c");
4617         if (ValidString)
4618           Fields[3] = Fields[3].drop_front(1);
4619       }
4620     }
4621 
4622     SmallVector<int, 5> Ranges;
4623     if (FiveFields)
4624       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4625     else
4626       Ranges.append({15, 7, 15});
4627 
4628     for (unsigned i=0; i<Fields.size(); ++i) {
4629       int IntField;
4630       ValidString &= !Fields[i].getAsInteger(10, IntField);
4631       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4632     }
4633 
4634     if (!ValidString)
4635       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4636              << Arg->getSourceRange();
4637   } else if (IsAArch64Builtin && Fields.size() == 1) {
4638     // If the register name is one of those that appear in the condition below
4639     // and the special register builtin being used is one of the write builtins,
4640     // then we require that the argument provided for writing to the register
4641     // is an integer constant expression. This is because it will be lowered to
4642     // an MSR (immediate) instruction, so we need to know the immediate at
4643     // compile time.
4644     if (TheCall->getNumArgs() != 2)
4645       return false;
4646 
4647     std::string RegLower = Reg.lower();
4648     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4649         RegLower != "pan" && RegLower != "uao")
4650       return false;
4651 
4652     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4653   }
4654 
4655   return false;
4656 }
4657 
4658 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4659 /// This checks that the target supports __builtin_longjmp and
4660 /// that val is a constant 1.
4661 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4662   if (!Context.getTargetInfo().hasSjLjLowering())
4663     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4664              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4665 
4666   Expr *Arg = TheCall->getArg(1);
4667   llvm::APSInt Result;
4668 
4669   // TODO: This is less than ideal. Overload this to take a value.
4670   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4671     return true;
4672 
4673   if (Result != 1)
4674     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4675              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4676 
4677   return false;
4678 }
4679 
4680 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4681 /// This checks that the target supports __builtin_setjmp.
4682 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4683   if (!Context.getTargetInfo().hasSjLjLowering())
4684     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4685              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4686   return false;
4687 }
4688 
4689 namespace {
4690 
4691 class UncoveredArgHandler {
4692   enum { Unknown = -1, AllCovered = -2 };
4693 
4694   signed FirstUncoveredArg = Unknown;
4695   SmallVector<const Expr *, 4> DiagnosticExprs;
4696 
4697 public:
4698   UncoveredArgHandler() = default;
4699 
4700   bool hasUncoveredArg() const {
4701     return (FirstUncoveredArg >= 0);
4702   }
4703 
4704   unsigned getUncoveredArg() const {
4705     assert(hasUncoveredArg() && "no uncovered argument");
4706     return FirstUncoveredArg;
4707   }
4708 
4709   void setAllCovered() {
4710     // A string has been found with all arguments covered, so clear out
4711     // the diagnostics.
4712     DiagnosticExprs.clear();
4713     FirstUncoveredArg = AllCovered;
4714   }
4715 
4716   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4717     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4718 
4719     // Don't update if a previous string covers all arguments.
4720     if (FirstUncoveredArg == AllCovered)
4721       return;
4722 
4723     // UncoveredArgHandler tracks the highest uncovered argument index
4724     // and with it all the strings that match this index.
4725     if (NewFirstUncoveredArg == FirstUncoveredArg)
4726       DiagnosticExprs.push_back(StrExpr);
4727     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4728       DiagnosticExprs.clear();
4729       DiagnosticExprs.push_back(StrExpr);
4730       FirstUncoveredArg = NewFirstUncoveredArg;
4731     }
4732   }
4733 
4734   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4735 };
4736 
4737 enum StringLiteralCheckType {
4738   SLCT_NotALiteral,
4739   SLCT_UncheckedLiteral,
4740   SLCT_CheckedLiteral
4741 };
4742 
4743 } // namespace
4744 
4745 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4746                                      BinaryOperatorKind BinOpKind,
4747                                      bool AddendIsRight) {
4748   unsigned BitWidth = Offset.getBitWidth();
4749   unsigned AddendBitWidth = Addend.getBitWidth();
4750   // There might be negative interim results.
4751   if (Addend.isUnsigned()) {
4752     Addend = Addend.zext(++AddendBitWidth);
4753     Addend.setIsSigned(true);
4754   }
4755   // Adjust the bit width of the APSInts.
4756   if (AddendBitWidth > BitWidth) {
4757     Offset = Offset.sext(AddendBitWidth);
4758     BitWidth = AddendBitWidth;
4759   } else if (BitWidth > AddendBitWidth) {
4760     Addend = Addend.sext(BitWidth);
4761   }
4762 
4763   bool Ov = false;
4764   llvm::APSInt ResOffset = Offset;
4765   if (BinOpKind == BO_Add)
4766     ResOffset = Offset.sadd_ov(Addend, Ov);
4767   else {
4768     assert(AddendIsRight && BinOpKind == BO_Sub &&
4769            "operator must be add or sub with addend on the right");
4770     ResOffset = Offset.ssub_ov(Addend, Ov);
4771   }
4772 
4773   // We add an offset to a pointer here so we should support an offset as big as
4774   // possible.
4775   if (Ov) {
4776     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4777            "index (intermediate) result too big");
4778     Offset = Offset.sext(2 * BitWidth);
4779     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4780     return;
4781   }
4782 
4783   Offset = ResOffset;
4784 }
4785 
4786 namespace {
4787 
4788 // This is a wrapper class around StringLiteral to support offsetted string
4789 // literals as format strings. It takes the offset into account when returning
4790 // the string and its length or the source locations to display notes correctly.
4791 class FormatStringLiteral {
4792   const StringLiteral *FExpr;
4793   int64_t Offset;
4794 
4795  public:
4796   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4797       : FExpr(fexpr), Offset(Offset) {}
4798 
4799   StringRef getString() const {
4800     return FExpr->getString().drop_front(Offset);
4801   }
4802 
4803   unsigned getByteLength() const {
4804     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4805   }
4806 
4807   unsigned getLength() const { return FExpr->getLength() - Offset; }
4808   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4809 
4810   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4811 
4812   QualType getType() const { return FExpr->getType(); }
4813 
4814   bool isAscii() const { return FExpr->isAscii(); }
4815   bool isWide() const { return FExpr->isWide(); }
4816   bool isUTF8() const { return FExpr->isUTF8(); }
4817   bool isUTF16() const { return FExpr->isUTF16(); }
4818   bool isUTF32() const { return FExpr->isUTF32(); }
4819   bool isPascal() const { return FExpr->isPascal(); }
4820 
4821   SourceLocation getLocationOfByte(
4822       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4823       const TargetInfo &Target, unsigned *StartToken = nullptr,
4824       unsigned *StartTokenByteOffset = nullptr) const {
4825     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4826                                     StartToken, StartTokenByteOffset);
4827   }
4828 
4829   SourceLocation getLocStart() const LLVM_READONLY {
4830     return FExpr->getLocStart().getLocWithOffset(Offset);
4831   }
4832 
4833   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4834 };
4835 
4836 }  // namespace
4837 
4838 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4839                               const Expr *OrigFormatExpr,
4840                               ArrayRef<const Expr *> Args,
4841                               bool HasVAListArg, unsigned format_idx,
4842                               unsigned firstDataArg,
4843                               Sema::FormatStringType Type,
4844                               bool inFunctionCall,
4845                               Sema::VariadicCallType CallType,
4846                               llvm::SmallBitVector &CheckedVarArgs,
4847                               UncoveredArgHandler &UncoveredArg);
4848 
4849 // Determine if an expression is a string literal or constant string.
4850 // If this function returns false on the arguments to a function expecting a
4851 // format string, we will usually need to emit a warning.
4852 // True string literals are then checked by CheckFormatString.
4853 static StringLiteralCheckType
4854 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4855                       bool HasVAListArg, unsigned format_idx,
4856                       unsigned firstDataArg, Sema::FormatStringType Type,
4857                       Sema::VariadicCallType CallType, bool InFunctionCall,
4858                       llvm::SmallBitVector &CheckedVarArgs,
4859                       UncoveredArgHandler &UncoveredArg,
4860                       llvm::APSInt Offset) {
4861  tryAgain:
4862   assert(Offset.isSigned() && "invalid offset");
4863 
4864   if (E->isTypeDependent() || E->isValueDependent())
4865     return SLCT_NotALiteral;
4866 
4867   E = E->IgnoreParenCasts();
4868 
4869   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4870     // Technically -Wformat-nonliteral does not warn about this case.
4871     // The behavior of printf and friends in this case is implementation
4872     // dependent.  Ideally if the format string cannot be null then
4873     // it should have a 'nonnull' attribute in the function prototype.
4874     return SLCT_UncheckedLiteral;
4875 
4876   switch (E->getStmtClass()) {
4877   case Stmt::BinaryConditionalOperatorClass:
4878   case Stmt::ConditionalOperatorClass: {
4879     // The expression is a literal if both sub-expressions were, and it was
4880     // completely checked only if both sub-expressions were checked.
4881     const AbstractConditionalOperator *C =
4882         cast<AbstractConditionalOperator>(E);
4883 
4884     // Determine whether it is necessary to check both sub-expressions, for
4885     // example, because the condition expression is a constant that can be
4886     // evaluated at compile time.
4887     bool CheckLeft = true, CheckRight = true;
4888 
4889     bool Cond;
4890     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4891       if (Cond)
4892         CheckRight = false;
4893       else
4894         CheckLeft = false;
4895     }
4896 
4897     // We need to maintain the offsets for the right and the left hand side
4898     // separately to check if every possible indexed expression is a valid
4899     // string literal. They might have different offsets for different string
4900     // literals in the end.
4901     StringLiteralCheckType Left;
4902     if (!CheckLeft)
4903       Left = SLCT_UncheckedLiteral;
4904     else {
4905       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4906                                    HasVAListArg, format_idx, firstDataArg,
4907                                    Type, CallType, InFunctionCall,
4908                                    CheckedVarArgs, UncoveredArg, Offset);
4909       if (Left == SLCT_NotALiteral || !CheckRight) {
4910         return Left;
4911       }
4912     }
4913 
4914     StringLiteralCheckType Right =
4915         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4916                               HasVAListArg, format_idx, firstDataArg,
4917                               Type, CallType, InFunctionCall, CheckedVarArgs,
4918                               UncoveredArg, Offset);
4919 
4920     return (CheckLeft && Left < Right) ? Left : Right;
4921   }
4922 
4923   case Stmt::ImplicitCastExprClass:
4924     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4925     goto tryAgain;
4926 
4927   case Stmt::OpaqueValueExprClass:
4928     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4929       E = src;
4930       goto tryAgain;
4931     }
4932     return SLCT_NotALiteral;
4933 
4934   case Stmt::PredefinedExprClass:
4935     // While __func__, etc., are technically not string literals, they
4936     // cannot contain format specifiers and thus are not a security
4937     // liability.
4938     return SLCT_UncheckedLiteral;
4939 
4940   case Stmt::DeclRefExprClass: {
4941     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4942 
4943     // As an exception, do not flag errors for variables binding to
4944     // const string literals.
4945     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4946       bool isConstant = false;
4947       QualType T = DR->getType();
4948 
4949       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4950         isConstant = AT->getElementType().isConstant(S.Context);
4951       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4952         isConstant = T.isConstant(S.Context) &&
4953                      PT->getPointeeType().isConstant(S.Context);
4954       } else if (T->isObjCObjectPointerType()) {
4955         // In ObjC, there is usually no "const ObjectPointer" type,
4956         // so don't check if the pointee type is constant.
4957         isConstant = T.isConstant(S.Context);
4958       }
4959 
4960       if (isConstant) {
4961         if (const Expr *Init = VD->getAnyInitializer()) {
4962           // Look through initializers like const char c[] = { "foo" }
4963           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4964             if (InitList->isStringLiteralInit())
4965               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4966           }
4967           return checkFormatStringExpr(S, Init, Args,
4968                                        HasVAListArg, format_idx,
4969                                        firstDataArg, Type, CallType,
4970                                        /*InFunctionCall*/ false, CheckedVarArgs,
4971                                        UncoveredArg, Offset);
4972         }
4973       }
4974 
4975       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4976       // special check to see if the format string is a function parameter
4977       // of the function calling the printf function.  If the function
4978       // has an attribute indicating it is a printf-like function, then we
4979       // should suppress warnings concerning non-literals being used in a call
4980       // to a vprintf function.  For example:
4981       //
4982       // void
4983       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4984       //      va_list ap;
4985       //      va_start(ap, fmt);
4986       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4987       //      ...
4988       // }
4989       if (HasVAListArg) {
4990         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4991           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4992             int PVIndex = PV->getFunctionScopeIndex() + 1;
4993             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4994               // adjust for implicit parameter
4995               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4996                 if (MD->isInstance())
4997                   ++PVIndex;
4998               // We also check if the formats are compatible.
4999               // We can't pass a 'scanf' string to a 'printf' function.
5000               if (PVIndex == PVFormat->getFormatIdx() &&
5001                   Type == S.GetFormatStringType(PVFormat))
5002                 return SLCT_UncheckedLiteral;
5003             }
5004           }
5005         }
5006       }
5007     }
5008 
5009     return SLCT_NotALiteral;
5010   }
5011 
5012   case Stmt::CallExprClass:
5013   case Stmt::CXXMemberCallExprClass: {
5014     const CallExpr *CE = cast<CallExpr>(E);
5015     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5016       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5017         unsigned ArgIndex = FA->getFormatIdx();
5018         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
5019           if (MD->isInstance())
5020             --ArgIndex;
5021         const Expr *Arg = CE->getArg(ArgIndex - 1);
5022 
5023         return checkFormatStringExpr(S, Arg, Args,
5024                                      HasVAListArg, format_idx, firstDataArg,
5025                                      Type, CallType, InFunctionCall,
5026                                      CheckedVarArgs, UncoveredArg, Offset);
5027       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5028         unsigned BuiltinID = FD->getBuiltinID();
5029         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5030             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5031           const Expr *Arg = CE->getArg(0);
5032           return checkFormatStringExpr(S, Arg, Args,
5033                                        HasVAListArg, format_idx,
5034                                        firstDataArg, Type, CallType,
5035                                        InFunctionCall, CheckedVarArgs,
5036                                        UncoveredArg, Offset);
5037         }
5038       }
5039     }
5040 
5041     return SLCT_NotALiteral;
5042   }
5043   case Stmt::ObjCMessageExprClass: {
5044     const auto *ME = cast<ObjCMessageExpr>(E);
5045     if (const auto *ND = ME->getMethodDecl()) {
5046       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5047         unsigned ArgIndex = FA->getFormatIdx();
5048         const Expr *Arg = ME->getArg(ArgIndex - 1);
5049         return checkFormatStringExpr(
5050             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5051             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5052       }
5053     }
5054 
5055     return SLCT_NotALiteral;
5056   }
5057   case Stmt::ObjCStringLiteralClass:
5058   case Stmt::StringLiteralClass: {
5059     const StringLiteral *StrE = nullptr;
5060 
5061     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5062       StrE = ObjCFExpr->getString();
5063     else
5064       StrE = cast<StringLiteral>(E);
5065 
5066     if (StrE) {
5067       if (Offset.isNegative() || Offset > StrE->getLength()) {
5068         // TODO: It would be better to have an explicit warning for out of
5069         // bounds literals.
5070         return SLCT_NotALiteral;
5071       }
5072       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5073       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5074                         firstDataArg, Type, InFunctionCall, CallType,
5075                         CheckedVarArgs, UncoveredArg);
5076       return SLCT_CheckedLiteral;
5077     }
5078 
5079     return SLCT_NotALiteral;
5080   }
5081   case Stmt::BinaryOperatorClass: {
5082     llvm::APSInt LResult;
5083     llvm::APSInt RResult;
5084 
5085     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5086 
5087     // A string literal + an int offset is still a string literal.
5088     if (BinOp->isAdditiveOp()) {
5089       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5090       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5091 
5092       if (LIsInt != RIsInt) {
5093         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5094 
5095         if (LIsInt) {
5096           if (BinOpKind == BO_Add) {
5097             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5098             E = BinOp->getRHS();
5099             goto tryAgain;
5100           }
5101         } else {
5102           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5103           E = BinOp->getLHS();
5104           goto tryAgain;
5105         }
5106       }
5107     }
5108 
5109     return SLCT_NotALiteral;
5110   }
5111   case Stmt::UnaryOperatorClass: {
5112     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5113     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5114     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5115       llvm::APSInt IndexResult;
5116       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5117         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5118         E = ASE->getBase();
5119         goto tryAgain;
5120       }
5121     }
5122 
5123     return SLCT_NotALiteral;
5124   }
5125 
5126   default:
5127     return SLCT_NotALiteral;
5128   }
5129 }
5130 
5131 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5132   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5133       .Case("scanf", FST_Scanf)
5134       .Cases("printf", "printf0", FST_Printf)
5135       .Cases("NSString", "CFString", FST_NSString)
5136       .Case("strftime", FST_Strftime)
5137       .Case("strfmon", FST_Strfmon)
5138       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5139       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5140       .Case("os_trace", FST_OSLog)
5141       .Case("os_log", FST_OSLog)
5142       .Default(FST_Unknown);
5143 }
5144 
5145 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5146 /// functions) for correct use of format strings.
5147 /// Returns true if a format string has been fully checked.
5148 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5149                                 ArrayRef<const Expr *> Args,
5150                                 bool IsCXXMember,
5151                                 VariadicCallType CallType,
5152                                 SourceLocation Loc, SourceRange Range,
5153                                 llvm::SmallBitVector &CheckedVarArgs) {
5154   FormatStringInfo FSI;
5155   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5156     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5157                                 FSI.FirstDataArg, GetFormatStringType(Format),
5158                                 CallType, Loc, Range, CheckedVarArgs);
5159   return false;
5160 }
5161 
5162 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5163                                 bool HasVAListArg, unsigned format_idx,
5164                                 unsigned firstDataArg, FormatStringType Type,
5165                                 VariadicCallType CallType,
5166                                 SourceLocation Loc, SourceRange Range,
5167                                 llvm::SmallBitVector &CheckedVarArgs) {
5168   // CHECK: printf/scanf-like function is called with no format string.
5169   if (format_idx >= Args.size()) {
5170     Diag(Loc, diag::warn_missing_format_string) << Range;
5171     return false;
5172   }
5173 
5174   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5175 
5176   // CHECK: format string is not a string literal.
5177   //
5178   // Dynamically generated format strings are difficult to
5179   // automatically vet at compile time.  Requiring that format strings
5180   // are string literals: (1) permits the checking of format strings by
5181   // the compiler and thereby (2) can practically remove the source of
5182   // many format string exploits.
5183 
5184   // Format string can be either ObjC string (e.g. @"%d") or
5185   // C string (e.g. "%d")
5186   // ObjC string uses the same format specifiers as C string, so we can use
5187   // the same format string checking logic for both ObjC and C strings.
5188   UncoveredArgHandler UncoveredArg;
5189   StringLiteralCheckType CT =
5190       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5191                             format_idx, firstDataArg, Type, CallType,
5192                             /*IsFunctionCall*/ true, CheckedVarArgs,
5193                             UncoveredArg,
5194                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5195 
5196   // Generate a diagnostic where an uncovered argument is detected.
5197   if (UncoveredArg.hasUncoveredArg()) {
5198     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5199     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5200     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5201   }
5202 
5203   if (CT != SLCT_NotALiteral)
5204     // Literal format string found, check done!
5205     return CT == SLCT_CheckedLiteral;
5206 
5207   // Strftime is particular as it always uses a single 'time' argument,
5208   // so it is safe to pass a non-literal string.
5209   if (Type == FST_Strftime)
5210     return false;
5211 
5212   // Do not emit diag when the string param is a macro expansion and the
5213   // format is either NSString or CFString. This is a hack to prevent
5214   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5215   // which are usually used in place of NS and CF string literals.
5216   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5217   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5218     return false;
5219 
5220   // If there are no arguments specified, warn with -Wformat-security, otherwise
5221   // warn only with -Wformat-nonliteral.
5222   if (Args.size() == firstDataArg) {
5223     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5224       << OrigFormatExpr->getSourceRange();
5225     switch (Type) {
5226     default:
5227       break;
5228     case FST_Kprintf:
5229     case FST_FreeBSDKPrintf:
5230     case FST_Printf:
5231       Diag(FormatLoc, diag::note_format_security_fixit)
5232         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5233       break;
5234     case FST_NSString:
5235       Diag(FormatLoc, diag::note_format_security_fixit)
5236         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5237       break;
5238     }
5239   } else {
5240     Diag(FormatLoc, diag::warn_format_nonliteral)
5241       << OrigFormatExpr->getSourceRange();
5242   }
5243   return false;
5244 }
5245 
5246 namespace {
5247 
5248 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5249 protected:
5250   Sema &S;
5251   const FormatStringLiteral *FExpr;
5252   const Expr *OrigFormatExpr;
5253   const Sema::FormatStringType FSType;
5254   const unsigned FirstDataArg;
5255   const unsigned NumDataArgs;
5256   const char *Beg; // Start of format string.
5257   const bool HasVAListArg;
5258   ArrayRef<const Expr *> Args;
5259   unsigned FormatIdx;
5260   llvm::SmallBitVector CoveredArgs;
5261   bool usesPositionalArgs = false;
5262   bool atFirstArg = true;
5263   bool inFunctionCall;
5264   Sema::VariadicCallType CallType;
5265   llvm::SmallBitVector &CheckedVarArgs;
5266   UncoveredArgHandler &UncoveredArg;
5267 
5268 public:
5269   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5270                      const Expr *origFormatExpr,
5271                      const Sema::FormatStringType type, unsigned firstDataArg,
5272                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5273                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5274                      bool inFunctionCall, Sema::VariadicCallType callType,
5275                      llvm::SmallBitVector &CheckedVarArgs,
5276                      UncoveredArgHandler &UncoveredArg)
5277       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5278         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5279         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5280         inFunctionCall(inFunctionCall), CallType(callType),
5281         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5282     CoveredArgs.resize(numDataArgs);
5283     CoveredArgs.reset();
5284   }
5285 
5286   void DoneProcessing();
5287 
5288   void HandleIncompleteSpecifier(const char *startSpecifier,
5289                                  unsigned specifierLen) override;
5290 
5291   void HandleInvalidLengthModifier(
5292                            const analyze_format_string::FormatSpecifier &FS,
5293                            const analyze_format_string::ConversionSpecifier &CS,
5294                            const char *startSpecifier, unsigned specifierLen,
5295                            unsigned DiagID);
5296 
5297   void HandleNonStandardLengthModifier(
5298                     const analyze_format_string::FormatSpecifier &FS,
5299                     const char *startSpecifier, unsigned specifierLen);
5300 
5301   void HandleNonStandardConversionSpecifier(
5302                     const analyze_format_string::ConversionSpecifier &CS,
5303                     const char *startSpecifier, unsigned specifierLen);
5304 
5305   void HandlePosition(const char *startPos, unsigned posLen) override;
5306 
5307   void HandleInvalidPosition(const char *startSpecifier,
5308                              unsigned specifierLen,
5309                              analyze_format_string::PositionContext p) override;
5310 
5311   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5312 
5313   void HandleNullChar(const char *nullCharacter) override;
5314 
5315   template <typename Range>
5316   static void
5317   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5318                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5319                        bool IsStringLocation, Range StringRange,
5320                        ArrayRef<FixItHint> Fixit = None);
5321 
5322 protected:
5323   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5324                                         const char *startSpec,
5325                                         unsigned specifierLen,
5326                                         const char *csStart, unsigned csLen);
5327 
5328   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5329                                          const char *startSpec,
5330                                          unsigned specifierLen);
5331 
5332   SourceRange getFormatStringRange();
5333   CharSourceRange getSpecifierRange(const char *startSpecifier,
5334                                     unsigned specifierLen);
5335   SourceLocation getLocationOfByte(const char *x);
5336 
5337   const Expr *getDataArg(unsigned i) const;
5338 
5339   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5340                     const analyze_format_string::ConversionSpecifier &CS,
5341                     const char *startSpecifier, unsigned specifierLen,
5342                     unsigned argIndex);
5343 
5344   template <typename Range>
5345   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5346                             bool IsStringLocation, Range StringRange,
5347                             ArrayRef<FixItHint> Fixit = None);
5348 };
5349 
5350 } // namespace
5351 
5352 SourceRange CheckFormatHandler::getFormatStringRange() {
5353   return OrigFormatExpr->getSourceRange();
5354 }
5355 
5356 CharSourceRange CheckFormatHandler::
5357 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5358   SourceLocation Start = getLocationOfByte(startSpecifier);
5359   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5360 
5361   // Advance the end SourceLocation by one due to half-open ranges.
5362   End = End.getLocWithOffset(1);
5363 
5364   return CharSourceRange::getCharRange(Start, End);
5365 }
5366 
5367 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5368   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5369                                   S.getLangOpts(), S.Context.getTargetInfo());
5370 }
5371 
5372 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5373                                                    unsigned specifierLen){
5374   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5375                        getLocationOfByte(startSpecifier),
5376                        /*IsStringLocation*/true,
5377                        getSpecifierRange(startSpecifier, specifierLen));
5378 }
5379 
5380 void CheckFormatHandler::HandleInvalidLengthModifier(
5381     const analyze_format_string::FormatSpecifier &FS,
5382     const analyze_format_string::ConversionSpecifier &CS,
5383     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5384   using namespace analyze_format_string;
5385 
5386   const LengthModifier &LM = FS.getLengthModifier();
5387   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5388 
5389   // See if we know how to fix this length modifier.
5390   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5391   if (FixedLM) {
5392     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5393                          getLocationOfByte(LM.getStart()),
5394                          /*IsStringLocation*/true,
5395                          getSpecifierRange(startSpecifier, specifierLen));
5396 
5397     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5398       << FixedLM->toString()
5399       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5400 
5401   } else {
5402     FixItHint Hint;
5403     if (DiagID == diag::warn_format_nonsensical_length)
5404       Hint = FixItHint::CreateRemoval(LMRange);
5405 
5406     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5407                          getLocationOfByte(LM.getStart()),
5408                          /*IsStringLocation*/true,
5409                          getSpecifierRange(startSpecifier, specifierLen),
5410                          Hint);
5411   }
5412 }
5413 
5414 void CheckFormatHandler::HandleNonStandardLengthModifier(
5415     const analyze_format_string::FormatSpecifier &FS,
5416     const char *startSpecifier, unsigned specifierLen) {
5417   using namespace analyze_format_string;
5418 
5419   const LengthModifier &LM = FS.getLengthModifier();
5420   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5421 
5422   // See if we know how to fix this length modifier.
5423   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5424   if (FixedLM) {
5425     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5426                            << LM.toString() << 0,
5427                          getLocationOfByte(LM.getStart()),
5428                          /*IsStringLocation*/true,
5429                          getSpecifierRange(startSpecifier, specifierLen));
5430 
5431     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5432       << FixedLM->toString()
5433       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5434 
5435   } else {
5436     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5437                            << LM.toString() << 0,
5438                          getLocationOfByte(LM.getStart()),
5439                          /*IsStringLocation*/true,
5440                          getSpecifierRange(startSpecifier, specifierLen));
5441   }
5442 }
5443 
5444 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5445     const analyze_format_string::ConversionSpecifier &CS,
5446     const char *startSpecifier, unsigned specifierLen) {
5447   using namespace analyze_format_string;
5448 
5449   // See if we know how to fix this conversion specifier.
5450   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5451   if (FixedCS) {
5452     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5453                           << CS.toString() << /*conversion specifier*/1,
5454                          getLocationOfByte(CS.getStart()),
5455                          /*IsStringLocation*/true,
5456                          getSpecifierRange(startSpecifier, specifierLen));
5457 
5458     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5459     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5460       << FixedCS->toString()
5461       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5462   } else {
5463     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5464                           << CS.toString() << /*conversion specifier*/1,
5465                          getLocationOfByte(CS.getStart()),
5466                          /*IsStringLocation*/true,
5467                          getSpecifierRange(startSpecifier, specifierLen));
5468   }
5469 }
5470 
5471 void CheckFormatHandler::HandlePosition(const char *startPos,
5472                                         unsigned posLen) {
5473   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5474                                getLocationOfByte(startPos),
5475                                /*IsStringLocation*/true,
5476                                getSpecifierRange(startPos, posLen));
5477 }
5478 
5479 void
5480 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5481                                      analyze_format_string::PositionContext p) {
5482   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5483                          << (unsigned) p,
5484                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5485                        getSpecifierRange(startPos, posLen));
5486 }
5487 
5488 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5489                                             unsigned posLen) {
5490   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5491                                getLocationOfByte(startPos),
5492                                /*IsStringLocation*/true,
5493                                getSpecifierRange(startPos, posLen));
5494 }
5495 
5496 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5497   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5498     // The presence of a null character is likely an error.
5499     EmitFormatDiagnostic(
5500       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5501       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5502       getFormatStringRange());
5503   }
5504 }
5505 
5506 // Note that this may return NULL if there was an error parsing or building
5507 // one of the argument expressions.
5508 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5509   return Args[FirstDataArg + i];
5510 }
5511 
5512 void CheckFormatHandler::DoneProcessing() {
5513   // Does the number of data arguments exceed the number of
5514   // format conversions in the format string?
5515   if (!HasVAListArg) {
5516       // Find any arguments that weren't covered.
5517     CoveredArgs.flip();
5518     signed notCoveredArg = CoveredArgs.find_first();
5519     if (notCoveredArg >= 0) {
5520       assert((unsigned)notCoveredArg < NumDataArgs);
5521       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5522     } else {
5523       UncoveredArg.setAllCovered();
5524     }
5525   }
5526 }
5527 
5528 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5529                                    const Expr *ArgExpr) {
5530   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5531          "Invalid state");
5532 
5533   if (!ArgExpr)
5534     return;
5535 
5536   SourceLocation Loc = ArgExpr->getLocStart();
5537 
5538   if (S.getSourceManager().isInSystemMacro(Loc))
5539     return;
5540 
5541   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5542   for (auto E : DiagnosticExprs)
5543     PDiag << E->getSourceRange();
5544 
5545   CheckFormatHandler::EmitFormatDiagnostic(
5546                                   S, IsFunctionCall, DiagnosticExprs[0],
5547                                   PDiag, Loc, /*IsStringLocation*/false,
5548                                   DiagnosticExprs[0]->getSourceRange());
5549 }
5550 
5551 bool
5552 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5553                                                      SourceLocation Loc,
5554                                                      const char *startSpec,
5555                                                      unsigned specifierLen,
5556                                                      const char *csStart,
5557                                                      unsigned csLen) {
5558   bool keepGoing = true;
5559   if (argIndex < NumDataArgs) {
5560     // Consider the argument coverered, even though the specifier doesn't
5561     // make sense.
5562     CoveredArgs.set(argIndex);
5563   }
5564   else {
5565     // If argIndex exceeds the number of data arguments we
5566     // don't issue a warning because that is just a cascade of warnings (and
5567     // they may have intended '%%' anyway). We don't want to continue processing
5568     // the format string after this point, however, as we will like just get
5569     // gibberish when trying to match arguments.
5570     keepGoing = false;
5571   }
5572 
5573   StringRef Specifier(csStart, csLen);
5574 
5575   // If the specifier in non-printable, it could be the first byte of a UTF-8
5576   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5577   // hex value.
5578   std::string CodePointStr;
5579   if (!llvm::sys::locale::isPrint(*csStart)) {
5580     llvm::UTF32 CodePoint;
5581     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5582     const llvm::UTF8 *E =
5583         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5584     llvm::ConversionResult Result =
5585         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5586 
5587     if (Result != llvm::conversionOK) {
5588       unsigned char FirstChar = *csStart;
5589       CodePoint = (llvm::UTF32)FirstChar;
5590     }
5591 
5592     llvm::raw_string_ostream OS(CodePointStr);
5593     if (CodePoint < 256)
5594       OS << "\\x" << llvm::format("%02x", CodePoint);
5595     else if (CodePoint <= 0xFFFF)
5596       OS << "\\u" << llvm::format("%04x", CodePoint);
5597     else
5598       OS << "\\U" << llvm::format("%08x", CodePoint);
5599     OS.flush();
5600     Specifier = CodePointStr;
5601   }
5602 
5603   EmitFormatDiagnostic(
5604       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5605       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5606 
5607   return keepGoing;
5608 }
5609 
5610 void
5611 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5612                                                       const char *startSpec,
5613                                                       unsigned specifierLen) {
5614   EmitFormatDiagnostic(
5615     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5616     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5617 }
5618 
5619 bool
5620 CheckFormatHandler::CheckNumArgs(
5621   const analyze_format_string::FormatSpecifier &FS,
5622   const analyze_format_string::ConversionSpecifier &CS,
5623   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5624 
5625   if (argIndex >= NumDataArgs) {
5626     PartialDiagnostic PDiag = FS.usesPositionalArg()
5627       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5628            << (argIndex+1) << NumDataArgs)
5629       : S.PDiag(diag::warn_printf_insufficient_data_args);
5630     EmitFormatDiagnostic(
5631       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5632       getSpecifierRange(startSpecifier, specifierLen));
5633 
5634     // Since more arguments than conversion tokens are given, by extension
5635     // all arguments are covered, so mark this as so.
5636     UncoveredArg.setAllCovered();
5637     return false;
5638   }
5639   return true;
5640 }
5641 
5642 template<typename Range>
5643 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5644                                               SourceLocation Loc,
5645                                               bool IsStringLocation,
5646                                               Range StringRange,
5647                                               ArrayRef<FixItHint> FixIt) {
5648   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5649                        Loc, IsStringLocation, StringRange, FixIt);
5650 }
5651 
5652 /// \brief If the format string is not within the funcion call, emit a note
5653 /// so that the function call and string are in diagnostic messages.
5654 ///
5655 /// \param InFunctionCall if true, the format string is within the function
5656 /// call and only one diagnostic message will be produced.  Otherwise, an
5657 /// extra note will be emitted pointing to location of the format string.
5658 ///
5659 /// \param ArgumentExpr the expression that is passed as the format string
5660 /// argument in the function call.  Used for getting locations when two
5661 /// diagnostics are emitted.
5662 ///
5663 /// \param PDiag the callee should already have provided any strings for the
5664 /// diagnostic message.  This function only adds locations and fixits
5665 /// to diagnostics.
5666 ///
5667 /// \param Loc primary location for diagnostic.  If two diagnostics are
5668 /// required, one will be at Loc and a new SourceLocation will be created for
5669 /// the other one.
5670 ///
5671 /// \param IsStringLocation if true, Loc points to the format string should be
5672 /// used for the note.  Otherwise, Loc points to the argument list and will
5673 /// be used with PDiag.
5674 ///
5675 /// \param StringRange some or all of the string to highlight.  This is
5676 /// templated so it can accept either a CharSourceRange or a SourceRange.
5677 ///
5678 /// \param FixIt optional fix it hint for the format string.
5679 template <typename Range>
5680 void CheckFormatHandler::EmitFormatDiagnostic(
5681     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5682     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5683     Range StringRange, ArrayRef<FixItHint> FixIt) {
5684   if (InFunctionCall) {
5685     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5686     D << StringRange;
5687     D << FixIt;
5688   } else {
5689     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5690       << ArgumentExpr->getSourceRange();
5691 
5692     const Sema::SemaDiagnosticBuilder &Note =
5693       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5694              diag::note_format_string_defined);
5695 
5696     Note << StringRange;
5697     Note << FixIt;
5698   }
5699 }
5700 
5701 //===--- CHECK: Printf format string checking ------------------------------===//
5702 
5703 namespace {
5704 
5705 class CheckPrintfHandler : public CheckFormatHandler {
5706 public:
5707   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5708                      const Expr *origFormatExpr,
5709                      const Sema::FormatStringType type, unsigned firstDataArg,
5710                      unsigned numDataArgs, bool isObjC, const char *beg,
5711                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5712                      unsigned formatIdx, bool inFunctionCall,
5713                      Sema::VariadicCallType CallType,
5714                      llvm::SmallBitVector &CheckedVarArgs,
5715                      UncoveredArgHandler &UncoveredArg)
5716       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5717                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5718                            inFunctionCall, CallType, CheckedVarArgs,
5719                            UncoveredArg) {}
5720 
5721   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5722 
5723   /// Returns true if '%@' specifiers are allowed in the format string.
5724   bool allowsObjCArg() const {
5725     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5726            FSType == Sema::FST_OSTrace;
5727   }
5728 
5729   bool HandleInvalidPrintfConversionSpecifier(
5730                                       const analyze_printf::PrintfSpecifier &FS,
5731                                       const char *startSpecifier,
5732                                       unsigned specifierLen) override;
5733 
5734   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5735                              const char *startSpecifier,
5736                              unsigned specifierLen) override;
5737   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5738                        const char *StartSpecifier,
5739                        unsigned SpecifierLen,
5740                        const Expr *E);
5741 
5742   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5743                     const char *startSpecifier, unsigned specifierLen);
5744   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5745                            const analyze_printf::OptionalAmount &Amt,
5746                            unsigned type,
5747                            const char *startSpecifier, unsigned specifierLen);
5748   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5749                   const analyze_printf::OptionalFlag &flag,
5750                   const char *startSpecifier, unsigned specifierLen);
5751   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5752                          const analyze_printf::OptionalFlag &ignoredFlag,
5753                          const analyze_printf::OptionalFlag &flag,
5754                          const char *startSpecifier, unsigned specifierLen);
5755   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5756                            const Expr *E);
5757 
5758   void HandleEmptyObjCModifierFlag(const char *startFlag,
5759                                    unsigned flagLen) override;
5760 
5761   void HandleInvalidObjCModifierFlag(const char *startFlag,
5762                                             unsigned flagLen) override;
5763 
5764   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5765                                            const char *flagsEnd,
5766                                            const char *conversionPosition)
5767                                              override;
5768 };
5769 
5770 } // namespace
5771 
5772 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5773                                       const analyze_printf::PrintfSpecifier &FS,
5774                                       const char *startSpecifier,
5775                                       unsigned specifierLen) {
5776   const analyze_printf::PrintfConversionSpecifier &CS =
5777     FS.getConversionSpecifier();
5778 
5779   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5780                                           getLocationOfByte(CS.getStart()),
5781                                           startSpecifier, specifierLen,
5782                                           CS.getStart(), CS.getLength());
5783 }
5784 
5785 bool CheckPrintfHandler::HandleAmount(
5786                                const analyze_format_string::OptionalAmount &Amt,
5787                                unsigned k, const char *startSpecifier,
5788                                unsigned specifierLen) {
5789   if (Amt.hasDataArgument()) {
5790     if (!HasVAListArg) {
5791       unsigned argIndex = Amt.getArgIndex();
5792       if (argIndex >= NumDataArgs) {
5793         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5794                                << k,
5795                              getLocationOfByte(Amt.getStart()),
5796                              /*IsStringLocation*/true,
5797                              getSpecifierRange(startSpecifier, specifierLen));
5798         // Don't do any more checking.  We will just emit
5799         // spurious errors.
5800         return false;
5801       }
5802 
5803       // Type check the data argument.  It should be an 'int'.
5804       // Although not in conformance with C99, we also allow the argument to be
5805       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5806       // doesn't emit a warning for that case.
5807       CoveredArgs.set(argIndex);
5808       const Expr *Arg = getDataArg(argIndex);
5809       if (!Arg)
5810         return false;
5811 
5812       QualType T = Arg->getType();
5813 
5814       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5815       assert(AT.isValid());
5816 
5817       if (!AT.matchesType(S.Context, T)) {
5818         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5819                                << k << AT.getRepresentativeTypeName(S.Context)
5820                                << T << Arg->getSourceRange(),
5821                              getLocationOfByte(Amt.getStart()),
5822                              /*IsStringLocation*/true,
5823                              getSpecifierRange(startSpecifier, specifierLen));
5824         // Don't do any more checking.  We will just emit
5825         // spurious errors.
5826         return false;
5827       }
5828     }
5829   }
5830   return true;
5831 }
5832 
5833 void CheckPrintfHandler::HandleInvalidAmount(
5834                                       const analyze_printf::PrintfSpecifier &FS,
5835                                       const analyze_printf::OptionalAmount &Amt,
5836                                       unsigned type,
5837                                       const char *startSpecifier,
5838                                       unsigned specifierLen) {
5839   const analyze_printf::PrintfConversionSpecifier &CS =
5840     FS.getConversionSpecifier();
5841 
5842   FixItHint fixit =
5843     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5844       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5845                                  Amt.getConstantLength()))
5846       : FixItHint();
5847 
5848   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5849                          << type << CS.toString(),
5850                        getLocationOfByte(Amt.getStart()),
5851                        /*IsStringLocation*/true,
5852                        getSpecifierRange(startSpecifier, specifierLen),
5853                        fixit);
5854 }
5855 
5856 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5857                                     const analyze_printf::OptionalFlag &flag,
5858                                     const char *startSpecifier,
5859                                     unsigned specifierLen) {
5860   // Warn about pointless flag with a fixit removal.
5861   const analyze_printf::PrintfConversionSpecifier &CS =
5862     FS.getConversionSpecifier();
5863   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5864                          << flag.toString() << CS.toString(),
5865                        getLocationOfByte(flag.getPosition()),
5866                        /*IsStringLocation*/true,
5867                        getSpecifierRange(startSpecifier, specifierLen),
5868                        FixItHint::CreateRemoval(
5869                          getSpecifierRange(flag.getPosition(), 1)));
5870 }
5871 
5872 void CheckPrintfHandler::HandleIgnoredFlag(
5873                                 const analyze_printf::PrintfSpecifier &FS,
5874                                 const analyze_printf::OptionalFlag &ignoredFlag,
5875                                 const analyze_printf::OptionalFlag &flag,
5876                                 const char *startSpecifier,
5877                                 unsigned specifierLen) {
5878   // Warn about ignored flag with a fixit removal.
5879   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5880                          << ignoredFlag.toString() << flag.toString(),
5881                        getLocationOfByte(ignoredFlag.getPosition()),
5882                        /*IsStringLocation*/true,
5883                        getSpecifierRange(startSpecifier, specifierLen),
5884                        FixItHint::CreateRemoval(
5885                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5886 }
5887 
5888 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5889                                                      unsigned flagLen) {
5890   // Warn about an empty flag.
5891   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5892                        getLocationOfByte(startFlag),
5893                        /*IsStringLocation*/true,
5894                        getSpecifierRange(startFlag, flagLen));
5895 }
5896 
5897 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5898                                                        unsigned flagLen) {
5899   // Warn about an invalid flag.
5900   auto Range = getSpecifierRange(startFlag, flagLen);
5901   StringRef flag(startFlag, flagLen);
5902   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5903                       getLocationOfByte(startFlag),
5904                       /*IsStringLocation*/true,
5905                       Range, FixItHint::CreateRemoval(Range));
5906 }
5907 
5908 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5909     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5910     // Warn about using '[...]' without a '@' conversion.
5911     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5912     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5913     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5914                          getLocationOfByte(conversionPosition),
5915                          /*IsStringLocation*/true,
5916                          Range, FixItHint::CreateRemoval(Range));
5917 }
5918 
5919 // Determines if the specified is a C++ class or struct containing
5920 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5921 // "c_str()").
5922 template<typename MemberKind>
5923 static llvm::SmallPtrSet<MemberKind*, 1>
5924 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5925   const RecordType *RT = Ty->getAs<RecordType>();
5926   llvm::SmallPtrSet<MemberKind*, 1> Results;
5927 
5928   if (!RT)
5929     return Results;
5930   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5931   if (!RD || !RD->getDefinition())
5932     return Results;
5933 
5934   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5935                  Sema::LookupMemberName);
5936   R.suppressDiagnostics();
5937 
5938   // We just need to include all members of the right kind turned up by the
5939   // filter, at this point.
5940   if (S.LookupQualifiedName(R, RT->getDecl()))
5941     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5942       NamedDecl *decl = (*I)->getUnderlyingDecl();
5943       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5944         Results.insert(FK);
5945     }
5946   return Results;
5947 }
5948 
5949 /// Check if we could call '.c_str()' on an object.
5950 ///
5951 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5952 /// allow the call, or if it would be ambiguous).
5953 bool Sema::hasCStrMethod(const Expr *E) {
5954   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5955 
5956   MethodSet Results =
5957       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5958   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5959        MI != ME; ++MI)
5960     if ((*MI)->getMinRequiredArguments() == 0)
5961       return true;
5962   return false;
5963 }
5964 
5965 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5966 // better diagnostic if so. AT is assumed to be valid.
5967 // Returns true when a c_str() conversion method is found.
5968 bool CheckPrintfHandler::checkForCStrMembers(
5969     const analyze_printf::ArgType &AT, const Expr *E) {
5970   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5971 
5972   MethodSet Results =
5973       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5974 
5975   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5976        MI != ME; ++MI) {
5977     const CXXMethodDecl *Method = *MI;
5978     if (Method->getMinRequiredArguments() == 0 &&
5979         AT.matchesType(S.Context, Method->getReturnType())) {
5980       // FIXME: Suggest parens if the expression needs them.
5981       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5982       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5983           << "c_str()"
5984           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5985       return true;
5986     }
5987   }
5988 
5989   return false;
5990 }
5991 
5992 bool
5993 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5994                                             &FS,
5995                                           const char *startSpecifier,
5996                                           unsigned specifierLen) {
5997   using namespace analyze_format_string;
5998   using namespace analyze_printf;
5999 
6000   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
6001 
6002   if (FS.consumesDataArgument()) {
6003     if (atFirstArg) {
6004         atFirstArg = false;
6005         usesPositionalArgs = FS.usesPositionalArg();
6006     }
6007     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6008       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6009                                         startSpecifier, specifierLen);
6010       return false;
6011     }
6012   }
6013 
6014   // First check if the field width, precision, and conversion specifier
6015   // have matching data arguments.
6016   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6017                     startSpecifier, specifierLen)) {
6018     return false;
6019   }
6020 
6021   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6022                     startSpecifier, specifierLen)) {
6023     return false;
6024   }
6025 
6026   if (!CS.consumesDataArgument()) {
6027     // FIXME: Technically specifying a precision or field width here
6028     // makes no sense.  Worth issuing a warning at some point.
6029     return true;
6030   }
6031 
6032   // Consume the argument.
6033   unsigned argIndex = FS.getArgIndex();
6034   if (argIndex < NumDataArgs) {
6035     // The check to see if the argIndex is valid will come later.
6036     // We set the bit here because we may exit early from this
6037     // function if we encounter some other error.
6038     CoveredArgs.set(argIndex);
6039   }
6040 
6041   // FreeBSD kernel extensions.
6042   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6043       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6044     // We need at least two arguments.
6045     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6046       return false;
6047 
6048     // Claim the second argument.
6049     CoveredArgs.set(argIndex + 1);
6050 
6051     // Type check the first argument (int for %b, pointer for %D)
6052     const Expr *Ex = getDataArg(argIndex);
6053     const analyze_printf::ArgType &AT =
6054       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6055         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6056     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6057       EmitFormatDiagnostic(
6058         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6059         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6060         << false << Ex->getSourceRange(),
6061         Ex->getLocStart(), /*IsStringLocation*/false,
6062         getSpecifierRange(startSpecifier, specifierLen));
6063 
6064     // Type check the second argument (char * for both %b and %D)
6065     Ex = getDataArg(argIndex + 1);
6066     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6067     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6068       EmitFormatDiagnostic(
6069         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6070         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6071         << false << Ex->getSourceRange(),
6072         Ex->getLocStart(), /*IsStringLocation*/false,
6073         getSpecifierRange(startSpecifier, specifierLen));
6074 
6075      return true;
6076   }
6077 
6078   // Check for using an Objective-C specific conversion specifier
6079   // in a non-ObjC literal.
6080   if (!allowsObjCArg() && CS.isObjCArg()) {
6081     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6082                                                   specifierLen);
6083   }
6084 
6085   // %P can only be used with os_log.
6086   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6087     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6088                                                   specifierLen);
6089   }
6090 
6091   // %n is not allowed with os_log.
6092   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6093     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6094                          getLocationOfByte(CS.getStart()),
6095                          /*IsStringLocation*/ false,
6096                          getSpecifierRange(startSpecifier, specifierLen));
6097 
6098     return true;
6099   }
6100 
6101   // Only scalars are allowed for os_trace.
6102   if (FSType == Sema::FST_OSTrace &&
6103       (CS.getKind() == ConversionSpecifier::PArg ||
6104        CS.getKind() == ConversionSpecifier::sArg ||
6105        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6106     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6107                                                   specifierLen);
6108   }
6109 
6110   // Check for use of public/private annotation outside of os_log().
6111   if (FSType != Sema::FST_OSLog) {
6112     if (FS.isPublic().isSet()) {
6113       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6114                                << "public",
6115                            getLocationOfByte(FS.isPublic().getPosition()),
6116                            /*IsStringLocation*/ false,
6117                            getSpecifierRange(startSpecifier, specifierLen));
6118     }
6119     if (FS.isPrivate().isSet()) {
6120       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6121                                << "private",
6122                            getLocationOfByte(FS.isPrivate().getPosition()),
6123                            /*IsStringLocation*/ false,
6124                            getSpecifierRange(startSpecifier, specifierLen));
6125     }
6126   }
6127 
6128   // Check for invalid use of field width
6129   if (!FS.hasValidFieldWidth()) {
6130     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6131         startSpecifier, specifierLen);
6132   }
6133 
6134   // Check for invalid use of precision
6135   if (!FS.hasValidPrecision()) {
6136     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6137         startSpecifier, specifierLen);
6138   }
6139 
6140   // Precision is mandatory for %P specifier.
6141   if (CS.getKind() == ConversionSpecifier::PArg &&
6142       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6143     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6144                          getLocationOfByte(startSpecifier),
6145                          /*IsStringLocation*/ false,
6146                          getSpecifierRange(startSpecifier, specifierLen));
6147   }
6148 
6149   // Check each flag does not conflict with any other component.
6150   if (!FS.hasValidThousandsGroupingPrefix())
6151     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6152   if (!FS.hasValidLeadingZeros())
6153     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6154   if (!FS.hasValidPlusPrefix())
6155     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6156   if (!FS.hasValidSpacePrefix())
6157     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6158   if (!FS.hasValidAlternativeForm())
6159     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6160   if (!FS.hasValidLeftJustified())
6161     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6162 
6163   // Check that flags are not ignored by another flag
6164   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6165     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6166         startSpecifier, specifierLen);
6167   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6168     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6169             startSpecifier, specifierLen);
6170 
6171   // Check the length modifier is valid with the given conversion specifier.
6172   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6173     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6174                                 diag::warn_format_nonsensical_length);
6175   else if (!FS.hasStandardLengthModifier())
6176     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6177   else if (!FS.hasStandardLengthConversionCombination())
6178     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6179                                 diag::warn_format_non_standard_conversion_spec);
6180 
6181   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6182     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6183 
6184   // The remaining checks depend on the data arguments.
6185   if (HasVAListArg)
6186     return true;
6187 
6188   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6189     return false;
6190 
6191   const Expr *Arg = getDataArg(argIndex);
6192   if (!Arg)
6193     return true;
6194 
6195   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6196 }
6197 
6198 static bool requiresParensToAddCast(const Expr *E) {
6199   // FIXME: We should have a general way to reason about operator
6200   // precedence and whether parens are actually needed here.
6201   // Take care of a few common cases where they aren't.
6202   const Expr *Inside = E->IgnoreImpCasts();
6203   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6204     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6205 
6206   switch (Inside->getStmtClass()) {
6207   case Stmt::ArraySubscriptExprClass:
6208   case Stmt::CallExprClass:
6209   case Stmt::CharacterLiteralClass:
6210   case Stmt::CXXBoolLiteralExprClass:
6211   case Stmt::DeclRefExprClass:
6212   case Stmt::FloatingLiteralClass:
6213   case Stmt::IntegerLiteralClass:
6214   case Stmt::MemberExprClass:
6215   case Stmt::ObjCArrayLiteralClass:
6216   case Stmt::ObjCBoolLiteralExprClass:
6217   case Stmt::ObjCBoxedExprClass:
6218   case Stmt::ObjCDictionaryLiteralClass:
6219   case Stmt::ObjCEncodeExprClass:
6220   case Stmt::ObjCIvarRefExprClass:
6221   case Stmt::ObjCMessageExprClass:
6222   case Stmt::ObjCPropertyRefExprClass:
6223   case Stmt::ObjCStringLiteralClass:
6224   case Stmt::ObjCSubscriptRefExprClass:
6225   case Stmt::ParenExprClass:
6226   case Stmt::StringLiteralClass:
6227   case Stmt::UnaryOperatorClass:
6228     return false;
6229   default:
6230     return true;
6231   }
6232 }
6233 
6234 static std::pair<QualType, StringRef>
6235 shouldNotPrintDirectly(const ASTContext &Context,
6236                        QualType IntendedTy,
6237                        const Expr *E) {
6238   // Use a 'while' to peel off layers of typedefs.
6239   QualType TyTy = IntendedTy;
6240   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6241     StringRef Name = UserTy->getDecl()->getName();
6242     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6243       .Case("CFIndex", Context.getNSIntegerType())
6244       .Case("NSInteger", Context.getNSIntegerType())
6245       .Case("NSUInteger", Context.getNSUIntegerType())
6246       .Case("SInt32", Context.IntTy)
6247       .Case("UInt32", Context.UnsignedIntTy)
6248       .Default(QualType());
6249 
6250     if (!CastTy.isNull())
6251       return std::make_pair(CastTy, Name);
6252 
6253     TyTy = UserTy->desugar();
6254   }
6255 
6256   // Strip parens if necessary.
6257   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6258     return shouldNotPrintDirectly(Context,
6259                                   PE->getSubExpr()->getType(),
6260                                   PE->getSubExpr());
6261 
6262   // If this is a conditional expression, then its result type is constructed
6263   // via usual arithmetic conversions and thus there might be no necessary
6264   // typedef sugar there.  Recurse to operands to check for NSInteger &
6265   // Co. usage condition.
6266   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6267     QualType TrueTy, FalseTy;
6268     StringRef TrueName, FalseName;
6269 
6270     std::tie(TrueTy, TrueName) =
6271       shouldNotPrintDirectly(Context,
6272                              CO->getTrueExpr()->getType(),
6273                              CO->getTrueExpr());
6274     std::tie(FalseTy, FalseName) =
6275       shouldNotPrintDirectly(Context,
6276                              CO->getFalseExpr()->getType(),
6277                              CO->getFalseExpr());
6278 
6279     if (TrueTy == FalseTy)
6280       return std::make_pair(TrueTy, TrueName);
6281     else if (TrueTy.isNull())
6282       return std::make_pair(FalseTy, FalseName);
6283     else if (FalseTy.isNull())
6284       return std::make_pair(TrueTy, TrueName);
6285   }
6286 
6287   return std::make_pair(QualType(), StringRef());
6288 }
6289 
6290 bool
6291 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6292                                     const char *StartSpecifier,
6293                                     unsigned SpecifierLen,
6294                                     const Expr *E) {
6295   using namespace analyze_format_string;
6296   using namespace analyze_printf;
6297 
6298   // Now type check the data expression that matches the
6299   // format specifier.
6300   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6301   if (!AT.isValid())
6302     return true;
6303 
6304   QualType ExprTy = E->getType();
6305   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6306     ExprTy = TET->getUnderlyingExpr()->getType();
6307   }
6308 
6309   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6310 
6311   if (match == analyze_printf::ArgType::Match) {
6312     return true;
6313   }
6314 
6315   // Look through argument promotions for our error message's reported type.
6316   // This includes the integral and floating promotions, but excludes array
6317   // and function pointer decay; seeing that an argument intended to be a
6318   // string has type 'char [6]' is probably more confusing than 'char *'.
6319   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6320     if (ICE->getCastKind() == CK_IntegralCast ||
6321         ICE->getCastKind() == CK_FloatingCast) {
6322       E = ICE->getSubExpr();
6323       ExprTy = E->getType();
6324 
6325       // Check if we didn't match because of an implicit cast from a 'char'
6326       // or 'short' to an 'int'.  This is done because printf is a varargs
6327       // function.
6328       if (ICE->getType() == S.Context.IntTy ||
6329           ICE->getType() == S.Context.UnsignedIntTy) {
6330         // All further checking is done on the subexpression.
6331         if (AT.matchesType(S.Context, ExprTy))
6332           return true;
6333       }
6334     }
6335   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6336     // Special case for 'a', which has type 'int' in C.
6337     // Note, however, that we do /not/ want to treat multibyte constants like
6338     // 'MooV' as characters! This form is deprecated but still exists.
6339     if (ExprTy == S.Context.IntTy)
6340       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6341         ExprTy = S.Context.CharTy;
6342   }
6343 
6344   // Look through enums to their underlying type.
6345   bool IsEnum = false;
6346   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6347     ExprTy = EnumTy->getDecl()->getIntegerType();
6348     IsEnum = true;
6349   }
6350 
6351   // %C in an Objective-C context prints a unichar, not a wchar_t.
6352   // If the argument is an integer of some kind, believe the %C and suggest
6353   // a cast instead of changing the conversion specifier.
6354   QualType IntendedTy = ExprTy;
6355   if (isObjCContext() &&
6356       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6357     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6358         !ExprTy->isCharType()) {
6359       // 'unichar' is defined as a typedef of unsigned short, but we should
6360       // prefer using the typedef if it is visible.
6361       IntendedTy = S.Context.UnsignedShortTy;
6362 
6363       // While we are here, check if the value is an IntegerLiteral that happens
6364       // to be within the valid range.
6365       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6366         const llvm::APInt &V = IL->getValue();
6367         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6368           return true;
6369       }
6370 
6371       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6372                           Sema::LookupOrdinaryName);
6373       if (S.LookupName(Result, S.getCurScope())) {
6374         NamedDecl *ND = Result.getFoundDecl();
6375         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6376           if (TD->getUnderlyingType() == IntendedTy)
6377             IntendedTy = S.Context.getTypedefType(TD);
6378       }
6379     }
6380   }
6381 
6382   // Special-case some of Darwin's platform-independence types by suggesting
6383   // casts to primitive types that are known to be large enough.
6384   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6385   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6386     QualType CastTy;
6387     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6388     if (!CastTy.isNull()) {
6389       IntendedTy = CastTy;
6390       ShouldNotPrintDirectly = true;
6391     }
6392   }
6393 
6394   // We may be able to offer a FixItHint if it is a supported type.
6395   PrintfSpecifier fixedFS = FS;
6396   bool success =
6397       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6398 
6399   if (success) {
6400     // Get the fix string from the fixed format specifier
6401     SmallString<16> buf;
6402     llvm::raw_svector_ostream os(buf);
6403     fixedFS.toString(os);
6404 
6405     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6406 
6407     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6408       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6409       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6410         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6411       }
6412       // In this case, the specifier is wrong and should be changed to match
6413       // the argument.
6414       EmitFormatDiagnostic(S.PDiag(diag)
6415                                << AT.getRepresentativeTypeName(S.Context)
6416                                << IntendedTy << IsEnum << E->getSourceRange(),
6417                            E->getLocStart(),
6418                            /*IsStringLocation*/ false, SpecRange,
6419                            FixItHint::CreateReplacement(SpecRange, os.str()));
6420     } else {
6421       // The canonical type for formatting this value is different from the
6422       // actual type of the expression. (This occurs, for example, with Darwin's
6423       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6424       // should be printed as 'long' for 64-bit compatibility.)
6425       // Rather than emitting a normal format/argument mismatch, we want to
6426       // add a cast to the recommended type (and correct the format string
6427       // if necessary).
6428       SmallString<16> CastBuf;
6429       llvm::raw_svector_ostream CastFix(CastBuf);
6430       CastFix << "(";
6431       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6432       CastFix << ")";
6433 
6434       SmallVector<FixItHint,4> Hints;
6435       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6436         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6437 
6438       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6439         // If there's already a cast present, just replace it.
6440         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6441         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6442 
6443       } else if (!requiresParensToAddCast(E)) {
6444         // If the expression has high enough precedence,
6445         // just write the C-style cast.
6446         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6447                                                    CastFix.str()));
6448       } else {
6449         // Otherwise, add parens around the expression as well as the cast.
6450         CastFix << "(";
6451         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6452                                                    CastFix.str()));
6453 
6454         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6455         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6456       }
6457 
6458       if (ShouldNotPrintDirectly) {
6459         // The expression has a type that should not be printed directly.
6460         // We extract the name from the typedef because we don't want to show
6461         // the underlying type in the diagnostic.
6462         StringRef Name;
6463         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6464           Name = TypedefTy->getDecl()->getName();
6465         else
6466           Name = CastTyName;
6467         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6468                                << Name << IntendedTy << IsEnum
6469                                << E->getSourceRange(),
6470                              E->getLocStart(), /*IsStringLocation=*/false,
6471                              SpecRange, Hints);
6472       } else {
6473         // In this case, the expression could be printed using a different
6474         // specifier, but we've decided that the specifier is probably correct
6475         // and we should cast instead. Just use the normal warning message.
6476         EmitFormatDiagnostic(
6477           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6478             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6479             << E->getSourceRange(),
6480           E->getLocStart(), /*IsStringLocation*/false,
6481           SpecRange, Hints);
6482       }
6483     }
6484   } else {
6485     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6486                                                    SpecifierLen);
6487     // Since the warning for passing non-POD types to variadic functions
6488     // was deferred until now, we emit a warning for non-POD
6489     // arguments here.
6490     switch (S.isValidVarArgType(ExprTy)) {
6491     case Sema::VAK_Valid:
6492     case Sema::VAK_ValidInCXX11: {
6493       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6494       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6495         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6496       }
6497 
6498       EmitFormatDiagnostic(
6499           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6500                         << IsEnum << CSR << E->getSourceRange(),
6501           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6502       break;
6503     }
6504     case Sema::VAK_Undefined:
6505     case Sema::VAK_MSVCUndefined:
6506       EmitFormatDiagnostic(
6507         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6508           << S.getLangOpts().CPlusPlus11
6509           << ExprTy
6510           << CallType
6511           << AT.getRepresentativeTypeName(S.Context)
6512           << CSR
6513           << E->getSourceRange(),
6514         E->getLocStart(), /*IsStringLocation*/false, CSR);
6515       checkForCStrMembers(AT, E);
6516       break;
6517 
6518     case Sema::VAK_Invalid:
6519       if (ExprTy->isObjCObjectType())
6520         EmitFormatDiagnostic(
6521           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6522             << S.getLangOpts().CPlusPlus11
6523             << ExprTy
6524             << CallType
6525             << AT.getRepresentativeTypeName(S.Context)
6526             << CSR
6527             << E->getSourceRange(),
6528           E->getLocStart(), /*IsStringLocation*/false, CSR);
6529       else
6530         // FIXME: If this is an initializer list, suggest removing the braces
6531         // or inserting a cast to the target type.
6532         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6533           << isa<InitListExpr>(E) << ExprTy << CallType
6534           << AT.getRepresentativeTypeName(S.Context)
6535           << E->getSourceRange();
6536       break;
6537     }
6538 
6539     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6540            "format string specifier index out of range");
6541     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6542   }
6543 
6544   return true;
6545 }
6546 
6547 //===--- CHECK: Scanf format string checking ------------------------------===//
6548 
6549 namespace {
6550 
6551 class CheckScanfHandler : public CheckFormatHandler {
6552 public:
6553   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6554                     const Expr *origFormatExpr, Sema::FormatStringType type,
6555                     unsigned firstDataArg, unsigned numDataArgs,
6556                     const char *beg, bool hasVAListArg,
6557                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6558                     bool inFunctionCall, Sema::VariadicCallType CallType,
6559                     llvm::SmallBitVector &CheckedVarArgs,
6560                     UncoveredArgHandler &UncoveredArg)
6561       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6562                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6563                            inFunctionCall, CallType, CheckedVarArgs,
6564                            UncoveredArg) {}
6565 
6566   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6567                             const char *startSpecifier,
6568                             unsigned specifierLen) override;
6569 
6570   bool HandleInvalidScanfConversionSpecifier(
6571           const analyze_scanf::ScanfSpecifier &FS,
6572           const char *startSpecifier,
6573           unsigned specifierLen) override;
6574 
6575   void HandleIncompleteScanList(const char *start, const char *end) override;
6576 };
6577 
6578 } // namespace
6579 
6580 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6581                                                  const char *end) {
6582   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6583                        getLocationOfByte(end), /*IsStringLocation*/true,
6584                        getSpecifierRange(start, end - start));
6585 }
6586 
6587 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6588                                         const analyze_scanf::ScanfSpecifier &FS,
6589                                         const char *startSpecifier,
6590                                         unsigned specifierLen) {
6591   const analyze_scanf::ScanfConversionSpecifier &CS =
6592     FS.getConversionSpecifier();
6593 
6594   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6595                                           getLocationOfByte(CS.getStart()),
6596                                           startSpecifier, specifierLen,
6597                                           CS.getStart(), CS.getLength());
6598 }
6599 
6600 bool CheckScanfHandler::HandleScanfSpecifier(
6601                                        const analyze_scanf::ScanfSpecifier &FS,
6602                                        const char *startSpecifier,
6603                                        unsigned specifierLen) {
6604   using namespace analyze_scanf;
6605   using namespace analyze_format_string;
6606 
6607   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6608 
6609   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6610   // be used to decide if we are using positional arguments consistently.
6611   if (FS.consumesDataArgument()) {
6612     if (atFirstArg) {
6613       atFirstArg = false;
6614       usesPositionalArgs = FS.usesPositionalArg();
6615     }
6616     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6617       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6618                                         startSpecifier, specifierLen);
6619       return false;
6620     }
6621   }
6622 
6623   // Check if the field with is non-zero.
6624   const OptionalAmount &Amt = FS.getFieldWidth();
6625   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6626     if (Amt.getConstantAmount() == 0) {
6627       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6628                                                    Amt.getConstantLength());
6629       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6630                            getLocationOfByte(Amt.getStart()),
6631                            /*IsStringLocation*/true, R,
6632                            FixItHint::CreateRemoval(R));
6633     }
6634   }
6635 
6636   if (!FS.consumesDataArgument()) {
6637     // FIXME: Technically specifying a precision or field width here
6638     // makes no sense.  Worth issuing a warning at some point.
6639     return true;
6640   }
6641 
6642   // Consume the argument.
6643   unsigned argIndex = FS.getArgIndex();
6644   if (argIndex < NumDataArgs) {
6645       // The check to see if the argIndex is valid will come later.
6646       // We set the bit here because we may exit early from this
6647       // function if we encounter some other error.
6648     CoveredArgs.set(argIndex);
6649   }
6650 
6651   // Check the length modifier is valid with the given conversion specifier.
6652   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6653     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6654                                 diag::warn_format_nonsensical_length);
6655   else if (!FS.hasStandardLengthModifier())
6656     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6657   else if (!FS.hasStandardLengthConversionCombination())
6658     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6659                                 diag::warn_format_non_standard_conversion_spec);
6660 
6661   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6662     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6663 
6664   // The remaining checks depend on the data arguments.
6665   if (HasVAListArg)
6666     return true;
6667 
6668   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6669     return false;
6670 
6671   // Check that the argument type matches the format specifier.
6672   const Expr *Ex = getDataArg(argIndex);
6673   if (!Ex)
6674     return true;
6675 
6676   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6677 
6678   if (!AT.isValid()) {
6679     return true;
6680   }
6681 
6682   analyze_format_string::ArgType::MatchKind match =
6683       AT.matchesType(S.Context, Ex->getType());
6684   if (match == analyze_format_string::ArgType::Match) {
6685     return true;
6686   }
6687 
6688   ScanfSpecifier fixedFS = FS;
6689   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6690                                  S.getLangOpts(), S.Context);
6691 
6692   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6693   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6694     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6695   }
6696 
6697   if (success) {
6698     // Get the fix string from the fixed format specifier.
6699     SmallString<128> buf;
6700     llvm::raw_svector_ostream os(buf);
6701     fixedFS.toString(os);
6702 
6703     EmitFormatDiagnostic(
6704         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6705                       << Ex->getType() << false << Ex->getSourceRange(),
6706         Ex->getLocStart(),
6707         /*IsStringLocation*/ false,
6708         getSpecifierRange(startSpecifier, specifierLen),
6709         FixItHint::CreateReplacement(
6710             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6711   } else {
6712     EmitFormatDiagnostic(S.PDiag(diag)
6713                              << AT.getRepresentativeTypeName(S.Context)
6714                              << Ex->getType() << false << Ex->getSourceRange(),
6715                          Ex->getLocStart(),
6716                          /*IsStringLocation*/ false,
6717                          getSpecifierRange(startSpecifier, specifierLen));
6718   }
6719 
6720   return true;
6721 }
6722 
6723 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6724                               const Expr *OrigFormatExpr,
6725                               ArrayRef<const Expr *> Args,
6726                               bool HasVAListArg, unsigned format_idx,
6727                               unsigned firstDataArg,
6728                               Sema::FormatStringType Type,
6729                               bool inFunctionCall,
6730                               Sema::VariadicCallType CallType,
6731                               llvm::SmallBitVector &CheckedVarArgs,
6732                               UncoveredArgHandler &UncoveredArg) {
6733   // CHECK: is the format string a wide literal?
6734   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6735     CheckFormatHandler::EmitFormatDiagnostic(
6736       S, inFunctionCall, Args[format_idx],
6737       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6738       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6739     return;
6740   }
6741 
6742   // Str - The format string.  NOTE: this is NOT null-terminated!
6743   StringRef StrRef = FExpr->getString();
6744   const char *Str = StrRef.data();
6745   // Account for cases where the string literal is truncated in a declaration.
6746   const ConstantArrayType *T =
6747     S.Context.getAsConstantArrayType(FExpr->getType());
6748   assert(T && "String literal not of constant array type!");
6749   size_t TypeSize = T->getSize().getZExtValue();
6750   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6751   const unsigned numDataArgs = Args.size() - firstDataArg;
6752 
6753   // Emit a warning if the string literal is truncated and does not contain an
6754   // embedded null character.
6755   if (TypeSize <= StrRef.size() &&
6756       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6757     CheckFormatHandler::EmitFormatDiagnostic(
6758         S, inFunctionCall, Args[format_idx],
6759         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6760         FExpr->getLocStart(),
6761         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6762     return;
6763   }
6764 
6765   // CHECK: empty format string?
6766   if (StrLen == 0 && numDataArgs > 0) {
6767     CheckFormatHandler::EmitFormatDiagnostic(
6768       S, inFunctionCall, Args[format_idx],
6769       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6770       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6771     return;
6772   }
6773 
6774   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6775       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6776       Type == Sema::FST_OSTrace) {
6777     CheckPrintfHandler H(
6778         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6779         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6780         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6781         CheckedVarArgs, UncoveredArg);
6782 
6783     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6784                                                   S.getLangOpts(),
6785                                                   S.Context.getTargetInfo(),
6786                                             Type == Sema::FST_FreeBSDKPrintf))
6787       H.DoneProcessing();
6788   } else if (Type == Sema::FST_Scanf) {
6789     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6790                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6791                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6792 
6793     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6794                                                  S.getLangOpts(),
6795                                                  S.Context.getTargetInfo()))
6796       H.DoneProcessing();
6797   } // TODO: handle other formats
6798 }
6799 
6800 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6801   // Str - The format string.  NOTE: this is NOT null-terminated!
6802   StringRef StrRef = FExpr->getString();
6803   const char *Str = StrRef.data();
6804   // Account for cases where the string literal is truncated in a declaration.
6805   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6806   assert(T && "String literal not of constant array type!");
6807   size_t TypeSize = T->getSize().getZExtValue();
6808   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6809   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6810                                                          getLangOpts(),
6811                                                          Context.getTargetInfo());
6812 }
6813 
6814 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6815 
6816 // Returns the related absolute value function that is larger, of 0 if one
6817 // does not exist.
6818 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6819   switch (AbsFunction) {
6820   default:
6821     return 0;
6822 
6823   case Builtin::BI__builtin_abs:
6824     return Builtin::BI__builtin_labs;
6825   case Builtin::BI__builtin_labs:
6826     return Builtin::BI__builtin_llabs;
6827   case Builtin::BI__builtin_llabs:
6828     return 0;
6829 
6830   case Builtin::BI__builtin_fabsf:
6831     return Builtin::BI__builtin_fabs;
6832   case Builtin::BI__builtin_fabs:
6833     return Builtin::BI__builtin_fabsl;
6834   case Builtin::BI__builtin_fabsl:
6835     return 0;
6836 
6837   case Builtin::BI__builtin_cabsf:
6838     return Builtin::BI__builtin_cabs;
6839   case Builtin::BI__builtin_cabs:
6840     return Builtin::BI__builtin_cabsl;
6841   case Builtin::BI__builtin_cabsl:
6842     return 0;
6843 
6844   case Builtin::BIabs:
6845     return Builtin::BIlabs;
6846   case Builtin::BIlabs:
6847     return Builtin::BIllabs;
6848   case Builtin::BIllabs:
6849     return 0;
6850 
6851   case Builtin::BIfabsf:
6852     return Builtin::BIfabs;
6853   case Builtin::BIfabs:
6854     return Builtin::BIfabsl;
6855   case Builtin::BIfabsl:
6856     return 0;
6857 
6858   case Builtin::BIcabsf:
6859    return Builtin::BIcabs;
6860   case Builtin::BIcabs:
6861     return Builtin::BIcabsl;
6862   case Builtin::BIcabsl:
6863     return 0;
6864   }
6865 }
6866 
6867 // Returns the argument type of the absolute value function.
6868 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6869                                              unsigned AbsType) {
6870   if (AbsType == 0)
6871     return QualType();
6872 
6873   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6874   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6875   if (Error != ASTContext::GE_None)
6876     return QualType();
6877 
6878   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6879   if (!FT)
6880     return QualType();
6881 
6882   if (FT->getNumParams() != 1)
6883     return QualType();
6884 
6885   return FT->getParamType(0);
6886 }
6887 
6888 // Returns the best absolute value function, or zero, based on type and
6889 // current absolute value function.
6890 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6891                                    unsigned AbsFunctionKind) {
6892   unsigned BestKind = 0;
6893   uint64_t ArgSize = Context.getTypeSize(ArgType);
6894   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6895        Kind = getLargerAbsoluteValueFunction(Kind)) {
6896     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6897     if (Context.getTypeSize(ParamType) >= ArgSize) {
6898       if (BestKind == 0)
6899         BestKind = Kind;
6900       else if (Context.hasSameType(ParamType, ArgType)) {
6901         BestKind = Kind;
6902         break;
6903       }
6904     }
6905   }
6906   return BestKind;
6907 }
6908 
6909 enum AbsoluteValueKind {
6910   AVK_Integer,
6911   AVK_Floating,
6912   AVK_Complex
6913 };
6914 
6915 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6916   if (T->isIntegralOrEnumerationType())
6917     return AVK_Integer;
6918   if (T->isRealFloatingType())
6919     return AVK_Floating;
6920   if (T->isAnyComplexType())
6921     return AVK_Complex;
6922 
6923   llvm_unreachable("Type not integer, floating, or complex");
6924 }
6925 
6926 // Changes the absolute value function to a different type.  Preserves whether
6927 // the function is a builtin.
6928 static unsigned changeAbsFunction(unsigned AbsKind,
6929                                   AbsoluteValueKind ValueKind) {
6930   switch (ValueKind) {
6931   case AVK_Integer:
6932     switch (AbsKind) {
6933     default:
6934       return 0;
6935     case Builtin::BI__builtin_fabsf:
6936     case Builtin::BI__builtin_fabs:
6937     case Builtin::BI__builtin_fabsl:
6938     case Builtin::BI__builtin_cabsf:
6939     case Builtin::BI__builtin_cabs:
6940     case Builtin::BI__builtin_cabsl:
6941       return Builtin::BI__builtin_abs;
6942     case Builtin::BIfabsf:
6943     case Builtin::BIfabs:
6944     case Builtin::BIfabsl:
6945     case Builtin::BIcabsf:
6946     case Builtin::BIcabs:
6947     case Builtin::BIcabsl:
6948       return Builtin::BIabs;
6949     }
6950   case AVK_Floating:
6951     switch (AbsKind) {
6952     default:
6953       return 0;
6954     case Builtin::BI__builtin_abs:
6955     case Builtin::BI__builtin_labs:
6956     case Builtin::BI__builtin_llabs:
6957     case Builtin::BI__builtin_cabsf:
6958     case Builtin::BI__builtin_cabs:
6959     case Builtin::BI__builtin_cabsl:
6960       return Builtin::BI__builtin_fabsf;
6961     case Builtin::BIabs:
6962     case Builtin::BIlabs:
6963     case Builtin::BIllabs:
6964     case Builtin::BIcabsf:
6965     case Builtin::BIcabs:
6966     case Builtin::BIcabsl:
6967       return Builtin::BIfabsf;
6968     }
6969   case AVK_Complex:
6970     switch (AbsKind) {
6971     default:
6972       return 0;
6973     case Builtin::BI__builtin_abs:
6974     case Builtin::BI__builtin_labs:
6975     case Builtin::BI__builtin_llabs:
6976     case Builtin::BI__builtin_fabsf:
6977     case Builtin::BI__builtin_fabs:
6978     case Builtin::BI__builtin_fabsl:
6979       return Builtin::BI__builtin_cabsf;
6980     case Builtin::BIabs:
6981     case Builtin::BIlabs:
6982     case Builtin::BIllabs:
6983     case Builtin::BIfabsf:
6984     case Builtin::BIfabs:
6985     case Builtin::BIfabsl:
6986       return Builtin::BIcabsf;
6987     }
6988   }
6989   llvm_unreachable("Unable to convert function");
6990 }
6991 
6992 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6993   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6994   if (!FnInfo)
6995     return 0;
6996 
6997   switch (FDecl->getBuiltinID()) {
6998   default:
6999     return 0;
7000   case Builtin::BI__builtin_abs:
7001   case Builtin::BI__builtin_fabs:
7002   case Builtin::BI__builtin_fabsf:
7003   case Builtin::BI__builtin_fabsl:
7004   case Builtin::BI__builtin_labs:
7005   case Builtin::BI__builtin_llabs:
7006   case Builtin::BI__builtin_cabs:
7007   case Builtin::BI__builtin_cabsf:
7008   case Builtin::BI__builtin_cabsl:
7009   case Builtin::BIabs:
7010   case Builtin::BIlabs:
7011   case Builtin::BIllabs:
7012   case Builtin::BIfabs:
7013   case Builtin::BIfabsf:
7014   case Builtin::BIfabsl:
7015   case Builtin::BIcabs:
7016   case Builtin::BIcabsf:
7017   case Builtin::BIcabsl:
7018     return FDecl->getBuiltinID();
7019   }
7020   llvm_unreachable("Unknown Builtin type");
7021 }
7022 
7023 // If the replacement is valid, emit a note with replacement function.
7024 // Additionally, suggest including the proper header if not already included.
7025 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7026                             unsigned AbsKind, QualType ArgType) {
7027   bool EmitHeaderHint = true;
7028   const char *HeaderName = nullptr;
7029   const char *FunctionName = nullptr;
7030   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7031     FunctionName = "std::abs";
7032     if (ArgType->isIntegralOrEnumerationType()) {
7033       HeaderName = "cstdlib";
7034     } else if (ArgType->isRealFloatingType()) {
7035       HeaderName = "cmath";
7036     } else {
7037       llvm_unreachable("Invalid Type");
7038     }
7039 
7040     // Lookup all std::abs
7041     if (NamespaceDecl *Std = S.getStdNamespace()) {
7042       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7043       R.suppressDiagnostics();
7044       S.LookupQualifiedName(R, Std);
7045 
7046       for (const auto *I : R) {
7047         const FunctionDecl *FDecl = nullptr;
7048         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7049           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7050         } else {
7051           FDecl = dyn_cast<FunctionDecl>(I);
7052         }
7053         if (!FDecl)
7054           continue;
7055 
7056         // Found std::abs(), check that they are the right ones.
7057         if (FDecl->getNumParams() != 1)
7058           continue;
7059 
7060         // Check that the parameter type can handle the argument.
7061         QualType ParamType = FDecl->getParamDecl(0)->getType();
7062         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7063             S.Context.getTypeSize(ArgType) <=
7064                 S.Context.getTypeSize(ParamType)) {
7065           // Found a function, don't need the header hint.
7066           EmitHeaderHint = false;
7067           break;
7068         }
7069       }
7070     }
7071   } else {
7072     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7073     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7074 
7075     if (HeaderName) {
7076       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7077       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7078       R.suppressDiagnostics();
7079       S.LookupName(R, S.getCurScope());
7080 
7081       if (R.isSingleResult()) {
7082         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7083         if (FD && FD->getBuiltinID() == AbsKind) {
7084           EmitHeaderHint = false;
7085         } else {
7086           return;
7087         }
7088       } else if (!R.empty()) {
7089         return;
7090       }
7091     }
7092   }
7093 
7094   S.Diag(Loc, diag::note_replace_abs_function)
7095       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7096 
7097   if (!HeaderName)
7098     return;
7099 
7100   if (!EmitHeaderHint)
7101     return;
7102 
7103   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7104                                                     << FunctionName;
7105 }
7106 
7107 template <std::size_t StrLen>
7108 static bool IsStdFunction(const FunctionDecl *FDecl,
7109                           const char (&Str)[StrLen]) {
7110   if (!FDecl)
7111     return false;
7112   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7113     return false;
7114   if (!FDecl->isInStdNamespace())
7115     return false;
7116 
7117   return true;
7118 }
7119 
7120 // Warn when using the wrong abs() function.
7121 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7122                                       const FunctionDecl *FDecl) {
7123   if (Call->getNumArgs() != 1)
7124     return;
7125 
7126   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7127   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7128   if (AbsKind == 0 && !IsStdAbs)
7129     return;
7130 
7131   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7132   QualType ParamType = Call->getArg(0)->getType();
7133 
7134   // Unsigned types cannot be negative.  Suggest removing the absolute value
7135   // function call.
7136   if (ArgType->isUnsignedIntegerType()) {
7137     const char *FunctionName =
7138         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7139     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7140     Diag(Call->getExprLoc(), diag::note_remove_abs)
7141         << FunctionName
7142         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7143     return;
7144   }
7145 
7146   // Taking the absolute value of a pointer is very suspicious, they probably
7147   // wanted to index into an array, dereference a pointer, call a function, etc.
7148   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7149     unsigned DiagType = 0;
7150     if (ArgType->isFunctionType())
7151       DiagType = 1;
7152     else if (ArgType->isArrayType())
7153       DiagType = 2;
7154 
7155     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7156     return;
7157   }
7158 
7159   // std::abs has overloads which prevent most of the absolute value problems
7160   // from occurring.
7161   if (IsStdAbs)
7162     return;
7163 
7164   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7165   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7166 
7167   // The argument and parameter are the same kind.  Check if they are the right
7168   // size.
7169   if (ArgValueKind == ParamValueKind) {
7170     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7171       return;
7172 
7173     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7174     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7175         << FDecl << ArgType << ParamType;
7176 
7177     if (NewAbsKind == 0)
7178       return;
7179 
7180     emitReplacement(*this, Call->getExprLoc(),
7181                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7182     return;
7183   }
7184 
7185   // ArgValueKind != ParamValueKind
7186   // The wrong type of absolute value function was used.  Attempt to find the
7187   // proper one.
7188   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7189   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7190   if (NewAbsKind == 0)
7191     return;
7192 
7193   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7194       << FDecl << ParamValueKind << ArgValueKind;
7195 
7196   emitReplacement(*this, Call->getExprLoc(),
7197                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7198 }
7199 
7200 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7201 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7202                                 const FunctionDecl *FDecl) {
7203   if (!Call || !FDecl) return;
7204 
7205   // Ignore template specializations and macros.
7206   if (inTemplateInstantiation()) return;
7207   if (Call->getExprLoc().isMacroID()) return;
7208 
7209   // Only care about the one template argument, two function parameter std::max
7210   if (Call->getNumArgs() != 2) return;
7211   if (!IsStdFunction(FDecl, "max")) return;
7212   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7213   if (!ArgList) return;
7214   if (ArgList->size() != 1) return;
7215 
7216   // Check that template type argument is unsigned integer.
7217   const auto& TA = ArgList->get(0);
7218   if (TA.getKind() != TemplateArgument::Type) return;
7219   QualType ArgType = TA.getAsType();
7220   if (!ArgType->isUnsignedIntegerType()) return;
7221 
7222   // See if either argument is a literal zero.
7223   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7224     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7225     if (!MTE) return false;
7226     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7227     if (!Num) return false;
7228     if (Num->getValue() != 0) return false;
7229     return true;
7230   };
7231 
7232   const Expr *FirstArg = Call->getArg(0);
7233   const Expr *SecondArg = Call->getArg(1);
7234   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7235   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7236 
7237   // Only warn when exactly one argument is zero.
7238   if (IsFirstArgZero == IsSecondArgZero) return;
7239 
7240   SourceRange FirstRange = FirstArg->getSourceRange();
7241   SourceRange SecondRange = SecondArg->getSourceRange();
7242 
7243   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7244 
7245   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7246       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7247 
7248   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7249   SourceRange RemovalRange;
7250   if (IsFirstArgZero) {
7251     RemovalRange = SourceRange(FirstRange.getBegin(),
7252                                SecondRange.getBegin().getLocWithOffset(-1));
7253   } else {
7254     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7255                                SecondRange.getEnd());
7256   }
7257 
7258   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7259         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7260         << FixItHint::CreateRemoval(RemovalRange);
7261 }
7262 
7263 //===--- CHECK: Standard memory functions ---------------------------------===//
7264 
7265 /// \brief Takes the expression passed to the size_t parameter of functions
7266 /// such as memcmp, strncat, etc and warns if it's a comparison.
7267 ///
7268 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7269 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7270                                            IdentifierInfo *FnName,
7271                                            SourceLocation FnLoc,
7272                                            SourceLocation RParenLoc) {
7273   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7274   if (!Size)
7275     return false;
7276 
7277   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7278   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7279     return false;
7280 
7281   SourceRange SizeRange = Size->getSourceRange();
7282   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7283       << SizeRange << FnName;
7284   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7285       << FnName << FixItHint::CreateInsertion(
7286                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7287       << FixItHint::CreateRemoval(RParenLoc);
7288   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7289       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7290       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7291                                     ")");
7292 
7293   return true;
7294 }
7295 
7296 /// \brief Determine whether the given type is or contains a dynamic class type
7297 /// (e.g., whether it has a vtable).
7298 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7299                                                      bool &IsContained) {
7300   // Look through array types while ignoring qualifiers.
7301   const Type *Ty = T->getBaseElementTypeUnsafe();
7302   IsContained = false;
7303 
7304   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7305   RD = RD ? RD->getDefinition() : nullptr;
7306   if (!RD || RD->isInvalidDecl())
7307     return nullptr;
7308 
7309   if (RD->isDynamicClass())
7310     return RD;
7311 
7312   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7313   // It's impossible for a class to transitively contain itself by value, so
7314   // infinite recursion is impossible.
7315   for (auto *FD : RD->fields()) {
7316     bool SubContained;
7317     if (const CXXRecordDecl *ContainedRD =
7318             getContainedDynamicClass(FD->getType(), SubContained)) {
7319       IsContained = true;
7320       return ContainedRD;
7321     }
7322   }
7323 
7324   return nullptr;
7325 }
7326 
7327 /// \brief If E is a sizeof expression, returns its argument expression,
7328 /// otherwise returns NULL.
7329 static const Expr *getSizeOfExprArg(const Expr *E) {
7330   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7331       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7332     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7333       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7334 
7335   return nullptr;
7336 }
7337 
7338 /// \brief If E is a sizeof expression, returns its argument type.
7339 static QualType getSizeOfArgType(const Expr *E) {
7340   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7341       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7342     if (SizeOf->getKind() == UETT_SizeOf)
7343       return SizeOf->getTypeOfArgument();
7344 
7345   return QualType();
7346 }
7347 
7348 /// \brief Check for dangerous or invalid arguments to memset().
7349 ///
7350 /// This issues warnings on known problematic, dangerous or unspecified
7351 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7352 /// function calls.
7353 ///
7354 /// \param Call The call expression to diagnose.
7355 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7356                                    unsigned BId,
7357                                    IdentifierInfo *FnName) {
7358   assert(BId != 0);
7359 
7360   // It is possible to have a non-standard definition of memset.  Validate
7361   // we have enough arguments, and if not, abort further checking.
7362   unsigned ExpectedNumArgs =
7363       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7364   if (Call->getNumArgs() < ExpectedNumArgs)
7365     return;
7366 
7367   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7368                       BId == Builtin::BIstrndup ? 1 : 2);
7369   unsigned LenArg =
7370       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7371   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7372 
7373   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7374                                      Call->getLocStart(), Call->getRParenLoc()))
7375     return;
7376 
7377   // We have special checking when the length is a sizeof expression.
7378   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7379   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7380   llvm::FoldingSetNodeID SizeOfArgID;
7381 
7382   // Although widely used, 'bzero' is not a standard function. Be more strict
7383   // with the argument types before allowing diagnostics and only allow the
7384   // form bzero(ptr, sizeof(...)).
7385   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7386   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7387     return;
7388 
7389   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7390     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7391     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7392 
7393     QualType DestTy = Dest->getType();
7394     QualType PointeeTy;
7395     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7396       PointeeTy = DestPtrTy->getPointeeType();
7397 
7398       // Never warn about void type pointers. This can be used to suppress
7399       // false positives.
7400       if (PointeeTy->isVoidType())
7401         continue;
7402 
7403       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7404       // actually comparing the expressions for equality. Because computing the
7405       // expression IDs can be expensive, we only do this if the diagnostic is
7406       // enabled.
7407       if (SizeOfArg &&
7408           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7409                            SizeOfArg->getExprLoc())) {
7410         // We only compute IDs for expressions if the warning is enabled, and
7411         // cache the sizeof arg's ID.
7412         if (SizeOfArgID == llvm::FoldingSetNodeID())
7413           SizeOfArg->Profile(SizeOfArgID, Context, true);
7414         llvm::FoldingSetNodeID DestID;
7415         Dest->Profile(DestID, Context, true);
7416         if (DestID == SizeOfArgID) {
7417           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7418           //       over sizeof(src) as well.
7419           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7420           StringRef ReadableName = FnName->getName();
7421 
7422           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7423             if (UnaryOp->getOpcode() == UO_AddrOf)
7424               ActionIdx = 1; // If its an address-of operator, just remove it.
7425           if (!PointeeTy->isIncompleteType() &&
7426               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7427             ActionIdx = 2; // If the pointee's size is sizeof(char),
7428                            // suggest an explicit length.
7429 
7430           // If the function is defined as a builtin macro, do not show macro
7431           // expansion.
7432           SourceLocation SL = SizeOfArg->getExprLoc();
7433           SourceRange DSR = Dest->getSourceRange();
7434           SourceRange SSR = SizeOfArg->getSourceRange();
7435           SourceManager &SM = getSourceManager();
7436 
7437           if (SM.isMacroArgExpansion(SL)) {
7438             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7439             SL = SM.getSpellingLoc(SL);
7440             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7441                              SM.getSpellingLoc(DSR.getEnd()));
7442             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7443                              SM.getSpellingLoc(SSR.getEnd()));
7444           }
7445 
7446           DiagRuntimeBehavior(SL, SizeOfArg,
7447                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7448                                 << ReadableName
7449                                 << PointeeTy
7450                                 << DestTy
7451                                 << DSR
7452                                 << SSR);
7453           DiagRuntimeBehavior(SL, SizeOfArg,
7454                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7455                                 << ActionIdx
7456                                 << SSR);
7457 
7458           break;
7459         }
7460       }
7461 
7462       // Also check for cases where the sizeof argument is the exact same
7463       // type as the memory argument, and where it points to a user-defined
7464       // record type.
7465       if (SizeOfArgTy != QualType()) {
7466         if (PointeeTy->isRecordType() &&
7467             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7468           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7469                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7470                                 << FnName << SizeOfArgTy << ArgIdx
7471                                 << PointeeTy << Dest->getSourceRange()
7472                                 << LenExpr->getSourceRange());
7473           break;
7474         }
7475       }
7476     } else if (DestTy->isArrayType()) {
7477       PointeeTy = DestTy;
7478     }
7479 
7480     if (PointeeTy == QualType())
7481       continue;
7482 
7483     // Always complain about dynamic classes.
7484     bool IsContained;
7485     if (const CXXRecordDecl *ContainedRD =
7486             getContainedDynamicClass(PointeeTy, IsContained)) {
7487 
7488       unsigned OperationType = 0;
7489       // "overwritten" if we're warning about the destination for any call
7490       // but memcmp; otherwise a verb appropriate to the call.
7491       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7492         if (BId == Builtin::BImemcpy)
7493           OperationType = 1;
7494         else if(BId == Builtin::BImemmove)
7495           OperationType = 2;
7496         else if (BId == Builtin::BImemcmp)
7497           OperationType = 3;
7498       }
7499 
7500       DiagRuntimeBehavior(
7501         Dest->getExprLoc(), Dest,
7502         PDiag(diag::warn_dyn_class_memaccess)
7503           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7504           << FnName << IsContained << ContainedRD << OperationType
7505           << Call->getCallee()->getSourceRange());
7506     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7507              BId != Builtin::BImemset)
7508       DiagRuntimeBehavior(
7509         Dest->getExprLoc(), Dest,
7510         PDiag(diag::warn_arc_object_memaccess)
7511           << ArgIdx << FnName << PointeeTy
7512           << Call->getCallee()->getSourceRange());
7513     else
7514       continue;
7515 
7516     DiagRuntimeBehavior(
7517       Dest->getExprLoc(), Dest,
7518       PDiag(diag::note_bad_memaccess_silence)
7519         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7520     break;
7521   }
7522 }
7523 
7524 // A little helper routine: ignore addition and subtraction of integer literals.
7525 // This intentionally does not ignore all integer constant expressions because
7526 // we don't want to remove sizeof().
7527 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7528   Ex = Ex->IgnoreParenCasts();
7529 
7530   while (true) {
7531     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7532     if (!BO || !BO->isAdditiveOp())
7533       break;
7534 
7535     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7536     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7537 
7538     if (isa<IntegerLiteral>(RHS))
7539       Ex = LHS;
7540     else if (isa<IntegerLiteral>(LHS))
7541       Ex = RHS;
7542     else
7543       break;
7544   }
7545 
7546   return Ex;
7547 }
7548 
7549 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7550                                                       ASTContext &Context) {
7551   // Only handle constant-sized or VLAs, but not flexible members.
7552   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7553     // Only issue the FIXIT for arrays of size > 1.
7554     if (CAT->getSize().getSExtValue() <= 1)
7555       return false;
7556   } else if (!Ty->isVariableArrayType()) {
7557     return false;
7558   }
7559   return true;
7560 }
7561 
7562 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7563 // be the size of the source, instead of the destination.
7564 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7565                                     IdentifierInfo *FnName) {
7566 
7567   // Don't crash if the user has the wrong number of arguments
7568   unsigned NumArgs = Call->getNumArgs();
7569   if ((NumArgs != 3) && (NumArgs != 4))
7570     return;
7571 
7572   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7573   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7574   const Expr *CompareWithSrc = nullptr;
7575 
7576   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7577                                      Call->getLocStart(), Call->getRParenLoc()))
7578     return;
7579 
7580   // Look for 'strlcpy(dst, x, sizeof(x))'
7581   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7582     CompareWithSrc = Ex;
7583   else {
7584     // Look for 'strlcpy(dst, x, strlen(x))'
7585     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7586       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7587           SizeCall->getNumArgs() == 1)
7588         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7589     }
7590   }
7591 
7592   if (!CompareWithSrc)
7593     return;
7594 
7595   // Determine if the argument to sizeof/strlen is equal to the source
7596   // argument.  In principle there's all kinds of things you could do
7597   // here, for instance creating an == expression and evaluating it with
7598   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7599   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7600   if (!SrcArgDRE)
7601     return;
7602 
7603   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7604   if (!CompareWithSrcDRE ||
7605       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7606     return;
7607 
7608   const Expr *OriginalSizeArg = Call->getArg(2);
7609   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7610     << OriginalSizeArg->getSourceRange() << FnName;
7611 
7612   // Output a FIXIT hint if the destination is an array (rather than a
7613   // pointer to an array).  This could be enhanced to handle some
7614   // pointers if we know the actual size, like if DstArg is 'array+2'
7615   // we could say 'sizeof(array)-2'.
7616   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7617   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7618     return;
7619 
7620   SmallString<128> sizeString;
7621   llvm::raw_svector_ostream OS(sizeString);
7622   OS << "sizeof(";
7623   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7624   OS << ")";
7625 
7626   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7627     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7628                                     OS.str());
7629 }
7630 
7631 /// Check if two expressions refer to the same declaration.
7632 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7633   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7634     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7635       return D1->getDecl() == D2->getDecl();
7636   return false;
7637 }
7638 
7639 static const Expr *getStrlenExprArg(const Expr *E) {
7640   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7641     const FunctionDecl *FD = CE->getDirectCallee();
7642     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7643       return nullptr;
7644     return CE->getArg(0)->IgnoreParenCasts();
7645   }
7646   return nullptr;
7647 }
7648 
7649 // Warn on anti-patterns as the 'size' argument to strncat.
7650 // The correct size argument should look like following:
7651 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7652 void Sema::CheckStrncatArguments(const CallExpr *CE,
7653                                  IdentifierInfo *FnName) {
7654   // Don't crash if the user has the wrong number of arguments.
7655   if (CE->getNumArgs() < 3)
7656     return;
7657   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7658   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7659   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7660 
7661   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7662                                      CE->getRParenLoc()))
7663     return;
7664 
7665   // Identify common expressions, which are wrongly used as the size argument
7666   // to strncat and may lead to buffer overflows.
7667   unsigned PatternType = 0;
7668   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7669     // - sizeof(dst)
7670     if (referToTheSameDecl(SizeOfArg, DstArg))
7671       PatternType = 1;
7672     // - sizeof(src)
7673     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7674       PatternType = 2;
7675   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7676     if (BE->getOpcode() == BO_Sub) {
7677       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7678       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7679       // - sizeof(dst) - strlen(dst)
7680       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7681           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7682         PatternType = 1;
7683       // - sizeof(src) - (anything)
7684       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7685         PatternType = 2;
7686     }
7687   }
7688 
7689   if (PatternType == 0)
7690     return;
7691 
7692   // Generate the diagnostic.
7693   SourceLocation SL = LenArg->getLocStart();
7694   SourceRange SR = LenArg->getSourceRange();
7695   SourceManager &SM = getSourceManager();
7696 
7697   // If the function is defined as a builtin macro, do not show macro expansion.
7698   if (SM.isMacroArgExpansion(SL)) {
7699     SL = SM.getSpellingLoc(SL);
7700     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7701                      SM.getSpellingLoc(SR.getEnd()));
7702   }
7703 
7704   // Check if the destination is an array (rather than a pointer to an array).
7705   QualType DstTy = DstArg->getType();
7706   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7707                                                                     Context);
7708   if (!isKnownSizeArray) {
7709     if (PatternType == 1)
7710       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7711     else
7712       Diag(SL, diag::warn_strncat_src_size) << SR;
7713     return;
7714   }
7715 
7716   if (PatternType == 1)
7717     Diag(SL, diag::warn_strncat_large_size) << SR;
7718   else
7719     Diag(SL, diag::warn_strncat_src_size) << SR;
7720 
7721   SmallString<128> sizeString;
7722   llvm::raw_svector_ostream OS(sizeString);
7723   OS << "sizeof(";
7724   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7725   OS << ") - ";
7726   OS << "strlen(";
7727   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7728   OS << ") - 1";
7729 
7730   Diag(SL, diag::note_strncat_wrong_size)
7731     << FixItHint::CreateReplacement(SR, OS.str());
7732 }
7733 
7734 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7735 
7736 static const Expr *EvalVal(const Expr *E,
7737                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7738                            const Decl *ParentDecl);
7739 static const Expr *EvalAddr(const Expr *E,
7740                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7741                             const Decl *ParentDecl);
7742 
7743 /// CheckReturnStackAddr - Check if a return statement returns the address
7744 ///   of a stack variable.
7745 static void
7746 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7747                      SourceLocation ReturnLoc) {
7748   const Expr *stackE = nullptr;
7749   SmallVector<const DeclRefExpr *, 8> refVars;
7750 
7751   // Perform checking for returned stack addresses, local blocks,
7752   // label addresses or references to temporaries.
7753   if (lhsType->isPointerType() ||
7754       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7755     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7756   } else if (lhsType->isReferenceType()) {
7757     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7758   }
7759 
7760   if (!stackE)
7761     return; // Nothing suspicious was found.
7762 
7763   // Parameters are initialized in the calling scope, so taking the address
7764   // of a parameter reference doesn't need a warning.
7765   for (auto *DRE : refVars)
7766     if (isa<ParmVarDecl>(DRE->getDecl()))
7767       return;
7768 
7769   SourceLocation diagLoc;
7770   SourceRange diagRange;
7771   if (refVars.empty()) {
7772     diagLoc = stackE->getLocStart();
7773     diagRange = stackE->getSourceRange();
7774   } else {
7775     // We followed through a reference variable. 'stackE' contains the
7776     // problematic expression but we will warn at the return statement pointing
7777     // at the reference variable. We will later display the "trail" of
7778     // reference variables using notes.
7779     diagLoc = refVars[0]->getLocStart();
7780     diagRange = refVars[0]->getSourceRange();
7781   }
7782 
7783   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7784     // address of local var
7785     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7786      << DR->getDecl()->getDeclName() << diagRange;
7787   } else if (isa<BlockExpr>(stackE)) { // local block.
7788     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7789   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7790     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7791   } else { // local temporary.
7792     // If there is an LValue->RValue conversion, then the value of the
7793     // reference type is used, not the reference.
7794     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7795       if (ICE->getCastKind() == CK_LValueToRValue) {
7796         return;
7797       }
7798     }
7799     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7800      << lhsType->isReferenceType() << diagRange;
7801   }
7802 
7803   // Display the "trail" of reference variables that we followed until we
7804   // found the problematic expression using notes.
7805   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7806     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7807     // If this var binds to another reference var, show the range of the next
7808     // var, otherwise the var binds to the problematic expression, in which case
7809     // show the range of the expression.
7810     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7811                                     : stackE->getSourceRange();
7812     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7813         << VD->getDeclName() << range;
7814   }
7815 }
7816 
7817 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7818 ///  check if the expression in a return statement evaluates to an address
7819 ///  to a location on the stack, a local block, an address of a label, or a
7820 ///  reference to local temporary. The recursion is used to traverse the
7821 ///  AST of the return expression, with recursion backtracking when we
7822 ///  encounter a subexpression that (1) clearly does not lead to one of the
7823 ///  above problematic expressions (2) is something we cannot determine leads to
7824 ///  a problematic expression based on such local checking.
7825 ///
7826 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7827 ///  the expression that they point to. Such variables are added to the
7828 ///  'refVars' vector so that we know what the reference variable "trail" was.
7829 ///
7830 ///  EvalAddr processes expressions that are pointers that are used as
7831 ///  references (and not L-values).  EvalVal handles all other values.
7832 ///  At the base case of the recursion is a check for the above problematic
7833 ///  expressions.
7834 ///
7835 ///  This implementation handles:
7836 ///
7837 ///   * pointer-to-pointer casts
7838 ///   * implicit conversions from array references to pointers
7839 ///   * taking the address of fields
7840 ///   * arbitrary interplay between "&" and "*" operators
7841 ///   * pointer arithmetic from an address of a stack variable
7842 ///   * taking the address of an array element where the array is on the stack
7843 static const Expr *EvalAddr(const Expr *E,
7844                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7845                             const Decl *ParentDecl) {
7846   if (E->isTypeDependent())
7847     return nullptr;
7848 
7849   // We should only be called for evaluating pointer expressions.
7850   assert((E->getType()->isAnyPointerType() ||
7851           E->getType()->isBlockPointerType() ||
7852           E->getType()->isObjCQualifiedIdType()) &&
7853          "EvalAddr only works on pointers");
7854 
7855   E = E->IgnoreParens();
7856 
7857   // Our "symbolic interpreter" is just a dispatch off the currently
7858   // viewed AST node.  We then recursively traverse the AST by calling
7859   // EvalAddr and EvalVal appropriately.
7860   switch (E->getStmtClass()) {
7861   case Stmt::DeclRefExprClass: {
7862     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7863 
7864     // If we leave the immediate function, the lifetime isn't about to end.
7865     if (DR->refersToEnclosingVariableOrCapture())
7866       return nullptr;
7867 
7868     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7869       // If this is a reference variable, follow through to the expression that
7870       // it points to.
7871       if (V->hasLocalStorage() &&
7872           V->getType()->isReferenceType() && V->hasInit()) {
7873         // Add the reference variable to the "trail".
7874         refVars.push_back(DR);
7875         return EvalAddr(V->getInit(), refVars, ParentDecl);
7876       }
7877 
7878     return nullptr;
7879   }
7880 
7881   case Stmt::UnaryOperatorClass: {
7882     // The only unary operator that make sense to handle here
7883     // is AddrOf.  All others don't make sense as pointers.
7884     const UnaryOperator *U = cast<UnaryOperator>(E);
7885 
7886     if (U->getOpcode() == UO_AddrOf)
7887       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7888     return nullptr;
7889   }
7890 
7891   case Stmt::BinaryOperatorClass: {
7892     // Handle pointer arithmetic.  All other binary operators are not valid
7893     // in this context.
7894     const BinaryOperator *B = cast<BinaryOperator>(E);
7895     BinaryOperatorKind op = B->getOpcode();
7896 
7897     if (op != BO_Add && op != BO_Sub)
7898       return nullptr;
7899 
7900     const Expr *Base = B->getLHS();
7901 
7902     // Determine which argument is the real pointer base.  It could be
7903     // the RHS argument instead of the LHS.
7904     if (!Base->getType()->isPointerType())
7905       Base = B->getRHS();
7906 
7907     assert(Base->getType()->isPointerType());
7908     return EvalAddr(Base, refVars, ParentDecl);
7909   }
7910 
7911   // For conditional operators we need to see if either the LHS or RHS are
7912   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7913   case Stmt::ConditionalOperatorClass: {
7914     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7915 
7916     // Handle the GNU extension for missing LHS.
7917     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7918     if (const Expr *LHSExpr = C->getLHS()) {
7919       // In C++, we can have a throw-expression, which has 'void' type.
7920       if (!LHSExpr->getType()->isVoidType())
7921         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7922           return LHS;
7923     }
7924 
7925     // In C++, we can have a throw-expression, which has 'void' type.
7926     if (C->getRHS()->getType()->isVoidType())
7927       return nullptr;
7928 
7929     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7930   }
7931 
7932   case Stmt::BlockExprClass:
7933     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7934       return E; // local block.
7935     return nullptr;
7936 
7937   case Stmt::AddrLabelExprClass:
7938     return E; // address of label.
7939 
7940   case Stmt::ExprWithCleanupsClass:
7941     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7942                     ParentDecl);
7943 
7944   // For casts, we need to handle conversions from arrays to
7945   // pointer values, and pointer-to-pointer conversions.
7946   case Stmt::ImplicitCastExprClass:
7947   case Stmt::CStyleCastExprClass:
7948   case Stmt::CXXFunctionalCastExprClass:
7949   case Stmt::ObjCBridgedCastExprClass:
7950   case Stmt::CXXStaticCastExprClass:
7951   case Stmt::CXXDynamicCastExprClass:
7952   case Stmt::CXXConstCastExprClass:
7953   case Stmt::CXXReinterpretCastExprClass: {
7954     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7955     switch (cast<CastExpr>(E)->getCastKind()) {
7956     case CK_LValueToRValue:
7957     case CK_NoOp:
7958     case CK_BaseToDerived:
7959     case CK_DerivedToBase:
7960     case CK_UncheckedDerivedToBase:
7961     case CK_Dynamic:
7962     case CK_CPointerToObjCPointerCast:
7963     case CK_BlockPointerToObjCPointerCast:
7964     case CK_AnyPointerToBlockPointerCast:
7965       return EvalAddr(SubExpr, refVars, ParentDecl);
7966 
7967     case CK_ArrayToPointerDecay:
7968       return EvalVal(SubExpr, refVars, ParentDecl);
7969 
7970     case CK_BitCast:
7971       if (SubExpr->getType()->isAnyPointerType() ||
7972           SubExpr->getType()->isBlockPointerType() ||
7973           SubExpr->getType()->isObjCQualifiedIdType())
7974         return EvalAddr(SubExpr, refVars, ParentDecl);
7975       else
7976         return nullptr;
7977 
7978     default:
7979       return nullptr;
7980     }
7981   }
7982 
7983   case Stmt::MaterializeTemporaryExprClass:
7984     if (const Expr *Result =
7985             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7986                      refVars, ParentDecl))
7987       return Result;
7988     return E;
7989 
7990   // Everything else: we simply don't reason about them.
7991   default:
7992     return nullptr;
7993   }
7994 }
7995 
7996 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7997 ///   See the comments for EvalAddr for more details.
7998 static const Expr *EvalVal(const Expr *E,
7999                            SmallVectorImpl<const DeclRefExpr *> &refVars,
8000                            const Decl *ParentDecl) {
8001   do {
8002     // We should only be called for evaluating non-pointer expressions, or
8003     // expressions with a pointer type that are not used as references but
8004     // instead
8005     // are l-values (e.g., DeclRefExpr with a pointer type).
8006 
8007     // Our "symbolic interpreter" is just a dispatch off the currently
8008     // viewed AST node.  We then recursively traverse the AST by calling
8009     // EvalAddr and EvalVal appropriately.
8010 
8011     E = E->IgnoreParens();
8012     switch (E->getStmtClass()) {
8013     case Stmt::ImplicitCastExprClass: {
8014       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
8015       if (IE->getValueKind() == VK_LValue) {
8016         E = IE->getSubExpr();
8017         continue;
8018       }
8019       return nullptr;
8020     }
8021 
8022     case Stmt::ExprWithCleanupsClass:
8023       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8024                      ParentDecl);
8025 
8026     case Stmt::DeclRefExprClass: {
8027       // When we hit a DeclRefExpr we are looking at code that refers to a
8028       // variable's name. If it's not a reference variable we check if it has
8029       // local storage within the function, and if so, return the expression.
8030       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8031 
8032       // If we leave the immediate function, the lifetime isn't about to end.
8033       if (DR->refersToEnclosingVariableOrCapture())
8034         return nullptr;
8035 
8036       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8037         // Check if it refers to itself, e.g. "int& i = i;".
8038         if (V == ParentDecl)
8039           return DR;
8040 
8041         if (V->hasLocalStorage()) {
8042           if (!V->getType()->isReferenceType())
8043             return DR;
8044 
8045           // Reference variable, follow through to the expression that
8046           // it points to.
8047           if (V->hasInit()) {
8048             // Add the reference variable to the "trail".
8049             refVars.push_back(DR);
8050             return EvalVal(V->getInit(), refVars, V);
8051           }
8052         }
8053       }
8054 
8055       return nullptr;
8056     }
8057 
8058     case Stmt::UnaryOperatorClass: {
8059       // The only unary operator that make sense to handle here
8060       // is Deref.  All others don't resolve to a "name."  This includes
8061       // handling all sorts of rvalues passed to a unary operator.
8062       const UnaryOperator *U = cast<UnaryOperator>(E);
8063 
8064       if (U->getOpcode() == UO_Deref)
8065         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8066 
8067       return nullptr;
8068     }
8069 
8070     case Stmt::ArraySubscriptExprClass: {
8071       // Array subscripts are potential references to data on the stack.  We
8072       // retrieve the DeclRefExpr* for the array variable if it indeed
8073       // has local storage.
8074       const auto *ASE = cast<ArraySubscriptExpr>(E);
8075       if (ASE->isTypeDependent())
8076         return nullptr;
8077       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8078     }
8079 
8080     case Stmt::OMPArraySectionExprClass: {
8081       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8082                       ParentDecl);
8083     }
8084 
8085     case Stmt::ConditionalOperatorClass: {
8086       // For conditional operators we need to see if either the LHS or RHS are
8087       // non-NULL Expr's.  If one is non-NULL, we return it.
8088       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8089 
8090       // Handle the GNU extension for missing LHS.
8091       if (const Expr *LHSExpr = C->getLHS()) {
8092         // In C++, we can have a throw-expression, which has 'void' type.
8093         if (!LHSExpr->getType()->isVoidType())
8094           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8095             return LHS;
8096       }
8097 
8098       // In C++, we can have a throw-expression, which has 'void' type.
8099       if (C->getRHS()->getType()->isVoidType())
8100         return nullptr;
8101 
8102       return EvalVal(C->getRHS(), refVars, ParentDecl);
8103     }
8104 
8105     // Accesses to members are potential references to data on the stack.
8106     case Stmt::MemberExprClass: {
8107       const MemberExpr *M = cast<MemberExpr>(E);
8108 
8109       // Check for indirect access.  We only want direct field accesses.
8110       if (M->isArrow())
8111         return nullptr;
8112 
8113       // Check whether the member type is itself a reference, in which case
8114       // we're not going to refer to the member, but to what the member refers
8115       // to.
8116       if (M->getMemberDecl()->getType()->isReferenceType())
8117         return nullptr;
8118 
8119       return EvalVal(M->getBase(), refVars, ParentDecl);
8120     }
8121 
8122     case Stmt::MaterializeTemporaryExprClass:
8123       if (const Expr *Result =
8124               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8125                       refVars, ParentDecl))
8126         return Result;
8127       return E;
8128 
8129     default:
8130       // Check that we don't return or take the address of a reference to a
8131       // temporary. This is only useful in C++.
8132       if (!E->isTypeDependent() && E->isRValue())
8133         return E;
8134 
8135       // Everything else: we simply don't reason about them.
8136       return nullptr;
8137     }
8138   } while (true);
8139 }
8140 
8141 void
8142 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8143                          SourceLocation ReturnLoc,
8144                          bool isObjCMethod,
8145                          const AttrVec *Attrs,
8146                          const FunctionDecl *FD) {
8147   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8148 
8149   // Check if the return value is null but should not be.
8150   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8151        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8152       CheckNonNullExpr(*this, RetValExp))
8153     Diag(ReturnLoc, diag::warn_null_ret)
8154       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8155 
8156   // C++11 [basic.stc.dynamic.allocation]p4:
8157   //   If an allocation function declared with a non-throwing
8158   //   exception-specification fails to allocate storage, it shall return
8159   //   a null pointer. Any other allocation function that fails to allocate
8160   //   storage shall indicate failure only by throwing an exception [...]
8161   if (FD) {
8162     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8163     if (Op == OO_New || Op == OO_Array_New) {
8164       const FunctionProtoType *Proto
8165         = FD->getType()->castAs<FunctionProtoType>();
8166       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8167           CheckNonNullExpr(*this, RetValExp))
8168         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8169           << FD << getLangOpts().CPlusPlus11;
8170     }
8171   }
8172 }
8173 
8174 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8175 
8176 /// Check for comparisons of floating point operands using != and ==.
8177 /// Issue a warning if these are no self-comparisons, as they are not likely
8178 /// to do what the programmer intended.
8179 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8180   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8181   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8182 
8183   // Special case: check for x == x (which is OK).
8184   // Do not emit warnings for such cases.
8185   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8186     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8187       if (DRL->getDecl() == DRR->getDecl())
8188         return;
8189 
8190   // Special case: check for comparisons against literals that can be exactly
8191   //  represented by APFloat.  In such cases, do not emit a warning.  This
8192   //  is a heuristic: often comparison against such literals are used to
8193   //  detect if a value in a variable has not changed.  This clearly can
8194   //  lead to false negatives.
8195   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8196     if (FLL->isExact())
8197       return;
8198   } else
8199     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8200       if (FLR->isExact())
8201         return;
8202 
8203   // Check for comparisons with builtin types.
8204   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8205     if (CL->getBuiltinCallee())
8206       return;
8207 
8208   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8209     if (CR->getBuiltinCallee())
8210       return;
8211 
8212   // Emit the diagnostic.
8213   Diag(Loc, diag::warn_floatingpoint_eq)
8214     << LHS->getSourceRange() << RHS->getSourceRange();
8215 }
8216 
8217 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8218 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8219 
8220 namespace {
8221 
8222 /// Structure recording the 'active' range of an integer-valued
8223 /// expression.
8224 struct IntRange {
8225   /// The number of bits active in the int.
8226   unsigned Width;
8227 
8228   /// True if the int is known not to have negative values.
8229   bool NonNegative;
8230 
8231   IntRange(unsigned Width, bool NonNegative)
8232       : Width(Width), NonNegative(NonNegative) {}
8233 
8234   /// Returns the range of the bool type.
8235   static IntRange forBoolType() {
8236     return IntRange(1, true);
8237   }
8238 
8239   /// Returns the range of an opaque value of the given integral type.
8240   static IntRange forValueOfType(ASTContext &C, QualType T) {
8241     return forValueOfCanonicalType(C,
8242                           T->getCanonicalTypeInternal().getTypePtr());
8243   }
8244 
8245   /// Returns the range of an opaque value of a canonical integral type.
8246   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8247     assert(T->isCanonicalUnqualified());
8248 
8249     if (const VectorType *VT = dyn_cast<VectorType>(T))
8250       T = VT->getElementType().getTypePtr();
8251     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8252       T = CT->getElementType().getTypePtr();
8253     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8254       T = AT->getValueType().getTypePtr();
8255 
8256     if (!C.getLangOpts().CPlusPlus) {
8257       // For enum types in C code, use the underlying datatype.
8258       if (const EnumType *ET = dyn_cast<EnumType>(T))
8259         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8260     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8261       // For enum types in C++, use the known bit width of the enumerators.
8262       EnumDecl *Enum = ET->getDecl();
8263       // In C++11, enums without definitions can have an explicitly specified
8264       // underlying type.  Use this type to compute the range.
8265       if (!Enum->isCompleteDefinition())
8266         return IntRange(C.getIntWidth(QualType(T, 0)),
8267                         !ET->isSignedIntegerOrEnumerationType());
8268 
8269       unsigned NumPositive = Enum->getNumPositiveBits();
8270       unsigned NumNegative = Enum->getNumNegativeBits();
8271 
8272       if (NumNegative == 0)
8273         return IntRange(NumPositive, true/*NonNegative*/);
8274       else
8275         return IntRange(std::max(NumPositive + 1, NumNegative),
8276                         false/*NonNegative*/);
8277     }
8278 
8279     const BuiltinType *BT = cast<BuiltinType>(T);
8280     assert(BT->isInteger());
8281 
8282     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8283   }
8284 
8285   /// Returns the "target" range of a canonical integral type, i.e.
8286   /// the range of values expressible in the type.
8287   ///
8288   /// This matches forValueOfCanonicalType except that enums have the
8289   /// full range of their type, not the range of their enumerators.
8290   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8291     assert(T->isCanonicalUnqualified());
8292 
8293     if (const VectorType *VT = dyn_cast<VectorType>(T))
8294       T = VT->getElementType().getTypePtr();
8295     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8296       T = CT->getElementType().getTypePtr();
8297     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8298       T = AT->getValueType().getTypePtr();
8299     if (const EnumType *ET = dyn_cast<EnumType>(T))
8300       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8301 
8302     const BuiltinType *BT = cast<BuiltinType>(T);
8303     assert(BT->isInteger());
8304 
8305     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8306   }
8307 
8308   /// Returns the supremum of two ranges: i.e. their conservative merge.
8309   static IntRange join(IntRange L, IntRange R) {
8310     return IntRange(std::max(L.Width, R.Width),
8311                     L.NonNegative && R.NonNegative);
8312   }
8313 
8314   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8315   static IntRange meet(IntRange L, IntRange R) {
8316     return IntRange(std::min(L.Width, R.Width),
8317                     L.NonNegative || R.NonNegative);
8318   }
8319 };
8320 
8321 } // namespace
8322 
8323 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8324                               unsigned MaxWidth) {
8325   if (value.isSigned() && value.isNegative())
8326     return IntRange(value.getMinSignedBits(), false);
8327 
8328   if (value.getBitWidth() > MaxWidth)
8329     value = value.trunc(MaxWidth);
8330 
8331   // isNonNegative() just checks the sign bit without considering
8332   // signedness.
8333   return IntRange(value.getActiveBits(), true);
8334 }
8335 
8336 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8337                               unsigned MaxWidth) {
8338   if (result.isInt())
8339     return GetValueRange(C, result.getInt(), MaxWidth);
8340 
8341   if (result.isVector()) {
8342     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8343     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8344       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8345       R = IntRange::join(R, El);
8346     }
8347     return R;
8348   }
8349 
8350   if (result.isComplexInt()) {
8351     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8352     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8353     return IntRange::join(R, I);
8354   }
8355 
8356   // This can happen with lossless casts to intptr_t of "based" lvalues.
8357   // Assume it might use arbitrary bits.
8358   // FIXME: The only reason we need to pass the type in here is to get
8359   // the sign right on this one case.  It would be nice if APValue
8360   // preserved this.
8361   assert(result.isLValue() || result.isAddrLabelDiff());
8362   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8363 }
8364 
8365 static QualType GetExprType(const Expr *E) {
8366   QualType Ty = E->getType();
8367   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8368     Ty = AtomicRHS->getValueType();
8369   return Ty;
8370 }
8371 
8372 /// Pseudo-evaluate the given integer expression, estimating the
8373 /// range of values it might take.
8374 ///
8375 /// \param MaxWidth - the width to which the value will be truncated
8376 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8377   E = E->IgnoreParens();
8378 
8379   // Try a full evaluation first.
8380   Expr::EvalResult result;
8381   if (E->EvaluateAsRValue(result, C))
8382     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8383 
8384   // I think we only want to look through implicit casts here; if the
8385   // user has an explicit widening cast, we should treat the value as
8386   // being of the new, wider type.
8387   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8388     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8389       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8390 
8391     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8392 
8393     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8394                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8395 
8396     // Assume that non-integer casts can span the full range of the type.
8397     if (!isIntegerCast)
8398       return OutputTypeRange;
8399 
8400     IntRange SubRange
8401       = GetExprRange(C, CE->getSubExpr(),
8402                      std::min(MaxWidth, OutputTypeRange.Width));
8403 
8404     // Bail out if the subexpr's range is as wide as the cast type.
8405     if (SubRange.Width >= OutputTypeRange.Width)
8406       return OutputTypeRange;
8407 
8408     // Otherwise, we take the smaller width, and we're non-negative if
8409     // either the output type or the subexpr is.
8410     return IntRange(SubRange.Width,
8411                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8412   }
8413 
8414   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8415     // If we can fold the condition, just take that operand.
8416     bool CondResult;
8417     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8418       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8419                                         : CO->getFalseExpr(),
8420                           MaxWidth);
8421 
8422     // Otherwise, conservatively merge.
8423     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8424     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8425     return IntRange::join(L, R);
8426   }
8427 
8428   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8429     switch (BO->getOpcode()) {
8430 
8431     // Boolean-valued operations are single-bit and positive.
8432     case BO_LAnd:
8433     case BO_LOr:
8434     case BO_LT:
8435     case BO_GT:
8436     case BO_LE:
8437     case BO_GE:
8438     case BO_EQ:
8439     case BO_NE:
8440       return IntRange::forBoolType();
8441 
8442     // The type of the assignments is the type of the LHS, so the RHS
8443     // is not necessarily the same type.
8444     case BO_MulAssign:
8445     case BO_DivAssign:
8446     case BO_RemAssign:
8447     case BO_AddAssign:
8448     case BO_SubAssign:
8449     case BO_XorAssign:
8450     case BO_OrAssign:
8451       // TODO: bitfields?
8452       return IntRange::forValueOfType(C, GetExprType(E));
8453 
8454     // Simple assignments just pass through the RHS, which will have
8455     // been coerced to the LHS type.
8456     case BO_Assign:
8457       // TODO: bitfields?
8458       return GetExprRange(C, BO->getRHS(), MaxWidth);
8459 
8460     // Operations with opaque sources are black-listed.
8461     case BO_PtrMemD:
8462     case BO_PtrMemI:
8463       return IntRange::forValueOfType(C, GetExprType(E));
8464 
8465     // Bitwise-and uses the *infinum* of the two source ranges.
8466     case BO_And:
8467     case BO_AndAssign:
8468       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8469                             GetExprRange(C, BO->getRHS(), MaxWidth));
8470 
8471     // Left shift gets black-listed based on a judgement call.
8472     case BO_Shl:
8473       // ...except that we want to treat '1 << (blah)' as logically
8474       // positive.  It's an important idiom.
8475       if (IntegerLiteral *I
8476             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8477         if (I->getValue() == 1) {
8478           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8479           return IntRange(R.Width, /*NonNegative*/ true);
8480         }
8481       }
8482       // fallthrough
8483 
8484     case BO_ShlAssign:
8485       return IntRange::forValueOfType(C, GetExprType(E));
8486 
8487     // Right shift by a constant can narrow its left argument.
8488     case BO_Shr:
8489     case BO_ShrAssign: {
8490       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8491 
8492       // If the shift amount is a positive constant, drop the width by
8493       // that much.
8494       llvm::APSInt shift;
8495       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8496           shift.isNonNegative()) {
8497         unsigned zext = shift.getZExtValue();
8498         if (zext >= L.Width)
8499           L.Width = (L.NonNegative ? 0 : 1);
8500         else
8501           L.Width -= zext;
8502       }
8503 
8504       return L;
8505     }
8506 
8507     // Comma acts as its right operand.
8508     case BO_Comma:
8509       return GetExprRange(C, BO->getRHS(), MaxWidth);
8510 
8511     // Black-list pointer subtractions.
8512     case BO_Sub:
8513       if (BO->getLHS()->getType()->isPointerType())
8514         return IntRange::forValueOfType(C, GetExprType(E));
8515       break;
8516 
8517     // The width of a division result is mostly determined by the size
8518     // of the LHS.
8519     case BO_Div: {
8520       // Don't 'pre-truncate' the operands.
8521       unsigned opWidth = C.getIntWidth(GetExprType(E));
8522       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8523 
8524       // If the divisor is constant, use that.
8525       llvm::APSInt divisor;
8526       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8527         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8528         if (log2 >= L.Width)
8529           L.Width = (L.NonNegative ? 0 : 1);
8530         else
8531           L.Width = std::min(L.Width - log2, MaxWidth);
8532         return L;
8533       }
8534 
8535       // Otherwise, just use the LHS's width.
8536       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8537       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8538     }
8539 
8540     // The result of a remainder can't be larger than the result of
8541     // either side.
8542     case BO_Rem: {
8543       // Don't 'pre-truncate' the operands.
8544       unsigned opWidth = C.getIntWidth(GetExprType(E));
8545       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8546       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8547 
8548       IntRange meet = IntRange::meet(L, R);
8549       meet.Width = std::min(meet.Width, MaxWidth);
8550       return meet;
8551     }
8552 
8553     // The default behavior is okay for these.
8554     case BO_Mul:
8555     case BO_Add:
8556     case BO_Xor:
8557     case BO_Or:
8558       break;
8559     }
8560 
8561     // The default case is to treat the operation as if it were closed
8562     // on the narrowest type that encompasses both operands.
8563     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8564     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8565     return IntRange::join(L, R);
8566   }
8567 
8568   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8569     switch (UO->getOpcode()) {
8570     // Boolean-valued operations are white-listed.
8571     case UO_LNot:
8572       return IntRange::forBoolType();
8573 
8574     // Operations with opaque sources are black-listed.
8575     case UO_Deref:
8576     case UO_AddrOf: // should be impossible
8577       return IntRange::forValueOfType(C, GetExprType(E));
8578 
8579     default:
8580       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8581     }
8582   }
8583 
8584   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8585     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8586 
8587   if (const auto *BitField = E->getSourceBitField())
8588     return IntRange(BitField->getBitWidthValue(C),
8589                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8590 
8591   return IntRange::forValueOfType(C, GetExprType(E));
8592 }
8593 
8594 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8595   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8596 }
8597 
8598 /// Checks whether the given value, which currently has the given
8599 /// source semantics, has the same value when coerced through the
8600 /// target semantics.
8601 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8602                                  const llvm::fltSemantics &Src,
8603                                  const llvm::fltSemantics &Tgt) {
8604   llvm::APFloat truncated = value;
8605 
8606   bool ignored;
8607   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8608   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8609 
8610   return truncated.bitwiseIsEqual(value);
8611 }
8612 
8613 /// Checks whether the given value, which currently has the given
8614 /// source semantics, has the same value when coerced through the
8615 /// target semantics.
8616 ///
8617 /// The value might be a vector of floats (or a complex number).
8618 static bool IsSameFloatAfterCast(const APValue &value,
8619                                  const llvm::fltSemantics &Src,
8620                                  const llvm::fltSemantics &Tgt) {
8621   if (value.isFloat())
8622     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8623 
8624   if (value.isVector()) {
8625     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8626       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8627         return false;
8628     return true;
8629   }
8630 
8631   assert(value.isComplexFloat());
8632   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8633           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8634 }
8635 
8636 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8637 
8638 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8639   // Suppress cases where we are comparing against an enum constant.
8640   if (const DeclRefExpr *DR =
8641       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8642     if (isa<EnumConstantDecl>(DR->getDecl()))
8643       return true;
8644 
8645   // Suppress cases where the '0' value is expanded from a macro.
8646   if (E->getLocStart().isMacroID())
8647     return true;
8648 
8649   return false;
8650 }
8651 
8652 static bool isNonBooleanIntegerValue(Expr *E) {
8653   return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8654 }
8655 
8656 static bool isNonBooleanUnsignedValue(Expr *E) {
8657   // We are checking that the expression is not known to have boolean value,
8658   // is an integer type; and is either unsigned after implicit casts,
8659   // or was unsigned before implicit casts.
8660   return isNonBooleanIntegerValue(E) &&
8661          (!E->getType()->isSignedIntegerType() ||
8662           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8663 }
8664 
8665 namespace {
8666 
8667 enum class LimitType {
8668   Max = 1U << 0U,  // e.g. 32767 for short
8669   Min = 1U << 1U,  // e.g. -32768 for short
8670   Both = Max | Min // When the value is both the Min and the Max limit at the
8671                    // same time; e.g. in C++, A::a in enum A { a = 0 };
8672 };
8673 
8674 } // namespace
8675 
8676 /// Checks whether Expr 'Constant' may be the
8677 /// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8678 /// of the Expr 'Other'. If true, then returns the limit type (min or max).
8679 /// The Value is the evaluation of Constant
8680 static llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant,
8681                                              Expr *Other,
8682                                              const llvm::APSInt &Value) {
8683   if (IsEnumConstOrFromMacro(S, Constant))
8684     return llvm::Optional<LimitType>();
8685 
8686   if (isNonBooleanUnsignedValue(Other) && Value == 0)
8687     return LimitType::Min;
8688 
8689   // TODO: Investigate using GetExprRange() to get tighter bounds
8690   // on the bit ranges.
8691   QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8692   if (const auto *AT = OtherT->getAs<AtomicType>())
8693     OtherT = AT->getValueType();
8694 
8695   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8696 
8697   // Special-case for C++ for enum with one enumerator with value of 0.
8698   if (OtherRange.Width == 0)
8699     return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>();
8700 
8701   if (llvm::APSInt::isSameValue(
8702           llvm::APSInt::getMaxValue(OtherRange.Width,
8703                                     OtherT->isUnsignedIntegerType()),
8704           Value))
8705     return LimitType::Max;
8706 
8707   if (llvm::APSInt::isSameValue(
8708           llvm::APSInt::getMinValue(OtherRange.Width,
8709                                     OtherT->isUnsignedIntegerType()),
8710           Value))
8711     return LimitType::Min;
8712 
8713   return llvm::None;
8714 }
8715 
8716 static bool HasEnumType(Expr *E) {
8717   // Strip off implicit integral promotions.
8718   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8719     if (ICE->getCastKind() != CK_IntegralCast &&
8720         ICE->getCastKind() != CK_NoOp)
8721       break;
8722     E = ICE->getSubExpr();
8723   }
8724 
8725   return E->getType()->isEnumeralType();
8726 }
8727 
8728 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8729                                         Expr *Constant, Expr *Other,
8730                                         const llvm::APSInt &Value,
8731                                         bool RhsConstant) {
8732   // Disable warning in template instantiations
8733   // and only analyze <, >, <= and >= operations.
8734   if (S.inTemplateInstantiation() || !E->isRelationalOp())
8735     return false;
8736 
8737   BinaryOperatorKind Op = E->getOpcode();
8738 
8739   QualType OType = Other->IgnoreParenImpCasts()->getType();
8740 
8741   llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8742 
8743   if (!(isNonBooleanIntegerValue(Other) &&
8744         (ValueType = IsTypeLimit(S, Constant, Other, Value))))
8745     return false;
8746 
8747   bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8748   bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
8749   if (ValueType != LimitType::Both) {
8750     bool ResultWhenConstNeOther =
8751         ConstIsLowerBound ^ (ValueType == LimitType::Max);
8752     if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8753       return false; // The comparison is not tautological.
8754   } else if (ResultWhenConstEqualsOther == ConstIsLowerBound)
8755     return false; // The comparison is not tautological.
8756 
8757   const bool Result = ResultWhenConstEqualsOther;
8758 
8759   unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8760                       ? (HasEnumType(Other)
8761                              ? diag::warn_unsigned_enum_always_true_comparison
8762                              : diag::warn_unsigned_always_true_comparison)
8763                       : diag::warn_tautological_constant_compare;
8764 
8765   // Should be enough for uint128 (39 decimal digits)
8766   SmallString<64> PrettySourceValue;
8767   llvm::raw_svector_ostream OS(PrettySourceValue);
8768   OS << Value;
8769 
8770   S.Diag(E->getOperatorLoc(), Diag)
8771       << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8772       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8773 
8774   return true;
8775 }
8776 
8777 static bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
8778                                          Expr *Constant, Expr *Other,
8779                                          const llvm::APSInt &Value,
8780                                          bool RhsConstant) {
8781   // Disable warning in template instantiations.
8782   if (S.inTemplateInstantiation())
8783     return false;
8784 
8785   Constant = Constant->IgnoreParenImpCasts();
8786   Other = Other->IgnoreParenImpCasts();
8787 
8788   // TODO: Investigate using GetExprRange() to get tighter bounds
8789   // on the bit ranges.
8790   QualType OtherT = Other->getType();
8791   if (const auto *AT = OtherT->getAs<AtomicType>())
8792     OtherT = AT->getValueType();
8793   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8794   unsigned OtherWidth = OtherRange.Width;
8795 
8796   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8797 
8798   BinaryOperatorKind op = E->getOpcode();
8799   bool IsTrue = true;
8800 
8801   // Used for diagnostic printout.
8802   enum {
8803     LiteralConstant = 0,
8804     CXXBoolLiteralTrue,
8805     CXXBoolLiteralFalse
8806   } LiteralOrBoolConstant = LiteralConstant;
8807 
8808   if (!OtherIsBooleanType) {
8809     QualType ConstantT = Constant->getType();
8810     QualType CommonT = E->getLHS()->getType();
8811 
8812     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8813       return false;
8814     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8815            "comparison with non-integer type");
8816 
8817     bool ConstantSigned = ConstantT->isSignedIntegerType();
8818     bool CommonSigned = CommonT->isSignedIntegerType();
8819 
8820     bool EqualityOnly = false;
8821 
8822     if (CommonSigned) {
8823       // The common type is signed, therefore no signed to unsigned conversion.
8824       if (!OtherRange.NonNegative) {
8825         // Check that the constant is representable in type OtherT.
8826         if (ConstantSigned) {
8827           if (OtherWidth >= Value.getMinSignedBits())
8828             return false;
8829         } else { // !ConstantSigned
8830           if (OtherWidth >= Value.getActiveBits() + 1)
8831             return false;
8832         }
8833       } else { // !OtherSigned
8834                // Check that the constant is representable in type OtherT.
8835         // Negative values are out of range.
8836         if (ConstantSigned) {
8837           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8838             return false;
8839         } else { // !ConstantSigned
8840           if (OtherWidth >= Value.getActiveBits())
8841             return false;
8842         }
8843       }
8844     } else { // !CommonSigned
8845       if (OtherRange.NonNegative) {
8846         if (OtherWidth >= Value.getActiveBits())
8847           return false;
8848       } else { // OtherSigned
8849         assert(!ConstantSigned &&
8850                "Two signed types converted to unsigned types.");
8851         // Check to see if the constant is representable in OtherT.
8852         if (OtherWidth > Value.getActiveBits())
8853           return false;
8854         // Check to see if the constant is equivalent to a negative value
8855         // cast to CommonT.
8856         if (S.Context.getIntWidth(ConstantT) ==
8857                 S.Context.getIntWidth(CommonT) &&
8858             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8859           return false;
8860         // The constant value rests between values that OtherT can represent
8861         // after conversion.  Relational comparison still works, but equality
8862         // comparisons will be tautological.
8863         EqualityOnly = true;
8864       }
8865     }
8866 
8867     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8868 
8869     if (op == BO_EQ || op == BO_NE) {
8870       IsTrue = op == BO_NE;
8871     } else if (EqualityOnly) {
8872       return false;
8873     } else if (RhsConstant) {
8874       if (op == BO_GT || op == BO_GE)
8875         IsTrue = !PositiveConstant;
8876       else // op == BO_LT || op == BO_LE
8877         IsTrue = PositiveConstant;
8878     } else {
8879       if (op == BO_LT || op == BO_LE)
8880         IsTrue = !PositiveConstant;
8881       else // op == BO_GT || op == BO_GE
8882         IsTrue = PositiveConstant;
8883     }
8884   } else {
8885     // Other isKnownToHaveBooleanValue
8886     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8887     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8888     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8889 
8890     static const struct LinkedConditions {
8891       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8892       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8893       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8894       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8895       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8896       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8897 
8898     } TruthTable = {
8899         // Constant on LHS.              | Constant on RHS.              |
8900         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8901         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8902         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8903         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8904         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8905         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8906         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8907       };
8908 
8909     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8910 
8911     enum ConstantValue ConstVal = Zero;
8912     if (Value.isUnsigned() || Value.isNonNegative()) {
8913       if (Value == 0) {
8914         LiteralOrBoolConstant =
8915             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8916         ConstVal = Zero;
8917       } else if (Value == 1) {
8918         LiteralOrBoolConstant =
8919             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8920         ConstVal = One;
8921       } else {
8922         LiteralOrBoolConstant = LiteralConstant;
8923         ConstVal = GT_One;
8924       }
8925     } else {
8926       ConstVal = LT_Zero;
8927     }
8928 
8929     CompareBoolWithConstantResult CmpRes;
8930 
8931     switch (op) {
8932     case BO_LT:
8933       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8934       break;
8935     case BO_GT:
8936       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8937       break;
8938     case BO_LE:
8939       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8940       break;
8941     case BO_GE:
8942       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8943       break;
8944     case BO_EQ:
8945       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8946       break;
8947     case BO_NE:
8948       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8949       break;
8950     default:
8951       CmpRes = Unkwn;
8952       break;
8953     }
8954 
8955     if (CmpRes == AFals) {
8956       IsTrue = false;
8957     } else if (CmpRes == ATrue) {
8958       IsTrue = true;
8959     } else {
8960       return false;
8961     }
8962   }
8963 
8964   // If this is a comparison to an enum constant, include that
8965   // constant in the diagnostic.
8966   const EnumConstantDecl *ED = nullptr;
8967   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8968     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8969 
8970   SmallString<64> PrettySourceValue;
8971   llvm::raw_svector_ostream OS(PrettySourceValue);
8972   if (ED)
8973     OS << '\'' << *ED << "' (" << Value << ")";
8974   else
8975     OS << Value;
8976 
8977   S.DiagRuntimeBehavior(
8978     E->getOperatorLoc(), E,
8979     S.PDiag(diag::warn_out_of_range_compare)
8980         << OS.str() << LiteralOrBoolConstant
8981         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8982         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8983 
8984    return true;
8985 }
8986 
8987 /// Analyze the operands of the given comparison.  Implements the
8988 /// fallback case from AnalyzeComparison.
8989 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8990   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8991   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8992 }
8993 
8994 /// \brief Implements -Wsign-compare.
8995 ///
8996 /// \param E the binary operator to check for warnings
8997 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8998   // The type the comparison is being performed in.
8999   QualType T = E->getLHS()->getType();
9000 
9001   // Only analyze comparison operators where both sides have been converted to
9002   // the same type.
9003   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
9004     return AnalyzeImpConvsInComparison(S, E);
9005 
9006   // Don't analyze value-dependent comparisons directly.
9007   if (E->isValueDependent())
9008     return AnalyzeImpConvsInComparison(S, E);
9009 
9010   Expr *LHS = E->getLHS();
9011   Expr *RHS = E->getRHS();
9012 
9013   if (T->isIntegralType(S.Context)) {
9014     llvm::APSInt RHSValue;
9015     llvm::APSInt LHSValue;
9016 
9017     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
9018     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
9019 
9020     // We don't care about expressions whose result is a constant.
9021     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
9022       return AnalyzeImpConvsInComparison(S, E);
9023 
9024     // We only care about expressions where just one side is literal
9025     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
9026       // Is the constant on the RHS or LHS?
9027       const bool RhsConstant = IsRHSIntegralLiteral;
9028       Expr *Const = RhsConstant ? RHS : LHS;
9029       Expr *Other = RhsConstant ? LHS : RHS;
9030       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
9031 
9032       // Check whether an integer constant comparison results in a value
9033       // of 'true' or 'false'.
9034 
9035       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
9036         return AnalyzeImpConvsInComparison(S, E);
9037 
9038       if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
9039         return AnalyzeImpConvsInComparison(S, E);
9040     }
9041   }
9042 
9043   if (!T->hasUnsignedIntegerRepresentation()) {
9044     // We don't do anything special if this isn't an unsigned integral
9045     // comparison:  we're only interested in integral comparisons, and
9046     // signed comparisons only happen in cases we don't care to warn about.
9047     return AnalyzeImpConvsInComparison(S, E);
9048   }
9049 
9050   LHS = LHS->IgnoreParenImpCasts();
9051   RHS = RHS->IgnoreParenImpCasts();
9052 
9053   // Check to see if one of the (unmodified) operands is of different
9054   // signedness.
9055   Expr *signedOperand, *unsignedOperand;
9056   if (LHS->getType()->hasSignedIntegerRepresentation()) {
9057     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
9058            "unsigned comparison between two signed integer expressions?");
9059     signedOperand = LHS;
9060     unsignedOperand = RHS;
9061   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
9062     signedOperand = RHS;
9063     unsignedOperand = LHS;
9064   } else {
9065     return AnalyzeImpConvsInComparison(S, E);
9066   }
9067 
9068   // Otherwise, calculate the effective range of the signed operand.
9069   IntRange signedRange = GetExprRange(S.Context, signedOperand);
9070 
9071   // Go ahead and analyze implicit conversions in the operands.  Note
9072   // that we skip the implicit conversions on both sides.
9073   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
9074   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
9075 
9076   // If the signed range is non-negative, -Wsign-compare won't fire.
9077   if (signedRange.NonNegative)
9078     return;
9079 
9080   // For (in)equality comparisons, if the unsigned operand is a
9081   // constant which cannot collide with a overflowed signed operand,
9082   // then reinterpreting the signed operand as unsigned will not
9083   // change the result of the comparison.
9084   if (E->isEqualityOp()) {
9085     unsigned comparisonWidth = S.Context.getIntWidth(T);
9086     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9087 
9088     // We should never be unable to prove that the unsigned operand is
9089     // non-negative.
9090     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9091 
9092     if (unsignedRange.Width < comparisonWidth)
9093       return;
9094   }
9095 
9096   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9097     S.PDiag(diag::warn_mixed_sign_comparison)
9098       << LHS->getType() << RHS->getType()
9099       << LHS->getSourceRange() << RHS->getSourceRange());
9100 }
9101 
9102 /// Analyzes an attempt to assign the given value to a bitfield.
9103 ///
9104 /// Returns true if there was something fishy about the attempt.
9105 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9106                                       SourceLocation InitLoc) {
9107   assert(Bitfield->isBitField());
9108   if (Bitfield->isInvalidDecl())
9109     return false;
9110 
9111   // White-list bool bitfields.
9112   QualType BitfieldType = Bitfield->getType();
9113   if (BitfieldType->isBooleanType())
9114      return false;
9115 
9116   if (BitfieldType->isEnumeralType()) {
9117     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9118     // If the underlying enum type was not explicitly specified as an unsigned
9119     // type and the enum contain only positive values, MSVC++ will cause an
9120     // inconsistency by storing this as a signed type.
9121     if (S.getLangOpts().CPlusPlus11 &&
9122         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9123         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9124         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9125       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9126         << BitfieldEnumDecl->getNameAsString();
9127     }
9128   }
9129 
9130   if (Bitfield->getType()->isBooleanType())
9131     return false;
9132 
9133   // Ignore value- or type-dependent expressions.
9134   if (Bitfield->getBitWidth()->isValueDependent() ||
9135       Bitfield->getBitWidth()->isTypeDependent() ||
9136       Init->isValueDependent() ||
9137       Init->isTypeDependent())
9138     return false;
9139 
9140   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9141   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9142 
9143   llvm::APSInt Value;
9144   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9145                                    Expr::SE_AllowSideEffects)) {
9146     // The RHS is not constant.  If the RHS has an enum type, make sure the
9147     // bitfield is wide enough to hold all the values of the enum without
9148     // truncation.
9149     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9150       EnumDecl *ED = EnumTy->getDecl();
9151       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9152 
9153       // Enum types are implicitly signed on Windows, so check if there are any
9154       // negative enumerators to see if the enum was intended to be signed or
9155       // not.
9156       bool SignedEnum = ED->getNumNegativeBits() > 0;
9157 
9158       // Check for surprising sign changes when assigning enum values to a
9159       // bitfield of different signedness.  If the bitfield is signed and we
9160       // have exactly the right number of bits to store this unsigned enum,
9161       // suggest changing the enum to an unsigned type. This typically happens
9162       // on Windows where unfixed enums always use an underlying type of 'int'.
9163       unsigned DiagID = 0;
9164       if (SignedEnum && !SignedBitfield) {
9165         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9166       } else if (SignedBitfield && !SignedEnum &&
9167                  ED->getNumPositiveBits() == FieldWidth) {
9168         DiagID = diag::warn_signed_bitfield_enum_conversion;
9169       }
9170 
9171       if (DiagID) {
9172         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9173         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9174         SourceRange TypeRange =
9175             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9176         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9177             << SignedEnum << TypeRange;
9178       }
9179 
9180       // Compute the required bitwidth. If the enum has negative values, we need
9181       // one more bit than the normal number of positive bits to represent the
9182       // sign bit.
9183       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9184                                                   ED->getNumNegativeBits())
9185                                        : ED->getNumPositiveBits();
9186 
9187       // Check the bitwidth.
9188       if (BitsNeeded > FieldWidth) {
9189         Expr *WidthExpr = Bitfield->getBitWidth();
9190         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9191             << Bitfield << ED;
9192         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9193             << BitsNeeded << ED << WidthExpr->getSourceRange();
9194       }
9195     }
9196 
9197     return false;
9198   }
9199 
9200   unsigned OriginalWidth = Value.getBitWidth();
9201 
9202   if (!Value.isSigned() || Value.isNegative())
9203     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9204       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9205         OriginalWidth = Value.getMinSignedBits();
9206 
9207   if (OriginalWidth <= FieldWidth)
9208     return false;
9209 
9210   // Compute the value which the bitfield will contain.
9211   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9212   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9213 
9214   // Check whether the stored value is equal to the original value.
9215   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9216   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9217     return false;
9218 
9219   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9220   // therefore don't strictly fit into a signed bitfield of width 1.
9221   if (FieldWidth == 1 && Value == 1)
9222     return false;
9223 
9224   std::string PrettyValue = Value.toString(10);
9225   std::string PrettyTrunc = TruncatedValue.toString(10);
9226 
9227   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9228     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9229     << Init->getSourceRange();
9230 
9231   return true;
9232 }
9233 
9234 /// Analyze the given simple or compound assignment for warning-worthy
9235 /// operations.
9236 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9237   // Just recurse on the LHS.
9238   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9239 
9240   // We want to recurse on the RHS as normal unless we're assigning to
9241   // a bitfield.
9242   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9243     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9244                                   E->getOperatorLoc())) {
9245       // Recurse, ignoring any implicit conversions on the RHS.
9246       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9247                                         E->getOperatorLoc());
9248     }
9249   }
9250 
9251   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9252 }
9253 
9254 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9255 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9256                             SourceLocation CContext, unsigned diag,
9257                             bool pruneControlFlow = false) {
9258   if (pruneControlFlow) {
9259     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9260                           S.PDiag(diag)
9261                             << SourceType << T << E->getSourceRange()
9262                             << SourceRange(CContext));
9263     return;
9264   }
9265   S.Diag(E->getExprLoc(), diag)
9266     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9267 }
9268 
9269 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9270 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9271                             SourceLocation CContext,
9272                             unsigned diag, bool pruneControlFlow = false) {
9273   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9274 }
9275 
9276 
9277 /// Diagnose an implicit cast from a floating point value to an integer value.
9278 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9279                                     SourceLocation CContext) {
9280   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9281   const bool PruneWarnings = S.inTemplateInstantiation();
9282 
9283   Expr *InnerE = E->IgnoreParenImpCasts();
9284   // We also want to warn on, e.g., "int i = -1.234"
9285   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9286     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9287       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9288 
9289   const bool IsLiteral =
9290       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9291 
9292   llvm::APFloat Value(0.0);
9293   bool IsConstant =
9294     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9295   if (!IsConstant) {
9296     return DiagnoseImpCast(S, E, T, CContext,
9297                            diag::warn_impcast_float_integer, PruneWarnings);
9298   }
9299 
9300   bool isExact = false;
9301 
9302   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9303                             T->hasUnsignedIntegerRepresentation());
9304   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9305                              &isExact) == llvm::APFloat::opOK &&
9306       isExact) {
9307     if (IsLiteral) return;
9308     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9309                            PruneWarnings);
9310   }
9311 
9312   unsigned DiagID = 0;
9313   if (IsLiteral) {
9314     // Warn on floating point literal to integer.
9315     DiagID = diag::warn_impcast_literal_float_to_integer;
9316   } else if (IntegerValue == 0) {
9317     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9318       return DiagnoseImpCast(S, E, T, CContext,
9319                              diag::warn_impcast_float_integer, PruneWarnings);
9320     }
9321     // Warn on non-zero to zero conversion.
9322     DiagID = diag::warn_impcast_float_to_integer_zero;
9323   } else {
9324     if (IntegerValue.isUnsigned()) {
9325       if (!IntegerValue.isMaxValue()) {
9326         return DiagnoseImpCast(S, E, T, CContext,
9327                                diag::warn_impcast_float_integer, PruneWarnings);
9328       }
9329     } else {  // IntegerValue.isSigned()
9330       if (!IntegerValue.isMaxSignedValue() &&
9331           !IntegerValue.isMinSignedValue()) {
9332         return DiagnoseImpCast(S, E, T, CContext,
9333                                diag::warn_impcast_float_integer, PruneWarnings);
9334       }
9335     }
9336     // Warn on evaluatable floating point expression to integer conversion.
9337     DiagID = diag::warn_impcast_float_to_integer;
9338   }
9339 
9340   // FIXME: Force the precision of the source value down so we don't print
9341   // digits which are usually useless (we don't really care here if we
9342   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9343   // would automatically print the shortest representation, but it's a bit
9344   // tricky to implement.
9345   SmallString<16> PrettySourceValue;
9346   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9347   precision = (precision * 59 + 195) / 196;
9348   Value.toString(PrettySourceValue, precision);
9349 
9350   SmallString<16> PrettyTargetValue;
9351   if (IsBool)
9352     PrettyTargetValue = Value.isZero() ? "false" : "true";
9353   else
9354     IntegerValue.toString(PrettyTargetValue);
9355 
9356   if (PruneWarnings) {
9357     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9358                           S.PDiag(DiagID)
9359                               << E->getType() << T.getUnqualifiedType()
9360                               << PrettySourceValue << PrettyTargetValue
9361                               << E->getSourceRange() << SourceRange(CContext));
9362   } else {
9363     S.Diag(E->getExprLoc(), DiagID)
9364         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9365         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9366   }
9367 }
9368 
9369 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9370                                       IntRange Range) {
9371   if (!Range.Width) return "0";
9372 
9373   llvm::APSInt ValueInRange = Value;
9374   ValueInRange.setIsSigned(!Range.NonNegative);
9375   ValueInRange = ValueInRange.trunc(Range.Width);
9376   return ValueInRange.toString(10);
9377 }
9378 
9379 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9380   if (!isa<ImplicitCastExpr>(Ex))
9381     return false;
9382 
9383   Expr *InnerE = Ex->IgnoreParenImpCasts();
9384   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9385   const Type *Source =
9386     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9387   if (Target->isDependentType())
9388     return false;
9389 
9390   const BuiltinType *FloatCandidateBT =
9391     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9392   const Type *BoolCandidateType = ToBool ? Target : Source;
9393 
9394   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9395           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9396 }
9397 
9398 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9399                                              SourceLocation CC) {
9400   unsigned NumArgs = TheCall->getNumArgs();
9401   for (unsigned i = 0; i < NumArgs; ++i) {
9402     Expr *CurrA = TheCall->getArg(i);
9403     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9404       continue;
9405 
9406     bool IsSwapped = ((i > 0) &&
9407         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9408     IsSwapped |= ((i < (NumArgs - 1)) &&
9409         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9410     if (IsSwapped) {
9411       // Warn on this floating-point to bool conversion.
9412       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9413                       CurrA->getType(), CC,
9414                       diag::warn_impcast_floating_point_to_bool);
9415     }
9416   }
9417 }
9418 
9419 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9420                                    SourceLocation CC) {
9421   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9422                         E->getExprLoc()))
9423     return;
9424 
9425   // Don't warn on functions which have return type nullptr_t.
9426   if (isa<CallExpr>(E))
9427     return;
9428 
9429   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9430   const Expr::NullPointerConstantKind NullKind =
9431       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9432   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9433     return;
9434 
9435   // Return if target type is a safe conversion.
9436   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9437       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9438     return;
9439 
9440   SourceLocation Loc = E->getSourceRange().getBegin();
9441 
9442   // Venture through the macro stacks to get to the source of macro arguments.
9443   // The new location is a better location than the complete location that was
9444   // passed in.
9445   while (S.SourceMgr.isMacroArgExpansion(Loc))
9446     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9447 
9448   while (S.SourceMgr.isMacroArgExpansion(CC))
9449     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9450 
9451   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9452   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9453     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9454         Loc, S.SourceMgr, S.getLangOpts());
9455     if (MacroName == "NULL")
9456       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9457   }
9458 
9459   // Only warn if the null and context location are in the same macro expansion.
9460   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9461     return;
9462 
9463   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9464       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9465       << FixItHint::CreateReplacement(Loc,
9466                                       S.getFixItZeroLiteralForType(T, Loc));
9467 }
9468 
9469 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9470                                   ObjCArrayLiteral *ArrayLiteral);
9471 
9472 static void
9473 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9474                            ObjCDictionaryLiteral *DictionaryLiteral);
9475 
9476 /// Check a single element within a collection literal against the
9477 /// target element type.
9478 static void checkObjCCollectionLiteralElement(Sema &S,
9479                                               QualType TargetElementType,
9480                                               Expr *Element,
9481                                               unsigned ElementKind) {
9482   // Skip a bitcast to 'id' or qualified 'id'.
9483   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9484     if (ICE->getCastKind() == CK_BitCast &&
9485         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9486       Element = ICE->getSubExpr();
9487   }
9488 
9489   QualType ElementType = Element->getType();
9490   ExprResult ElementResult(Element);
9491   if (ElementType->getAs<ObjCObjectPointerType>() &&
9492       S.CheckSingleAssignmentConstraints(TargetElementType,
9493                                          ElementResult,
9494                                          false, false)
9495         != Sema::Compatible) {
9496     S.Diag(Element->getLocStart(),
9497            diag::warn_objc_collection_literal_element)
9498       << ElementType << ElementKind << TargetElementType
9499       << Element->getSourceRange();
9500   }
9501 
9502   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9503     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9504   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9505     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9506 }
9507 
9508 /// Check an Objective-C array literal being converted to the given
9509 /// target type.
9510 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9511                                   ObjCArrayLiteral *ArrayLiteral) {
9512   if (!S.NSArrayDecl)
9513     return;
9514 
9515   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9516   if (!TargetObjCPtr)
9517     return;
9518 
9519   if (TargetObjCPtr->isUnspecialized() ||
9520       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9521         != S.NSArrayDecl->getCanonicalDecl())
9522     return;
9523 
9524   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9525   if (TypeArgs.size() != 1)
9526     return;
9527 
9528   QualType TargetElementType = TypeArgs[0];
9529   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9530     checkObjCCollectionLiteralElement(S, TargetElementType,
9531                                       ArrayLiteral->getElement(I),
9532                                       0);
9533   }
9534 }
9535 
9536 /// Check an Objective-C dictionary literal being converted to the given
9537 /// target type.
9538 static void
9539 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9540                            ObjCDictionaryLiteral *DictionaryLiteral) {
9541   if (!S.NSDictionaryDecl)
9542     return;
9543 
9544   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9545   if (!TargetObjCPtr)
9546     return;
9547 
9548   if (TargetObjCPtr->isUnspecialized() ||
9549       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9550         != S.NSDictionaryDecl->getCanonicalDecl())
9551     return;
9552 
9553   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9554   if (TypeArgs.size() != 2)
9555     return;
9556 
9557   QualType TargetKeyType = TypeArgs[0];
9558   QualType TargetObjectType = TypeArgs[1];
9559   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9560     auto Element = DictionaryLiteral->getKeyValueElement(I);
9561     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9562     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9563   }
9564 }
9565 
9566 // Helper function to filter out cases for constant width constant conversion.
9567 // Don't warn on char array initialization or for non-decimal values.
9568 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9569                                           SourceLocation CC) {
9570   // If initializing from a constant, and the constant starts with '0',
9571   // then it is a binary, octal, or hexadecimal.  Allow these constants
9572   // to fill all the bits, even if there is a sign change.
9573   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9574     const char FirstLiteralCharacter =
9575         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9576     if (FirstLiteralCharacter == '0')
9577       return false;
9578   }
9579 
9580   // If the CC location points to a '{', and the type is char, then assume
9581   // assume it is an array initialization.
9582   if (CC.isValid() && T->isCharType()) {
9583     const char FirstContextCharacter =
9584         S.getSourceManager().getCharacterData(CC)[0];
9585     if (FirstContextCharacter == '{')
9586       return false;
9587   }
9588 
9589   return true;
9590 }
9591 
9592 static void
9593 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9594                         bool *ICContext = nullptr) {
9595   if (E->isTypeDependent() || E->isValueDependent()) return;
9596 
9597   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9598   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9599   if (Source == Target) return;
9600   if (Target->isDependentType()) return;
9601 
9602   // If the conversion context location is invalid don't complain. We also
9603   // don't want to emit a warning if the issue occurs from the expansion of
9604   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9605   // delay this check as long as possible. Once we detect we are in that
9606   // scenario, we just return.
9607   if (CC.isInvalid())
9608     return;
9609 
9610   // Diagnose implicit casts to bool.
9611   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9612     if (isa<StringLiteral>(E))
9613       // Warn on string literal to bool.  Checks for string literals in logical
9614       // and expressions, for instance, assert(0 && "error here"), are
9615       // prevented by a check in AnalyzeImplicitConversions().
9616       return DiagnoseImpCast(S, E, T, CC,
9617                              diag::warn_impcast_string_literal_to_bool);
9618     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9619         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9620       // This covers the literal expressions that evaluate to Objective-C
9621       // objects.
9622       return DiagnoseImpCast(S, E, T, CC,
9623                              diag::warn_impcast_objective_c_literal_to_bool);
9624     }
9625     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9626       // Warn on pointer to bool conversion that is always true.
9627       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9628                                      SourceRange(CC));
9629     }
9630   }
9631 
9632   // Check implicit casts from Objective-C collection literals to specialized
9633   // collection types, e.g., NSArray<NSString *> *.
9634   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9635     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9636   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9637     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9638 
9639   // Strip vector types.
9640   if (isa<VectorType>(Source)) {
9641     if (!isa<VectorType>(Target)) {
9642       if (S.SourceMgr.isInSystemMacro(CC))
9643         return;
9644       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9645     }
9646 
9647     // If the vector cast is cast between two vectors of the same size, it is
9648     // a bitcast, not a conversion.
9649     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9650       return;
9651 
9652     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9653     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9654   }
9655   if (auto VecTy = dyn_cast<VectorType>(Target))
9656     Target = VecTy->getElementType().getTypePtr();
9657 
9658   // Strip complex types.
9659   if (isa<ComplexType>(Source)) {
9660     if (!isa<ComplexType>(Target)) {
9661       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9662         return;
9663 
9664       return DiagnoseImpCast(S, E, T, CC,
9665                              S.getLangOpts().CPlusPlus
9666                                  ? diag::err_impcast_complex_scalar
9667                                  : diag::warn_impcast_complex_scalar);
9668     }
9669 
9670     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9671     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9672   }
9673 
9674   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9675   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9676 
9677   // If the source is floating point...
9678   if (SourceBT && SourceBT->isFloatingPoint()) {
9679     // ...and the target is floating point...
9680     if (TargetBT && TargetBT->isFloatingPoint()) {
9681       // ...then warn if we're dropping FP rank.
9682 
9683       // Builtin FP kinds are ordered by increasing FP rank.
9684       if (SourceBT->getKind() > TargetBT->getKind()) {
9685         // Don't warn about float constants that are precisely
9686         // representable in the target type.
9687         Expr::EvalResult result;
9688         if (E->EvaluateAsRValue(result, S.Context)) {
9689           // Value might be a float, a float vector, or a float complex.
9690           if (IsSameFloatAfterCast(result.Val,
9691                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9692                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9693             return;
9694         }
9695 
9696         if (S.SourceMgr.isInSystemMacro(CC))
9697           return;
9698 
9699         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9700       }
9701       // ... or possibly if we're increasing rank, too
9702       else if (TargetBT->getKind() > SourceBT->getKind()) {
9703         if (S.SourceMgr.isInSystemMacro(CC))
9704           return;
9705 
9706         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9707       }
9708       return;
9709     }
9710 
9711     // If the target is integral, always warn.
9712     if (TargetBT && TargetBT->isInteger()) {
9713       if (S.SourceMgr.isInSystemMacro(CC))
9714         return;
9715 
9716       DiagnoseFloatingImpCast(S, E, T, CC);
9717     }
9718 
9719     // Detect the case where a call result is converted from floating-point to
9720     // to bool, and the final argument to the call is converted from bool, to
9721     // discover this typo:
9722     //
9723     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9724     //
9725     // FIXME: This is an incredibly special case; is there some more general
9726     // way to detect this class of misplaced-parentheses bug?
9727     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9728       // Check last argument of function call to see if it is an
9729       // implicit cast from a type matching the type the result
9730       // is being cast to.
9731       CallExpr *CEx = cast<CallExpr>(E);
9732       if (unsigned NumArgs = CEx->getNumArgs()) {
9733         Expr *LastA = CEx->getArg(NumArgs - 1);
9734         Expr *InnerE = LastA->IgnoreParenImpCasts();
9735         if (isa<ImplicitCastExpr>(LastA) &&
9736             InnerE->getType()->isBooleanType()) {
9737           // Warn on this floating-point to bool conversion
9738           DiagnoseImpCast(S, E, T, CC,
9739                           diag::warn_impcast_floating_point_to_bool);
9740         }
9741       }
9742     }
9743     return;
9744   }
9745 
9746   DiagnoseNullConversion(S, E, T, CC);
9747 
9748   S.DiscardMisalignedMemberAddress(Target, E);
9749 
9750   if (!Source->isIntegerType() || !Target->isIntegerType())
9751     return;
9752 
9753   // TODO: remove this early return once the false positives for constant->bool
9754   // in templates, macros, etc, are reduced or removed.
9755   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9756     return;
9757 
9758   IntRange SourceRange = GetExprRange(S.Context, E);
9759   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9760 
9761   if (SourceRange.Width > TargetRange.Width) {
9762     // If the source is a constant, use a default-on diagnostic.
9763     // TODO: this should happen for bitfield stores, too.
9764     llvm::APSInt Value(32);
9765     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9766       if (S.SourceMgr.isInSystemMacro(CC))
9767         return;
9768 
9769       std::string PrettySourceValue = Value.toString(10);
9770       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9771 
9772       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9773         S.PDiag(diag::warn_impcast_integer_precision_constant)
9774             << PrettySourceValue << PrettyTargetValue
9775             << E->getType() << T << E->getSourceRange()
9776             << clang::SourceRange(CC));
9777       return;
9778     }
9779 
9780     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9781     if (S.SourceMgr.isInSystemMacro(CC))
9782       return;
9783 
9784     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9785       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9786                              /* pruneControlFlow */ true);
9787     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9788   }
9789 
9790   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9791       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9792     // Warn when doing a signed to signed conversion, warn if the positive
9793     // source value is exactly the width of the target type, which will
9794     // cause a negative value to be stored.
9795 
9796     llvm::APSInt Value;
9797     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9798         !S.SourceMgr.isInSystemMacro(CC)) {
9799       if (isSameWidthConstantConversion(S, E, T, CC)) {
9800         std::string PrettySourceValue = Value.toString(10);
9801         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9802 
9803         S.DiagRuntimeBehavior(
9804             E->getExprLoc(), E,
9805             S.PDiag(diag::warn_impcast_integer_precision_constant)
9806                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9807                 << E->getSourceRange() << clang::SourceRange(CC));
9808         return;
9809       }
9810     }
9811 
9812     // Fall through for non-constants to give a sign conversion warning.
9813   }
9814 
9815   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9816       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9817        SourceRange.Width == TargetRange.Width)) {
9818     if (S.SourceMgr.isInSystemMacro(CC))
9819       return;
9820 
9821     unsigned DiagID = diag::warn_impcast_integer_sign;
9822 
9823     // Traditionally, gcc has warned about this under -Wsign-compare.
9824     // We also want to warn about it in -Wconversion.
9825     // So if -Wconversion is off, use a completely identical diagnostic
9826     // in the sign-compare group.
9827     // The conditional-checking code will
9828     if (ICContext) {
9829       DiagID = diag::warn_impcast_integer_sign_conditional;
9830       *ICContext = true;
9831     }
9832 
9833     return DiagnoseImpCast(S, E, T, CC, DiagID);
9834   }
9835 
9836   // Diagnose conversions between different enumeration types.
9837   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9838   // type, to give us better diagnostics.
9839   QualType SourceType = E->getType();
9840   if (!S.getLangOpts().CPlusPlus) {
9841     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9842       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9843         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9844         SourceType = S.Context.getTypeDeclType(Enum);
9845         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9846       }
9847   }
9848 
9849   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9850     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9851       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9852           TargetEnum->getDecl()->hasNameForLinkage() &&
9853           SourceEnum != TargetEnum) {
9854         if (S.SourceMgr.isInSystemMacro(CC))
9855           return;
9856 
9857         return DiagnoseImpCast(S, E, SourceType, T, CC,
9858                                diag::warn_impcast_different_enum_types);
9859       }
9860 }
9861 
9862 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9863                                      SourceLocation CC, QualType T);
9864 
9865 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9866                                     SourceLocation CC, bool &ICContext) {
9867   E = E->IgnoreParenImpCasts();
9868 
9869   if (isa<ConditionalOperator>(E))
9870     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9871 
9872   AnalyzeImplicitConversions(S, E, CC);
9873   if (E->getType() != T)
9874     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9875 }
9876 
9877 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9878                                      SourceLocation CC, QualType T) {
9879   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9880 
9881   bool Suspicious = false;
9882   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9883   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9884 
9885   // If -Wconversion would have warned about either of the candidates
9886   // for a signedness conversion to the context type...
9887   if (!Suspicious) return;
9888 
9889   // ...but it's currently ignored...
9890   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9891     return;
9892 
9893   // ...then check whether it would have warned about either of the
9894   // candidates for a signedness conversion to the condition type.
9895   if (E->getType() == T) return;
9896 
9897   Suspicious = false;
9898   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9899                           E->getType(), CC, &Suspicious);
9900   if (!Suspicious)
9901     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9902                             E->getType(), CC, &Suspicious);
9903 }
9904 
9905 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9906 /// Input argument E is a logical expression.
9907 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9908   if (S.getLangOpts().Bool)
9909     return;
9910   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9911 }
9912 
9913 /// AnalyzeImplicitConversions - Find and report any interesting
9914 /// implicit conversions in the given expression.  There are a couple
9915 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9916 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9917                                        SourceLocation CC) {
9918   QualType T = OrigE->getType();
9919   Expr *E = OrigE->IgnoreParenImpCasts();
9920 
9921   if (E->isTypeDependent() || E->isValueDependent())
9922     return;
9923 
9924   // For conditional operators, we analyze the arguments as if they
9925   // were being fed directly into the output.
9926   if (isa<ConditionalOperator>(E)) {
9927     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9928     CheckConditionalOperator(S, CO, CC, T);
9929     return;
9930   }
9931 
9932   // Check implicit argument conversions for function calls.
9933   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9934     CheckImplicitArgumentConversions(S, Call, CC);
9935 
9936   // Go ahead and check any implicit conversions we might have skipped.
9937   // The non-canonical typecheck is just an optimization;
9938   // CheckImplicitConversion will filter out dead implicit conversions.
9939   if (E->getType() != T)
9940     CheckImplicitConversion(S, E, T, CC);
9941 
9942   // Now continue drilling into this expression.
9943 
9944   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9945     // The bound subexpressions in a PseudoObjectExpr are not reachable
9946     // as transitive children.
9947     // FIXME: Use a more uniform representation for this.
9948     for (auto *SE : POE->semantics())
9949       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9950         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9951   }
9952 
9953   // Skip past explicit casts.
9954   if (isa<ExplicitCastExpr>(E)) {
9955     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9956     return AnalyzeImplicitConversions(S, E, CC);
9957   }
9958 
9959   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9960     // Do a somewhat different check with comparison operators.
9961     if (BO->isComparisonOp())
9962       return AnalyzeComparison(S, BO);
9963 
9964     // And with simple assignments.
9965     if (BO->getOpcode() == BO_Assign)
9966       return AnalyzeAssignment(S, BO);
9967   }
9968 
9969   // These break the otherwise-useful invariant below.  Fortunately,
9970   // we don't really need to recurse into them, because any internal
9971   // expressions should have been analyzed already when they were
9972   // built into statements.
9973   if (isa<StmtExpr>(E)) return;
9974 
9975   // Don't descend into unevaluated contexts.
9976   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9977 
9978   // Now just recurse over the expression's children.
9979   CC = E->getExprLoc();
9980   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9981   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9982   for (Stmt *SubStmt : E->children()) {
9983     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9984     if (!ChildExpr)
9985       continue;
9986 
9987     if (IsLogicalAndOperator &&
9988         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9989       // Ignore checking string literals that are in logical and operators.
9990       // This is a common pattern for asserts.
9991       continue;
9992     AnalyzeImplicitConversions(S, ChildExpr, CC);
9993   }
9994 
9995   if (BO && BO->isLogicalOp()) {
9996     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9997     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9998       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9999 
10000     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
10001     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
10002       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
10003   }
10004 
10005   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
10006     if (U->getOpcode() == UO_LNot)
10007       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
10008 }
10009 
10010 /// Diagnose integer type and any valid implicit convertion to it.
10011 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
10012   // Taking into account implicit conversions,
10013   // allow any integer.
10014   if (!E->getType()->isIntegerType()) {
10015     S.Diag(E->getLocStart(),
10016            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
10017     return true;
10018   }
10019   // Potentially emit standard warnings for implicit conversions if enabled
10020   // using -Wconversion.
10021   CheckImplicitConversion(S, E, IntT, E->getLocStart());
10022   return false;
10023 }
10024 
10025 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
10026 // Returns true when emitting a warning about taking the address of a reference.
10027 static bool CheckForReference(Sema &SemaRef, const Expr *E,
10028                               const PartialDiagnostic &PD) {
10029   E = E->IgnoreParenImpCasts();
10030 
10031   const FunctionDecl *FD = nullptr;
10032 
10033   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10034     if (!DRE->getDecl()->getType()->isReferenceType())
10035       return false;
10036   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10037     if (!M->getMemberDecl()->getType()->isReferenceType())
10038       return false;
10039   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
10040     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
10041       return false;
10042     FD = Call->getDirectCallee();
10043   } else {
10044     return false;
10045   }
10046 
10047   SemaRef.Diag(E->getExprLoc(), PD);
10048 
10049   // If possible, point to location of function.
10050   if (FD) {
10051     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
10052   }
10053 
10054   return true;
10055 }
10056 
10057 // Returns true if the SourceLocation is expanded from any macro body.
10058 // Returns false if the SourceLocation is invalid, is from not in a macro
10059 // expansion, or is from expanded from a top-level macro argument.
10060 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
10061   if (Loc.isInvalid())
10062     return false;
10063 
10064   while (Loc.isMacroID()) {
10065     if (SM.isMacroBodyExpansion(Loc))
10066       return true;
10067     Loc = SM.getImmediateMacroCallerLoc(Loc);
10068   }
10069 
10070   return false;
10071 }
10072 
10073 /// \brief Diagnose pointers that are always non-null.
10074 /// \param E the expression containing the pointer
10075 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
10076 /// compared to a null pointer
10077 /// \param IsEqual True when the comparison is equal to a null pointer
10078 /// \param Range Extra SourceRange to highlight in the diagnostic
10079 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
10080                                         Expr::NullPointerConstantKind NullKind,
10081                                         bool IsEqual, SourceRange Range) {
10082   if (!E)
10083     return;
10084 
10085   // Don't warn inside macros.
10086   if (E->getExprLoc().isMacroID()) {
10087     const SourceManager &SM = getSourceManager();
10088     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10089         IsInAnyMacroBody(SM, Range.getBegin()))
10090       return;
10091   }
10092   E = E->IgnoreImpCasts();
10093 
10094   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10095 
10096   if (isa<CXXThisExpr>(E)) {
10097     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10098                                 : diag::warn_this_bool_conversion;
10099     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10100     return;
10101   }
10102 
10103   bool IsAddressOf = false;
10104 
10105   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10106     if (UO->getOpcode() != UO_AddrOf)
10107       return;
10108     IsAddressOf = true;
10109     E = UO->getSubExpr();
10110   }
10111 
10112   if (IsAddressOf) {
10113     unsigned DiagID = IsCompare
10114                           ? diag::warn_address_of_reference_null_compare
10115                           : diag::warn_address_of_reference_bool_conversion;
10116     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10117                                          << IsEqual;
10118     if (CheckForReference(*this, E, PD)) {
10119       return;
10120     }
10121   }
10122 
10123   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10124     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10125     std::string Str;
10126     llvm::raw_string_ostream S(Str);
10127     E->printPretty(S, nullptr, getPrintingPolicy());
10128     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10129                                 : diag::warn_cast_nonnull_to_bool;
10130     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10131       << E->getSourceRange() << Range << IsEqual;
10132     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10133   };
10134 
10135   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10136   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10137     if (auto *Callee = Call->getDirectCallee()) {
10138       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10139         ComplainAboutNonnullParamOrCall(A);
10140         return;
10141       }
10142     }
10143   }
10144 
10145   // Expect to find a single Decl.  Skip anything more complicated.
10146   ValueDecl *D = nullptr;
10147   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10148     D = R->getDecl();
10149   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10150     D = M->getMemberDecl();
10151   }
10152 
10153   // Weak Decls can be null.
10154   if (!D || D->isWeak())
10155     return;
10156 
10157   // Check for parameter decl with nonnull attribute
10158   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10159     if (getCurFunction() &&
10160         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10161       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10162         ComplainAboutNonnullParamOrCall(A);
10163         return;
10164       }
10165 
10166       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10167         auto ParamIter = llvm::find(FD->parameters(), PV);
10168         assert(ParamIter != FD->param_end());
10169         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10170 
10171         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10172           if (!NonNull->args_size()) {
10173               ComplainAboutNonnullParamOrCall(NonNull);
10174               return;
10175           }
10176 
10177           for (unsigned ArgNo : NonNull->args()) {
10178             if (ArgNo == ParamNo) {
10179               ComplainAboutNonnullParamOrCall(NonNull);
10180               return;
10181             }
10182           }
10183         }
10184       }
10185     }
10186   }
10187 
10188   QualType T = D->getType();
10189   const bool IsArray = T->isArrayType();
10190   const bool IsFunction = T->isFunctionType();
10191 
10192   // Address of function is used to silence the function warning.
10193   if (IsAddressOf && IsFunction) {
10194     return;
10195   }
10196 
10197   // Found nothing.
10198   if (!IsAddressOf && !IsFunction && !IsArray)
10199     return;
10200 
10201   // Pretty print the expression for the diagnostic.
10202   std::string Str;
10203   llvm::raw_string_ostream S(Str);
10204   E->printPretty(S, nullptr, getPrintingPolicy());
10205 
10206   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10207                               : diag::warn_impcast_pointer_to_bool;
10208   enum {
10209     AddressOf,
10210     FunctionPointer,
10211     ArrayPointer
10212   } DiagType;
10213   if (IsAddressOf)
10214     DiagType = AddressOf;
10215   else if (IsFunction)
10216     DiagType = FunctionPointer;
10217   else if (IsArray)
10218     DiagType = ArrayPointer;
10219   else
10220     llvm_unreachable("Could not determine diagnostic.");
10221   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10222                                 << Range << IsEqual;
10223 
10224   if (!IsFunction)
10225     return;
10226 
10227   // Suggest '&' to silence the function warning.
10228   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10229       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10230 
10231   // Check to see if '()' fixit should be emitted.
10232   QualType ReturnType;
10233   UnresolvedSet<4> NonTemplateOverloads;
10234   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10235   if (ReturnType.isNull())
10236     return;
10237 
10238   if (IsCompare) {
10239     // There are two cases here.  If there is null constant, the only suggest
10240     // for a pointer return type.  If the null is 0, then suggest if the return
10241     // type is a pointer or an integer type.
10242     if (!ReturnType->isPointerType()) {
10243       if (NullKind == Expr::NPCK_ZeroExpression ||
10244           NullKind == Expr::NPCK_ZeroLiteral) {
10245         if (!ReturnType->isIntegerType())
10246           return;
10247       } else {
10248         return;
10249       }
10250     }
10251   } else { // !IsCompare
10252     // For function to bool, only suggest if the function pointer has bool
10253     // return type.
10254     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10255       return;
10256   }
10257   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10258       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10259 }
10260 
10261 /// Diagnoses "dangerous" implicit conversions within the given
10262 /// expression (which is a full expression).  Implements -Wconversion
10263 /// and -Wsign-compare.
10264 ///
10265 /// \param CC the "context" location of the implicit conversion, i.e.
10266 ///   the most location of the syntactic entity requiring the implicit
10267 ///   conversion
10268 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10269   // Don't diagnose in unevaluated contexts.
10270   if (isUnevaluatedContext())
10271     return;
10272 
10273   // Don't diagnose for value- or type-dependent expressions.
10274   if (E->isTypeDependent() || E->isValueDependent())
10275     return;
10276 
10277   // Check for array bounds violations in cases where the check isn't triggered
10278   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10279   // ArraySubscriptExpr is on the RHS of a variable initialization.
10280   CheckArrayAccess(E);
10281 
10282   // This is not the right CC for (e.g.) a variable initialization.
10283   AnalyzeImplicitConversions(*this, E, CC);
10284 }
10285 
10286 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10287 /// Input argument E is a logical expression.
10288 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10289   ::CheckBoolLikeConversion(*this, E, CC);
10290 }
10291 
10292 /// Diagnose when expression is an integer constant expression and its evaluation
10293 /// results in integer overflow
10294 void Sema::CheckForIntOverflow (Expr *E) {
10295   // Use a work list to deal with nested struct initializers.
10296   SmallVector<Expr *, 2> Exprs(1, E);
10297 
10298   do {
10299     Expr *E = Exprs.pop_back_val();
10300 
10301     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10302       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10303       continue;
10304     }
10305 
10306     if (auto InitList = dyn_cast<InitListExpr>(E))
10307       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10308 
10309     if (isa<ObjCBoxedExpr>(E))
10310       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10311   } while (!Exprs.empty());
10312 }
10313 
10314 namespace {
10315 
10316 /// \brief Visitor for expressions which looks for unsequenced operations on the
10317 /// same object.
10318 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10319   using Base = EvaluatedExprVisitor<SequenceChecker>;
10320 
10321   /// \brief A tree of sequenced regions within an expression. Two regions are
10322   /// unsequenced if one is an ancestor or a descendent of the other. When we
10323   /// finish processing an expression with sequencing, such as a comma
10324   /// expression, we fold its tree nodes into its parent, since they are
10325   /// unsequenced with respect to nodes we will visit later.
10326   class SequenceTree {
10327     struct Value {
10328       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10329       unsigned Parent : 31;
10330       unsigned Merged : 1;
10331     };
10332     SmallVector<Value, 8> Values;
10333 
10334   public:
10335     /// \brief A region within an expression which may be sequenced with respect
10336     /// to some other region.
10337     class Seq {
10338       friend class SequenceTree;
10339 
10340       unsigned Index = 0;
10341 
10342       explicit Seq(unsigned N) : Index(N) {}
10343 
10344     public:
10345       Seq() = default;
10346     };
10347 
10348     SequenceTree() { Values.push_back(Value(0)); }
10349     Seq root() const { return Seq(0); }
10350 
10351     /// \brief Create a new sequence of operations, which is an unsequenced
10352     /// subset of \p Parent. This sequence of operations is sequenced with
10353     /// respect to other children of \p Parent.
10354     Seq allocate(Seq Parent) {
10355       Values.push_back(Value(Parent.Index));
10356       return Seq(Values.size() - 1);
10357     }
10358 
10359     /// \brief Merge a sequence of operations into its parent.
10360     void merge(Seq S) {
10361       Values[S.Index].Merged = true;
10362     }
10363 
10364     /// \brief Determine whether two operations are unsequenced. This operation
10365     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10366     /// should have been merged into its parent as appropriate.
10367     bool isUnsequenced(Seq Cur, Seq Old) {
10368       unsigned C = representative(Cur.Index);
10369       unsigned Target = representative(Old.Index);
10370       while (C >= Target) {
10371         if (C == Target)
10372           return true;
10373         C = Values[C].Parent;
10374       }
10375       return false;
10376     }
10377 
10378   private:
10379     /// \brief Pick a representative for a sequence.
10380     unsigned representative(unsigned K) {
10381       if (Values[K].Merged)
10382         // Perform path compression as we go.
10383         return Values[K].Parent = representative(Values[K].Parent);
10384       return K;
10385     }
10386   };
10387 
10388   /// An object for which we can track unsequenced uses.
10389   using Object = NamedDecl *;
10390 
10391   /// Different flavors of object usage which we track. We only track the
10392   /// least-sequenced usage of each kind.
10393   enum UsageKind {
10394     /// A read of an object. Multiple unsequenced reads are OK.
10395     UK_Use,
10396 
10397     /// A modification of an object which is sequenced before the value
10398     /// computation of the expression, such as ++n in C++.
10399     UK_ModAsValue,
10400 
10401     /// A modification of an object which is not sequenced before the value
10402     /// computation of the expression, such as n++.
10403     UK_ModAsSideEffect,
10404 
10405     UK_Count = UK_ModAsSideEffect + 1
10406   };
10407 
10408   struct Usage {
10409     Expr *Use = nullptr;
10410     SequenceTree::Seq Seq;
10411 
10412     Usage() = default;
10413   };
10414 
10415   struct UsageInfo {
10416     Usage Uses[UK_Count];
10417 
10418     /// Have we issued a diagnostic for this variable already?
10419     bool Diagnosed = false;
10420 
10421     UsageInfo() = default;
10422   };
10423   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10424 
10425   Sema &SemaRef;
10426 
10427   /// Sequenced regions within the expression.
10428   SequenceTree Tree;
10429 
10430   /// Declaration modifications and references which we have seen.
10431   UsageInfoMap UsageMap;
10432 
10433   /// The region we are currently within.
10434   SequenceTree::Seq Region;
10435 
10436   /// Filled in with declarations which were modified as a side-effect
10437   /// (that is, post-increment operations).
10438   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10439 
10440   /// Expressions to check later. We defer checking these to reduce
10441   /// stack usage.
10442   SmallVectorImpl<Expr *> &WorkList;
10443 
10444   /// RAII object wrapping the visitation of a sequenced subexpression of an
10445   /// expression. At the end of this process, the side-effects of the evaluation
10446   /// become sequenced with respect to the value computation of the result, so
10447   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10448   /// UK_ModAsValue.
10449   struct SequencedSubexpression {
10450     SequencedSubexpression(SequenceChecker &Self)
10451       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10452       Self.ModAsSideEffect = &ModAsSideEffect;
10453     }
10454 
10455     ~SequencedSubexpression() {
10456       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10457         UsageInfo &U = Self.UsageMap[M.first];
10458         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10459         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10460         SideEffectUsage = M.second;
10461       }
10462       Self.ModAsSideEffect = OldModAsSideEffect;
10463     }
10464 
10465     SequenceChecker &Self;
10466     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10467     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10468   };
10469 
10470   /// RAII object wrapping the visitation of a subexpression which we might
10471   /// choose to evaluate as a constant. If any subexpression is evaluated and
10472   /// found to be non-constant, this allows us to suppress the evaluation of
10473   /// the outer expression.
10474   class EvaluationTracker {
10475   public:
10476     EvaluationTracker(SequenceChecker &Self)
10477         : Self(Self), Prev(Self.EvalTracker) {
10478       Self.EvalTracker = this;
10479     }
10480 
10481     ~EvaluationTracker() {
10482       Self.EvalTracker = Prev;
10483       if (Prev)
10484         Prev->EvalOK &= EvalOK;
10485     }
10486 
10487     bool evaluate(const Expr *E, bool &Result) {
10488       if (!EvalOK || E->isValueDependent())
10489         return false;
10490       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10491       return EvalOK;
10492     }
10493 
10494   private:
10495     SequenceChecker &Self;
10496     EvaluationTracker *Prev;
10497     bool EvalOK = true;
10498   } *EvalTracker = nullptr;
10499 
10500   /// \brief Find the object which is produced by the specified expression,
10501   /// if any.
10502   Object getObject(Expr *E, bool Mod) const {
10503     E = E->IgnoreParenCasts();
10504     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10505       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10506         return getObject(UO->getSubExpr(), Mod);
10507     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10508       if (BO->getOpcode() == BO_Comma)
10509         return getObject(BO->getRHS(), Mod);
10510       if (Mod && BO->isAssignmentOp())
10511         return getObject(BO->getLHS(), Mod);
10512     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10513       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10514       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10515         return ME->getMemberDecl();
10516     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10517       // FIXME: If this is a reference, map through to its value.
10518       return DRE->getDecl();
10519     return nullptr;
10520   }
10521 
10522   /// \brief Note that an object was modified or used by an expression.
10523   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10524     Usage &U = UI.Uses[UK];
10525     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10526       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10527         ModAsSideEffect->push_back(std::make_pair(O, U));
10528       U.Use = Ref;
10529       U.Seq = Region;
10530     }
10531   }
10532 
10533   /// \brief Check whether a modification or use conflicts with a prior usage.
10534   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10535                   bool IsModMod) {
10536     if (UI.Diagnosed)
10537       return;
10538 
10539     const Usage &U = UI.Uses[OtherKind];
10540     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10541       return;
10542 
10543     Expr *Mod = U.Use;
10544     Expr *ModOrUse = Ref;
10545     if (OtherKind == UK_Use)
10546       std::swap(Mod, ModOrUse);
10547 
10548     SemaRef.Diag(Mod->getExprLoc(),
10549                  IsModMod ? diag::warn_unsequenced_mod_mod
10550                           : diag::warn_unsequenced_mod_use)
10551       << O << SourceRange(ModOrUse->getExprLoc());
10552     UI.Diagnosed = true;
10553   }
10554 
10555   void notePreUse(Object O, Expr *Use) {
10556     UsageInfo &U = UsageMap[O];
10557     // Uses conflict with other modifications.
10558     checkUsage(O, U, Use, UK_ModAsValue, false);
10559   }
10560 
10561   void notePostUse(Object O, Expr *Use) {
10562     UsageInfo &U = UsageMap[O];
10563     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10564     addUsage(U, O, Use, UK_Use);
10565   }
10566 
10567   void notePreMod(Object O, Expr *Mod) {
10568     UsageInfo &U = UsageMap[O];
10569     // Modifications conflict with other modifications and with uses.
10570     checkUsage(O, U, Mod, UK_ModAsValue, true);
10571     checkUsage(O, U, Mod, UK_Use, false);
10572   }
10573 
10574   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10575     UsageInfo &U = UsageMap[O];
10576     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10577     addUsage(U, O, Use, UK);
10578   }
10579 
10580 public:
10581   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10582       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10583     Visit(E);
10584   }
10585 
10586   void VisitStmt(Stmt *S) {
10587     // Skip all statements which aren't expressions for now.
10588   }
10589 
10590   void VisitExpr(Expr *E) {
10591     // By default, just recurse to evaluated subexpressions.
10592     Base::VisitStmt(E);
10593   }
10594 
10595   void VisitCastExpr(CastExpr *E) {
10596     Object O = Object();
10597     if (E->getCastKind() == CK_LValueToRValue)
10598       O = getObject(E->getSubExpr(), false);
10599 
10600     if (O)
10601       notePreUse(O, E);
10602     VisitExpr(E);
10603     if (O)
10604       notePostUse(O, E);
10605   }
10606 
10607   void VisitBinComma(BinaryOperator *BO) {
10608     // C++11 [expr.comma]p1:
10609     //   Every value computation and side effect associated with the left
10610     //   expression is sequenced before every value computation and side
10611     //   effect associated with the right expression.
10612     SequenceTree::Seq LHS = Tree.allocate(Region);
10613     SequenceTree::Seq RHS = Tree.allocate(Region);
10614     SequenceTree::Seq OldRegion = Region;
10615 
10616     {
10617       SequencedSubexpression SeqLHS(*this);
10618       Region = LHS;
10619       Visit(BO->getLHS());
10620     }
10621 
10622     Region = RHS;
10623     Visit(BO->getRHS());
10624 
10625     Region = OldRegion;
10626 
10627     // Forget that LHS and RHS are sequenced. They are both unsequenced
10628     // with respect to other stuff.
10629     Tree.merge(LHS);
10630     Tree.merge(RHS);
10631   }
10632 
10633   void VisitBinAssign(BinaryOperator *BO) {
10634     // The modification is sequenced after the value computation of the LHS
10635     // and RHS, so check it before inspecting the operands and update the
10636     // map afterwards.
10637     Object O = getObject(BO->getLHS(), true);
10638     if (!O)
10639       return VisitExpr(BO);
10640 
10641     notePreMod(O, BO);
10642 
10643     // C++11 [expr.ass]p7:
10644     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10645     //   only once.
10646     //
10647     // Therefore, for a compound assignment operator, O is considered used
10648     // everywhere except within the evaluation of E1 itself.
10649     if (isa<CompoundAssignOperator>(BO))
10650       notePreUse(O, BO);
10651 
10652     Visit(BO->getLHS());
10653 
10654     if (isa<CompoundAssignOperator>(BO))
10655       notePostUse(O, BO);
10656 
10657     Visit(BO->getRHS());
10658 
10659     // C++11 [expr.ass]p1:
10660     //   the assignment is sequenced [...] before the value computation of the
10661     //   assignment expression.
10662     // C11 6.5.16/3 has no such rule.
10663     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10664                                                        : UK_ModAsSideEffect);
10665   }
10666 
10667   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10668     VisitBinAssign(CAO);
10669   }
10670 
10671   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10672   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10673   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10674     Object O = getObject(UO->getSubExpr(), true);
10675     if (!O)
10676       return VisitExpr(UO);
10677 
10678     notePreMod(O, UO);
10679     Visit(UO->getSubExpr());
10680     // C++11 [expr.pre.incr]p1:
10681     //   the expression ++x is equivalent to x+=1
10682     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10683                                                        : UK_ModAsSideEffect);
10684   }
10685 
10686   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10687   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10688   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10689     Object O = getObject(UO->getSubExpr(), true);
10690     if (!O)
10691       return VisitExpr(UO);
10692 
10693     notePreMod(O, UO);
10694     Visit(UO->getSubExpr());
10695     notePostMod(O, UO, UK_ModAsSideEffect);
10696   }
10697 
10698   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10699   void VisitBinLOr(BinaryOperator *BO) {
10700     // The side-effects of the LHS of an '&&' are sequenced before the
10701     // value computation of the RHS, and hence before the value computation
10702     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10703     // as if they were unconditionally sequenced.
10704     EvaluationTracker Eval(*this);
10705     {
10706       SequencedSubexpression Sequenced(*this);
10707       Visit(BO->getLHS());
10708     }
10709 
10710     bool Result;
10711     if (Eval.evaluate(BO->getLHS(), Result)) {
10712       if (!Result)
10713         Visit(BO->getRHS());
10714     } else {
10715       // Check for unsequenced operations in the RHS, treating it as an
10716       // entirely separate evaluation.
10717       //
10718       // FIXME: If there are operations in the RHS which are unsequenced
10719       // with respect to operations outside the RHS, and those operations
10720       // are unconditionally evaluated, diagnose them.
10721       WorkList.push_back(BO->getRHS());
10722     }
10723   }
10724   void VisitBinLAnd(BinaryOperator *BO) {
10725     EvaluationTracker Eval(*this);
10726     {
10727       SequencedSubexpression Sequenced(*this);
10728       Visit(BO->getLHS());
10729     }
10730 
10731     bool Result;
10732     if (Eval.evaluate(BO->getLHS(), Result)) {
10733       if (Result)
10734         Visit(BO->getRHS());
10735     } else {
10736       WorkList.push_back(BO->getRHS());
10737     }
10738   }
10739 
10740   // Only visit the condition, unless we can be sure which subexpression will
10741   // be chosen.
10742   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10743     EvaluationTracker Eval(*this);
10744     {
10745       SequencedSubexpression Sequenced(*this);
10746       Visit(CO->getCond());
10747     }
10748 
10749     bool Result;
10750     if (Eval.evaluate(CO->getCond(), Result))
10751       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10752     else {
10753       WorkList.push_back(CO->getTrueExpr());
10754       WorkList.push_back(CO->getFalseExpr());
10755     }
10756   }
10757 
10758   void VisitCallExpr(CallExpr *CE) {
10759     // C++11 [intro.execution]p15:
10760     //   When calling a function [...], every value computation and side effect
10761     //   associated with any argument expression, or with the postfix expression
10762     //   designating the called function, is sequenced before execution of every
10763     //   expression or statement in the body of the function [and thus before
10764     //   the value computation of its result].
10765     SequencedSubexpression Sequenced(*this);
10766     Base::VisitCallExpr(CE);
10767 
10768     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10769   }
10770 
10771   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10772     // This is a call, so all subexpressions are sequenced before the result.
10773     SequencedSubexpression Sequenced(*this);
10774 
10775     if (!CCE->isListInitialization())
10776       return VisitExpr(CCE);
10777 
10778     // In C++11, list initializations are sequenced.
10779     SmallVector<SequenceTree::Seq, 32> Elts;
10780     SequenceTree::Seq Parent = Region;
10781     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10782                                         E = CCE->arg_end();
10783          I != E; ++I) {
10784       Region = Tree.allocate(Parent);
10785       Elts.push_back(Region);
10786       Visit(*I);
10787     }
10788 
10789     // Forget that the initializers are sequenced.
10790     Region = Parent;
10791     for (unsigned I = 0; I < Elts.size(); ++I)
10792       Tree.merge(Elts[I]);
10793   }
10794 
10795   void VisitInitListExpr(InitListExpr *ILE) {
10796     if (!SemaRef.getLangOpts().CPlusPlus11)
10797       return VisitExpr(ILE);
10798 
10799     // In C++11, list initializations are sequenced.
10800     SmallVector<SequenceTree::Seq, 32> Elts;
10801     SequenceTree::Seq Parent = Region;
10802     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10803       Expr *E = ILE->getInit(I);
10804       if (!E) continue;
10805       Region = Tree.allocate(Parent);
10806       Elts.push_back(Region);
10807       Visit(E);
10808     }
10809 
10810     // Forget that the initializers are sequenced.
10811     Region = Parent;
10812     for (unsigned I = 0; I < Elts.size(); ++I)
10813       Tree.merge(Elts[I]);
10814   }
10815 };
10816 
10817 } // namespace
10818 
10819 void Sema::CheckUnsequencedOperations(Expr *E) {
10820   SmallVector<Expr *, 8> WorkList;
10821   WorkList.push_back(E);
10822   while (!WorkList.empty()) {
10823     Expr *Item = WorkList.pop_back_val();
10824     SequenceChecker(*this, Item, WorkList);
10825   }
10826 }
10827 
10828 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10829                               bool IsConstexpr) {
10830   CheckImplicitConversions(E, CheckLoc);
10831   if (!E->isInstantiationDependent())
10832     CheckUnsequencedOperations(E);
10833   if (!IsConstexpr && !E->isValueDependent())
10834     CheckForIntOverflow(E);
10835   DiagnoseMisalignedMembers();
10836 }
10837 
10838 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10839                                        FieldDecl *BitField,
10840                                        Expr *Init) {
10841   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10842 }
10843 
10844 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10845                                          SourceLocation Loc) {
10846   if (!PType->isVariablyModifiedType())
10847     return;
10848   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10849     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10850     return;
10851   }
10852   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10853     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10854     return;
10855   }
10856   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10857     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10858     return;
10859   }
10860 
10861   const ArrayType *AT = S.Context.getAsArrayType(PType);
10862   if (!AT)
10863     return;
10864 
10865   if (AT->getSizeModifier() != ArrayType::Star) {
10866     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10867     return;
10868   }
10869 
10870   S.Diag(Loc, diag::err_array_star_in_function_definition);
10871 }
10872 
10873 /// CheckParmsForFunctionDef - Check that the parameters of the given
10874 /// function are appropriate for the definition of a function. This
10875 /// takes care of any checks that cannot be performed on the
10876 /// declaration itself, e.g., that the types of each of the function
10877 /// parameters are complete.
10878 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10879                                     bool CheckParameterNames) {
10880   bool HasInvalidParm = false;
10881   for (ParmVarDecl *Param : Parameters) {
10882     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10883     // function declarator that is part of a function definition of
10884     // that function shall not have incomplete type.
10885     //
10886     // This is also C++ [dcl.fct]p6.
10887     if (!Param->isInvalidDecl() &&
10888         RequireCompleteType(Param->getLocation(), Param->getType(),
10889                             diag::err_typecheck_decl_incomplete_type)) {
10890       Param->setInvalidDecl();
10891       HasInvalidParm = true;
10892     }
10893 
10894     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10895     // declaration of each parameter shall include an identifier.
10896     if (CheckParameterNames &&
10897         Param->getIdentifier() == nullptr &&
10898         !Param->isImplicit() &&
10899         !getLangOpts().CPlusPlus)
10900       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10901 
10902     // C99 6.7.5.3p12:
10903     //   If the function declarator is not part of a definition of that
10904     //   function, parameters may have incomplete type and may use the [*]
10905     //   notation in their sequences of declarator specifiers to specify
10906     //   variable length array types.
10907     QualType PType = Param->getOriginalType();
10908     // FIXME: This diagnostic should point the '[*]' if source-location
10909     // information is added for it.
10910     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10911 
10912     // MSVC destroys objects passed by value in the callee.  Therefore a
10913     // function definition which takes such a parameter must be able to call the
10914     // object's destructor.  However, we don't perform any direct access check
10915     // on the dtor.
10916     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10917                                        .getCXXABI()
10918                                        .areArgsDestroyedLeftToRightInCallee()) {
10919       if (!Param->isInvalidDecl()) {
10920         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10921           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10922           if (!ClassDecl->isInvalidDecl() &&
10923               !ClassDecl->hasIrrelevantDestructor() &&
10924               !ClassDecl->isDependentContext()) {
10925             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10926             MarkFunctionReferenced(Param->getLocation(), Destructor);
10927             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10928           }
10929         }
10930       }
10931     }
10932 
10933     // Parameters with the pass_object_size attribute only need to be marked
10934     // constant at function definitions. Because we lack information about
10935     // whether we're on a declaration or definition when we're instantiating the
10936     // attribute, we need to check for constness here.
10937     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10938       if (!Param->getType().isConstQualified())
10939         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10940             << Attr->getSpelling() << 1;
10941   }
10942 
10943   return HasInvalidParm;
10944 }
10945 
10946 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10947 /// or MemberExpr.
10948 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10949                               ASTContext &Context) {
10950   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10951     return Context.getDeclAlign(DRE->getDecl());
10952 
10953   if (const auto *ME = dyn_cast<MemberExpr>(E))
10954     return Context.getDeclAlign(ME->getMemberDecl());
10955 
10956   return TypeAlign;
10957 }
10958 
10959 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10960 /// pointer cast increases the alignment requirements.
10961 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10962   // This is actually a lot of work to potentially be doing on every
10963   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10964   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10965     return;
10966 
10967   // Ignore dependent types.
10968   if (T->isDependentType() || Op->getType()->isDependentType())
10969     return;
10970 
10971   // Require that the destination be a pointer type.
10972   const PointerType *DestPtr = T->getAs<PointerType>();
10973   if (!DestPtr) return;
10974 
10975   // If the destination has alignment 1, we're done.
10976   QualType DestPointee = DestPtr->getPointeeType();
10977   if (DestPointee->isIncompleteType()) return;
10978   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10979   if (DestAlign.isOne()) return;
10980 
10981   // Require that the source be a pointer type.
10982   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10983   if (!SrcPtr) return;
10984   QualType SrcPointee = SrcPtr->getPointeeType();
10985 
10986   // Whitelist casts from cv void*.  We already implicitly
10987   // whitelisted casts to cv void*, since they have alignment 1.
10988   // Also whitelist casts involving incomplete types, which implicitly
10989   // includes 'void'.
10990   if (SrcPointee->isIncompleteType()) return;
10991 
10992   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10993 
10994   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10995     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10996       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10997   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10998     if (UO->getOpcode() == UO_AddrOf)
10999       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
11000   }
11001 
11002   if (SrcAlign >= DestAlign) return;
11003 
11004   Diag(TRange.getBegin(), diag::warn_cast_align)
11005     << Op->getType() << T
11006     << static_cast<unsigned>(SrcAlign.getQuantity())
11007     << static_cast<unsigned>(DestAlign.getQuantity())
11008     << TRange << Op->getSourceRange();
11009 }
11010 
11011 /// \brief Check whether this array fits the idiom of a size-one tail padded
11012 /// array member of a struct.
11013 ///
11014 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
11015 /// commonly used to emulate flexible arrays in C89 code.
11016 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
11017                                     const NamedDecl *ND) {
11018   if (Size != 1 || !ND) return false;
11019 
11020   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
11021   if (!FD) return false;
11022 
11023   // Don't consider sizes resulting from macro expansions or template argument
11024   // substitution to form C89 tail-padded arrays.
11025 
11026   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
11027   while (TInfo) {
11028     TypeLoc TL = TInfo->getTypeLoc();
11029     // Look through typedefs.
11030     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
11031       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
11032       TInfo = TDL->getTypeSourceInfo();
11033       continue;
11034     }
11035     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
11036       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
11037       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
11038         return false;
11039     }
11040     break;
11041   }
11042 
11043   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
11044   if (!RD) return false;
11045   if (RD->isUnion()) return false;
11046   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11047     if (!CRD->isStandardLayout()) return false;
11048   }
11049 
11050   // See if this is the last field decl in the record.
11051   const Decl *D = FD;
11052   while ((D = D->getNextDeclInContext()))
11053     if (isa<FieldDecl>(D))
11054       return false;
11055   return true;
11056 }
11057 
11058 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
11059                             const ArraySubscriptExpr *ASE,
11060                             bool AllowOnePastEnd, bool IndexNegated) {
11061   IndexExpr = IndexExpr->IgnoreParenImpCasts();
11062   if (IndexExpr->isValueDependent())
11063     return;
11064 
11065   const Type *EffectiveType =
11066       BaseExpr->getType()->getPointeeOrArrayElementType();
11067   BaseExpr = BaseExpr->IgnoreParenCasts();
11068   const ConstantArrayType *ArrayTy =
11069     Context.getAsConstantArrayType(BaseExpr->getType());
11070   if (!ArrayTy)
11071     return;
11072 
11073   llvm::APSInt index;
11074   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
11075     return;
11076   if (IndexNegated)
11077     index = -index;
11078 
11079   const NamedDecl *ND = nullptr;
11080   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11081     ND = dyn_cast<NamedDecl>(DRE->getDecl());
11082   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11083     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11084 
11085   if (index.isUnsigned() || !index.isNegative()) {
11086     llvm::APInt size = ArrayTy->getSize();
11087     if (!size.isStrictlyPositive())
11088       return;
11089 
11090     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
11091     if (BaseType != EffectiveType) {
11092       // Make sure we're comparing apples to apples when comparing index to size
11093       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
11094       uint64_t array_typesize = Context.getTypeSize(BaseType);
11095       // Handle ptrarith_typesize being zero, such as when casting to void*
11096       if (!ptrarith_typesize) ptrarith_typesize = 1;
11097       if (ptrarith_typesize != array_typesize) {
11098         // There's a cast to a different size type involved
11099         uint64_t ratio = array_typesize / ptrarith_typesize;
11100         // TODO: Be smarter about handling cases where array_typesize is not a
11101         // multiple of ptrarith_typesize
11102         if (ptrarith_typesize * ratio == array_typesize)
11103           size *= llvm::APInt(size.getBitWidth(), ratio);
11104       }
11105     }
11106 
11107     if (size.getBitWidth() > index.getBitWidth())
11108       index = index.zext(size.getBitWidth());
11109     else if (size.getBitWidth() < index.getBitWidth())
11110       size = size.zext(index.getBitWidth());
11111 
11112     // For array subscripting the index must be less than size, but for pointer
11113     // arithmetic also allow the index (offset) to be equal to size since
11114     // computing the next address after the end of the array is legal and
11115     // commonly done e.g. in C++ iterators and range-based for loops.
11116     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11117       return;
11118 
11119     // Also don't warn for arrays of size 1 which are members of some
11120     // structure. These are often used to approximate flexible arrays in C89
11121     // code.
11122     if (IsTailPaddedMemberArray(*this, size, ND))
11123       return;
11124 
11125     // Suppress the warning if the subscript expression (as identified by the
11126     // ']' location) and the index expression are both from macro expansions
11127     // within a system header.
11128     if (ASE) {
11129       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11130           ASE->getRBracketLoc());
11131       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11132         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11133             IndexExpr->getLocStart());
11134         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11135           return;
11136       }
11137     }
11138 
11139     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11140     if (ASE)
11141       DiagID = diag::warn_array_index_exceeds_bounds;
11142 
11143     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11144                         PDiag(DiagID) << index.toString(10, true)
11145                           << size.toString(10, true)
11146                           << (unsigned)size.getLimitedValue(~0U)
11147                           << IndexExpr->getSourceRange());
11148   } else {
11149     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11150     if (!ASE) {
11151       DiagID = diag::warn_ptr_arith_precedes_bounds;
11152       if (index.isNegative()) index = -index;
11153     }
11154 
11155     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11156                         PDiag(DiagID) << index.toString(10, true)
11157                           << IndexExpr->getSourceRange());
11158   }
11159 
11160   if (!ND) {
11161     // Try harder to find a NamedDecl to point at in the note.
11162     while (const ArraySubscriptExpr *ASE =
11163            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11164       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11165     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11166       ND = dyn_cast<NamedDecl>(DRE->getDecl());
11167     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11168       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11169   }
11170 
11171   if (ND)
11172     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11173                         PDiag(diag::note_array_index_out_of_bounds)
11174                           << ND->getDeclName());
11175 }
11176 
11177 void Sema::CheckArrayAccess(const Expr *expr) {
11178   int AllowOnePastEnd = 0;
11179   while (expr) {
11180     expr = expr->IgnoreParenImpCasts();
11181     switch (expr->getStmtClass()) {
11182       case Stmt::ArraySubscriptExprClass: {
11183         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11184         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11185                          AllowOnePastEnd > 0);
11186         return;
11187       }
11188       case Stmt::OMPArraySectionExprClass: {
11189         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11190         if (ASE->getLowerBound())
11191           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11192                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11193         return;
11194       }
11195       case Stmt::UnaryOperatorClass: {
11196         // Only unwrap the * and & unary operators
11197         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11198         expr = UO->getSubExpr();
11199         switch (UO->getOpcode()) {
11200           case UO_AddrOf:
11201             AllowOnePastEnd++;
11202             break;
11203           case UO_Deref:
11204             AllowOnePastEnd--;
11205             break;
11206           default:
11207             return;
11208         }
11209         break;
11210       }
11211       case Stmt::ConditionalOperatorClass: {
11212         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11213         if (const Expr *lhs = cond->getLHS())
11214           CheckArrayAccess(lhs);
11215         if (const Expr *rhs = cond->getRHS())
11216           CheckArrayAccess(rhs);
11217         return;
11218       }
11219       case Stmt::CXXOperatorCallExprClass: {
11220         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11221         for (const auto *Arg : OCE->arguments())
11222           CheckArrayAccess(Arg);
11223         return;
11224       }
11225       default:
11226         return;
11227     }
11228   }
11229 }
11230 
11231 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11232 
11233 namespace {
11234 
11235 struct RetainCycleOwner {
11236   VarDecl *Variable = nullptr;
11237   SourceRange Range;
11238   SourceLocation Loc;
11239   bool Indirect = false;
11240 
11241   RetainCycleOwner() = default;
11242 
11243   void setLocsFrom(Expr *e) {
11244     Loc = e->getExprLoc();
11245     Range = e->getSourceRange();
11246   }
11247 };
11248 
11249 } // namespace
11250 
11251 /// Consider whether capturing the given variable can possibly lead to
11252 /// a retain cycle.
11253 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11254   // In ARC, it's captured strongly iff the variable has __strong
11255   // lifetime.  In MRR, it's captured strongly if the variable is
11256   // __block and has an appropriate type.
11257   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11258     return false;
11259 
11260   owner.Variable = var;
11261   if (ref)
11262     owner.setLocsFrom(ref);
11263   return true;
11264 }
11265 
11266 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11267   while (true) {
11268     e = e->IgnoreParens();
11269     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11270       switch (cast->getCastKind()) {
11271       case CK_BitCast:
11272       case CK_LValueBitCast:
11273       case CK_LValueToRValue:
11274       case CK_ARCReclaimReturnedObject:
11275         e = cast->getSubExpr();
11276         continue;
11277 
11278       default:
11279         return false;
11280       }
11281     }
11282 
11283     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11284       ObjCIvarDecl *ivar = ref->getDecl();
11285       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11286         return false;
11287 
11288       // Try to find a retain cycle in the base.
11289       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11290         return false;
11291 
11292       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11293       owner.Indirect = true;
11294       return true;
11295     }
11296 
11297     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11298       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11299       if (!var) return false;
11300       return considerVariable(var, ref, owner);
11301     }
11302 
11303     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11304       if (member->isArrow()) return false;
11305 
11306       // Don't count this as an indirect ownership.
11307       e = member->getBase();
11308       continue;
11309     }
11310 
11311     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11312       // Only pay attention to pseudo-objects on property references.
11313       ObjCPropertyRefExpr *pre
11314         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11315                                               ->IgnoreParens());
11316       if (!pre) return false;
11317       if (pre->isImplicitProperty()) return false;
11318       ObjCPropertyDecl *property = pre->getExplicitProperty();
11319       if (!property->isRetaining() &&
11320           !(property->getPropertyIvarDecl() &&
11321             property->getPropertyIvarDecl()->getType()
11322               .getObjCLifetime() == Qualifiers::OCL_Strong))
11323           return false;
11324 
11325       owner.Indirect = true;
11326       if (pre->isSuperReceiver()) {
11327         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11328         if (!owner.Variable)
11329           return false;
11330         owner.Loc = pre->getLocation();
11331         owner.Range = pre->getSourceRange();
11332         return true;
11333       }
11334       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11335                               ->getSourceExpr());
11336       continue;
11337     }
11338 
11339     // Array ivars?
11340 
11341     return false;
11342   }
11343 }
11344 
11345 namespace {
11346 
11347   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11348     ASTContext &Context;
11349     VarDecl *Variable;
11350     Expr *Capturer = nullptr;
11351     bool VarWillBeReased = false;
11352 
11353     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11354         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11355           Context(Context), Variable(variable) {}
11356 
11357     void VisitDeclRefExpr(DeclRefExpr *ref) {
11358       if (ref->getDecl() == Variable && !Capturer)
11359         Capturer = ref;
11360     }
11361 
11362     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11363       if (Capturer) return;
11364       Visit(ref->getBase());
11365       if (Capturer && ref->isFreeIvar())
11366         Capturer = ref;
11367     }
11368 
11369     void VisitBlockExpr(BlockExpr *block) {
11370       // Look inside nested blocks
11371       if (block->getBlockDecl()->capturesVariable(Variable))
11372         Visit(block->getBlockDecl()->getBody());
11373     }
11374 
11375     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11376       if (Capturer) return;
11377       if (OVE->getSourceExpr())
11378         Visit(OVE->getSourceExpr());
11379     }
11380 
11381     void VisitBinaryOperator(BinaryOperator *BinOp) {
11382       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11383         return;
11384       Expr *LHS = BinOp->getLHS();
11385       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11386         if (DRE->getDecl() != Variable)
11387           return;
11388         if (Expr *RHS = BinOp->getRHS()) {
11389           RHS = RHS->IgnoreParenCasts();
11390           llvm::APSInt Value;
11391           VarWillBeReased =
11392             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11393         }
11394       }
11395     }
11396   };
11397 
11398 } // namespace
11399 
11400 /// Check whether the given argument is a block which captures a
11401 /// variable.
11402 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11403   assert(owner.Variable && owner.Loc.isValid());
11404 
11405   e = e->IgnoreParenCasts();
11406 
11407   // Look through [^{...} copy] and Block_copy(^{...}).
11408   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11409     Selector Cmd = ME->getSelector();
11410     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11411       e = ME->getInstanceReceiver();
11412       if (!e)
11413         return nullptr;
11414       e = e->IgnoreParenCasts();
11415     }
11416   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11417     if (CE->getNumArgs() == 1) {
11418       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11419       if (Fn) {
11420         const IdentifierInfo *FnI = Fn->getIdentifier();
11421         if (FnI && FnI->isStr("_Block_copy")) {
11422           e = CE->getArg(0)->IgnoreParenCasts();
11423         }
11424       }
11425     }
11426   }
11427 
11428   BlockExpr *block = dyn_cast<BlockExpr>(e);
11429   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11430     return nullptr;
11431 
11432   FindCaptureVisitor visitor(S.Context, owner.Variable);
11433   visitor.Visit(block->getBlockDecl()->getBody());
11434   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11435 }
11436 
11437 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11438                                 RetainCycleOwner &owner) {
11439   assert(capturer);
11440   assert(owner.Variable && owner.Loc.isValid());
11441 
11442   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11443     << owner.Variable << capturer->getSourceRange();
11444   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11445     << owner.Indirect << owner.Range;
11446 }
11447 
11448 /// Check for a keyword selector that starts with the word 'add' or
11449 /// 'set'.
11450 static bool isSetterLikeSelector(Selector sel) {
11451   if (sel.isUnarySelector()) return false;
11452 
11453   StringRef str = sel.getNameForSlot(0);
11454   while (!str.empty() && str.front() == '_') str = str.substr(1);
11455   if (str.startswith("set"))
11456     str = str.substr(3);
11457   else if (str.startswith("add")) {
11458     // Specially whitelist 'addOperationWithBlock:'.
11459     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11460       return false;
11461     str = str.substr(3);
11462   }
11463   else
11464     return false;
11465 
11466   if (str.empty()) return true;
11467   return !isLowercase(str.front());
11468 }
11469 
11470 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11471                                                     ObjCMessageExpr *Message) {
11472   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11473                                                 Message->getReceiverInterface(),
11474                                                 NSAPI::ClassId_NSMutableArray);
11475   if (!IsMutableArray) {
11476     return None;
11477   }
11478 
11479   Selector Sel = Message->getSelector();
11480 
11481   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11482     S.NSAPIObj->getNSArrayMethodKind(Sel);
11483   if (!MKOpt) {
11484     return None;
11485   }
11486 
11487   NSAPI::NSArrayMethodKind MK = *MKOpt;
11488 
11489   switch (MK) {
11490     case NSAPI::NSMutableArr_addObject:
11491     case NSAPI::NSMutableArr_insertObjectAtIndex:
11492     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11493       return 0;
11494     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11495       return 1;
11496 
11497     default:
11498       return None;
11499   }
11500 
11501   return None;
11502 }
11503 
11504 static
11505 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11506                                                   ObjCMessageExpr *Message) {
11507   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11508                                             Message->getReceiverInterface(),
11509                                             NSAPI::ClassId_NSMutableDictionary);
11510   if (!IsMutableDictionary) {
11511     return None;
11512   }
11513 
11514   Selector Sel = Message->getSelector();
11515 
11516   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11517     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11518   if (!MKOpt) {
11519     return None;
11520   }
11521 
11522   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11523 
11524   switch (MK) {
11525     case NSAPI::NSMutableDict_setObjectForKey:
11526     case NSAPI::NSMutableDict_setValueForKey:
11527     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11528       return 0;
11529 
11530     default:
11531       return None;
11532   }
11533 
11534   return None;
11535 }
11536 
11537 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11538   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11539                                                 Message->getReceiverInterface(),
11540                                                 NSAPI::ClassId_NSMutableSet);
11541 
11542   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11543                                             Message->getReceiverInterface(),
11544                                             NSAPI::ClassId_NSMutableOrderedSet);
11545   if (!IsMutableSet && !IsMutableOrderedSet) {
11546     return None;
11547   }
11548 
11549   Selector Sel = Message->getSelector();
11550 
11551   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11552   if (!MKOpt) {
11553     return None;
11554   }
11555 
11556   NSAPI::NSSetMethodKind MK = *MKOpt;
11557 
11558   switch (MK) {
11559     case NSAPI::NSMutableSet_addObject:
11560     case NSAPI::NSOrderedSet_setObjectAtIndex:
11561     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11562     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11563       return 0;
11564     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11565       return 1;
11566   }
11567 
11568   return None;
11569 }
11570 
11571 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11572   if (!Message->isInstanceMessage()) {
11573     return;
11574   }
11575 
11576   Optional<int> ArgOpt;
11577 
11578   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11579       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11580       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11581     return;
11582   }
11583 
11584   int ArgIndex = *ArgOpt;
11585 
11586   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11587   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11588     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11589   }
11590 
11591   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11592     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11593       if (ArgRE->isObjCSelfExpr()) {
11594         Diag(Message->getSourceRange().getBegin(),
11595              diag::warn_objc_circular_container)
11596           << ArgRE->getDecl()->getName() << StringRef("super");
11597       }
11598     }
11599   } else {
11600     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11601 
11602     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11603       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11604     }
11605 
11606     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11607       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11608         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11609           ValueDecl *Decl = ReceiverRE->getDecl();
11610           Diag(Message->getSourceRange().getBegin(),
11611                diag::warn_objc_circular_container)
11612             << Decl->getName() << Decl->getName();
11613           if (!ArgRE->isObjCSelfExpr()) {
11614             Diag(Decl->getLocation(),
11615                  diag::note_objc_circular_container_declared_here)
11616               << Decl->getName();
11617           }
11618         }
11619       }
11620     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11621       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11622         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11623           ObjCIvarDecl *Decl = IvarRE->getDecl();
11624           Diag(Message->getSourceRange().getBegin(),
11625                diag::warn_objc_circular_container)
11626             << Decl->getName() << Decl->getName();
11627           Diag(Decl->getLocation(),
11628                diag::note_objc_circular_container_declared_here)
11629             << Decl->getName();
11630         }
11631       }
11632     }
11633   }
11634 }
11635 
11636 /// Check a message send to see if it's likely to cause a retain cycle.
11637 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11638   // Only check instance methods whose selector looks like a setter.
11639   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11640     return;
11641 
11642   // Try to find a variable that the receiver is strongly owned by.
11643   RetainCycleOwner owner;
11644   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11645     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11646       return;
11647   } else {
11648     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11649     owner.Variable = getCurMethodDecl()->getSelfDecl();
11650     owner.Loc = msg->getSuperLoc();
11651     owner.Range = msg->getSuperLoc();
11652   }
11653 
11654   // Check whether the receiver is captured by any of the arguments.
11655   const ObjCMethodDecl *MD = msg->getMethodDecl();
11656   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11657     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11658       // noescape blocks should not be retained by the method.
11659       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11660         continue;
11661       return diagnoseRetainCycle(*this, capturer, owner);
11662     }
11663   }
11664 }
11665 
11666 /// Check a property assign to see if it's likely to cause a retain cycle.
11667 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11668   RetainCycleOwner owner;
11669   if (!findRetainCycleOwner(*this, receiver, owner))
11670     return;
11671 
11672   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11673     diagnoseRetainCycle(*this, capturer, owner);
11674 }
11675 
11676 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11677   RetainCycleOwner Owner;
11678   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11679     return;
11680 
11681   // Because we don't have an expression for the variable, we have to set the
11682   // location explicitly here.
11683   Owner.Loc = Var->getLocation();
11684   Owner.Range = Var->getSourceRange();
11685 
11686   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11687     diagnoseRetainCycle(*this, Capturer, Owner);
11688 }
11689 
11690 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11691                                      Expr *RHS, bool isProperty) {
11692   // Check if RHS is an Objective-C object literal, which also can get
11693   // immediately zapped in a weak reference.  Note that we explicitly
11694   // allow ObjCStringLiterals, since those are designed to never really die.
11695   RHS = RHS->IgnoreParenImpCasts();
11696 
11697   // This enum needs to match with the 'select' in
11698   // warn_objc_arc_literal_assign (off-by-1).
11699   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11700   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11701     return false;
11702 
11703   S.Diag(Loc, diag::warn_arc_literal_assign)
11704     << (unsigned) Kind
11705     << (isProperty ? 0 : 1)
11706     << RHS->getSourceRange();
11707 
11708   return true;
11709 }
11710 
11711 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11712                                     Qualifiers::ObjCLifetime LT,
11713                                     Expr *RHS, bool isProperty) {
11714   // Strip off any implicit cast added to get to the one ARC-specific.
11715   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11716     if (cast->getCastKind() == CK_ARCConsumeObject) {
11717       S.Diag(Loc, diag::warn_arc_retained_assign)
11718         << (LT == Qualifiers::OCL_ExplicitNone)
11719         << (isProperty ? 0 : 1)
11720         << RHS->getSourceRange();
11721       return true;
11722     }
11723     RHS = cast->getSubExpr();
11724   }
11725 
11726   if (LT == Qualifiers::OCL_Weak &&
11727       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11728     return true;
11729 
11730   return false;
11731 }
11732 
11733 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11734                               QualType LHS, Expr *RHS) {
11735   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11736 
11737   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11738     return false;
11739 
11740   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11741     return true;
11742 
11743   return false;
11744 }
11745 
11746 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11747                               Expr *LHS, Expr *RHS) {
11748   QualType LHSType;
11749   // PropertyRef on LHS type need be directly obtained from
11750   // its declaration as it has a PseudoType.
11751   ObjCPropertyRefExpr *PRE
11752     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11753   if (PRE && !PRE->isImplicitProperty()) {
11754     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11755     if (PD)
11756       LHSType = PD->getType();
11757   }
11758 
11759   if (LHSType.isNull())
11760     LHSType = LHS->getType();
11761 
11762   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11763 
11764   if (LT == Qualifiers::OCL_Weak) {
11765     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11766       getCurFunction()->markSafeWeakUse(LHS);
11767   }
11768 
11769   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11770     return;
11771 
11772   // FIXME. Check for other life times.
11773   if (LT != Qualifiers::OCL_None)
11774     return;
11775 
11776   if (PRE) {
11777     if (PRE->isImplicitProperty())
11778       return;
11779     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11780     if (!PD)
11781       return;
11782 
11783     unsigned Attributes = PD->getPropertyAttributes();
11784     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11785       // when 'assign' attribute was not explicitly specified
11786       // by user, ignore it and rely on property type itself
11787       // for lifetime info.
11788       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11789       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11790           LHSType->isObjCRetainableType())
11791         return;
11792 
11793       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11794         if (cast->getCastKind() == CK_ARCConsumeObject) {
11795           Diag(Loc, diag::warn_arc_retained_property_assign)
11796           << RHS->getSourceRange();
11797           return;
11798         }
11799         RHS = cast->getSubExpr();
11800       }
11801     }
11802     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11803       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11804         return;
11805     }
11806   }
11807 }
11808 
11809 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11810 
11811 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11812                                         SourceLocation StmtLoc,
11813                                         const NullStmt *Body) {
11814   // Do not warn if the body is a macro that expands to nothing, e.g:
11815   //
11816   // #define CALL(x)
11817   // if (condition)
11818   //   CALL(0);
11819   if (Body->hasLeadingEmptyMacro())
11820     return false;
11821 
11822   // Get line numbers of statement and body.
11823   bool StmtLineInvalid;
11824   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11825                                                       &StmtLineInvalid);
11826   if (StmtLineInvalid)
11827     return false;
11828 
11829   bool BodyLineInvalid;
11830   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11831                                                       &BodyLineInvalid);
11832   if (BodyLineInvalid)
11833     return false;
11834 
11835   // Warn if null statement and body are on the same line.
11836   if (StmtLine != BodyLine)
11837     return false;
11838 
11839   return true;
11840 }
11841 
11842 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11843                                  const Stmt *Body,
11844                                  unsigned DiagID) {
11845   // Since this is a syntactic check, don't emit diagnostic for template
11846   // instantiations, this just adds noise.
11847   if (CurrentInstantiationScope)
11848     return;
11849 
11850   // The body should be a null statement.
11851   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11852   if (!NBody)
11853     return;
11854 
11855   // Do the usual checks.
11856   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11857     return;
11858 
11859   Diag(NBody->getSemiLoc(), DiagID);
11860   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11861 }
11862 
11863 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11864                                  const Stmt *PossibleBody) {
11865   assert(!CurrentInstantiationScope); // Ensured by caller
11866 
11867   SourceLocation StmtLoc;
11868   const Stmt *Body;
11869   unsigned DiagID;
11870   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11871     StmtLoc = FS->getRParenLoc();
11872     Body = FS->getBody();
11873     DiagID = diag::warn_empty_for_body;
11874   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11875     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11876     Body = WS->getBody();
11877     DiagID = diag::warn_empty_while_body;
11878   } else
11879     return; // Neither `for' nor `while'.
11880 
11881   // The body should be a null statement.
11882   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11883   if (!NBody)
11884     return;
11885 
11886   // Skip expensive checks if diagnostic is disabled.
11887   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11888     return;
11889 
11890   // Do the usual checks.
11891   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11892     return;
11893 
11894   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11895   // noise level low, emit diagnostics only if for/while is followed by a
11896   // CompoundStmt, e.g.:
11897   //    for (int i = 0; i < n; i++);
11898   //    {
11899   //      a(i);
11900   //    }
11901   // or if for/while is followed by a statement with more indentation
11902   // than for/while itself:
11903   //    for (int i = 0; i < n; i++);
11904   //      a(i);
11905   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11906   if (!ProbableTypo) {
11907     bool BodyColInvalid;
11908     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11909                              PossibleBody->getLocStart(),
11910                              &BodyColInvalid);
11911     if (BodyColInvalid)
11912       return;
11913 
11914     bool StmtColInvalid;
11915     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11916                              S->getLocStart(),
11917                              &StmtColInvalid);
11918     if (StmtColInvalid)
11919       return;
11920 
11921     if (BodyCol > StmtCol)
11922       ProbableTypo = true;
11923   }
11924 
11925   if (ProbableTypo) {
11926     Diag(NBody->getSemiLoc(), DiagID);
11927     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11928   }
11929 }
11930 
11931 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11932 
11933 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11934 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11935                              SourceLocation OpLoc) {
11936   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11937     return;
11938 
11939   if (inTemplateInstantiation())
11940     return;
11941 
11942   // Strip parens and casts away.
11943   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11944   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11945 
11946   // Check for a call expression
11947   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11948   if (!CE || CE->getNumArgs() != 1)
11949     return;
11950 
11951   // Check for a call to std::move
11952   if (!CE->isCallToStdMove())
11953     return;
11954 
11955   // Get argument from std::move
11956   RHSExpr = CE->getArg(0);
11957 
11958   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11959   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11960 
11961   // Two DeclRefExpr's, check that the decls are the same.
11962   if (LHSDeclRef && RHSDeclRef) {
11963     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11964       return;
11965     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11966         RHSDeclRef->getDecl()->getCanonicalDecl())
11967       return;
11968 
11969     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11970                                         << LHSExpr->getSourceRange()
11971                                         << RHSExpr->getSourceRange();
11972     return;
11973   }
11974 
11975   // Member variables require a different approach to check for self moves.
11976   // MemberExpr's are the same if every nested MemberExpr refers to the same
11977   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11978   // the base Expr's are CXXThisExpr's.
11979   const Expr *LHSBase = LHSExpr;
11980   const Expr *RHSBase = RHSExpr;
11981   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11982   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11983   if (!LHSME || !RHSME)
11984     return;
11985 
11986   while (LHSME && RHSME) {
11987     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11988         RHSME->getMemberDecl()->getCanonicalDecl())
11989       return;
11990 
11991     LHSBase = LHSME->getBase();
11992     RHSBase = RHSME->getBase();
11993     LHSME = dyn_cast<MemberExpr>(LHSBase);
11994     RHSME = dyn_cast<MemberExpr>(RHSBase);
11995   }
11996 
11997   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11998   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11999   if (LHSDeclRef && RHSDeclRef) {
12000     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
12001       return;
12002     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
12003         RHSDeclRef->getDecl()->getCanonicalDecl())
12004       return;
12005 
12006     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12007                                         << LHSExpr->getSourceRange()
12008                                         << RHSExpr->getSourceRange();
12009     return;
12010   }
12011 
12012   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
12013     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
12014                                         << LHSExpr->getSourceRange()
12015                                         << RHSExpr->getSourceRange();
12016 }
12017 
12018 //===--- Layout compatibility ----------------------------------------------//
12019 
12020 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
12021 
12022 /// \brief Check if two enumeration types are layout-compatible.
12023 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
12024   // C++11 [dcl.enum] p8:
12025   // Two enumeration types are layout-compatible if they have the same
12026   // underlying type.
12027   return ED1->isComplete() && ED2->isComplete() &&
12028          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
12029 }
12030 
12031 /// \brief Check if two fields are layout-compatible.
12032 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
12033                                FieldDecl *Field2) {
12034   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
12035     return false;
12036 
12037   if (Field1->isBitField() != Field2->isBitField())
12038     return false;
12039 
12040   if (Field1->isBitField()) {
12041     // Make sure that the bit-fields are the same length.
12042     unsigned Bits1 = Field1->getBitWidthValue(C);
12043     unsigned Bits2 = Field2->getBitWidthValue(C);
12044 
12045     if (Bits1 != Bits2)
12046       return false;
12047   }
12048 
12049   return true;
12050 }
12051 
12052 /// \brief Check if two standard-layout structs are layout-compatible.
12053 /// (C++11 [class.mem] p17)
12054 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
12055                                      RecordDecl *RD2) {
12056   // If both records are C++ classes, check that base classes match.
12057   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
12058     // If one of records is a CXXRecordDecl we are in C++ mode,
12059     // thus the other one is a CXXRecordDecl, too.
12060     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
12061     // Check number of base classes.
12062     if (D1CXX->getNumBases() != D2CXX->getNumBases())
12063       return false;
12064 
12065     // Check the base classes.
12066     for (CXXRecordDecl::base_class_const_iterator
12067                Base1 = D1CXX->bases_begin(),
12068            BaseEnd1 = D1CXX->bases_end(),
12069               Base2 = D2CXX->bases_begin();
12070          Base1 != BaseEnd1;
12071          ++Base1, ++Base2) {
12072       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
12073         return false;
12074     }
12075   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
12076     // If only RD2 is a C++ class, it should have zero base classes.
12077     if (D2CXX->getNumBases() > 0)
12078       return false;
12079   }
12080 
12081   // Check the fields.
12082   RecordDecl::field_iterator Field2 = RD2->field_begin(),
12083                              Field2End = RD2->field_end(),
12084                              Field1 = RD1->field_begin(),
12085                              Field1End = RD1->field_end();
12086   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
12087     if (!isLayoutCompatible(C, *Field1, *Field2))
12088       return false;
12089   }
12090   if (Field1 != Field1End || Field2 != Field2End)
12091     return false;
12092 
12093   return true;
12094 }
12095 
12096 /// \brief Check if two standard-layout unions are layout-compatible.
12097 /// (C++11 [class.mem] p18)
12098 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12099                                     RecordDecl *RD2) {
12100   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12101   for (auto *Field2 : RD2->fields())
12102     UnmatchedFields.insert(Field2);
12103 
12104   for (auto *Field1 : RD1->fields()) {
12105     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12106         I = UnmatchedFields.begin(),
12107         E = UnmatchedFields.end();
12108 
12109     for ( ; I != E; ++I) {
12110       if (isLayoutCompatible(C, Field1, *I)) {
12111         bool Result = UnmatchedFields.erase(*I);
12112         (void) Result;
12113         assert(Result);
12114         break;
12115       }
12116     }
12117     if (I == E)
12118       return false;
12119   }
12120 
12121   return UnmatchedFields.empty();
12122 }
12123 
12124 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12125                                RecordDecl *RD2) {
12126   if (RD1->isUnion() != RD2->isUnion())
12127     return false;
12128 
12129   if (RD1->isUnion())
12130     return isLayoutCompatibleUnion(C, RD1, RD2);
12131   else
12132     return isLayoutCompatibleStruct(C, RD1, RD2);
12133 }
12134 
12135 /// \brief Check if two types are layout-compatible in C++11 sense.
12136 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12137   if (T1.isNull() || T2.isNull())
12138     return false;
12139 
12140   // C++11 [basic.types] p11:
12141   // If two types T1 and T2 are the same type, then T1 and T2 are
12142   // layout-compatible types.
12143   if (C.hasSameType(T1, T2))
12144     return true;
12145 
12146   T1 = T1.getCanonicalType().getUnqualifiedType();
12147   T2 = T2.getCanonicalType().getUnqualifiedType();
12148 
12149   const Type::TypeClass TC1 = T1->getTypeClass();
12150   const Type::TypeClass TC2 = T2->getTypeClass();
12151 
12152   if (TC1 != TC2)
12153     return false;
12154 
12155   if (TC1 == Type::Enum) {
12156     return isLayoutCompatible(C,
12157                               cast<EnumType>(T1)->getDecl(),
12158                               cast<EnumType>(T2)->getDecl());
12159   } else if (TC1 == Type::Record) {
12160     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12161       return false;
12162 
12163     return isLayoutCompatible(C,
12164                               cast<RecordType>(T1)->getDecl(),
12165                               cast<RecordType>(T2)->getDecl());
12166   }
12167 
12168   return false;
12169 }
12170 
12171 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12172 
12173 /// \brief Given a type tag expression find the type tag itself.
12174 ///
12175 /// \param TypeExpr Type tag expression, as it appears in user's code.
12176 ///
12177 /// \param VD Declaration of an identifier that appears in a type tag.
12178 ///
12179 /// \param MagicValue Type tag magic value.
12180 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12181                             const ValueDecl **VD, uint64_t *MagicValue) {
12182   while(true) {
12183     if (!TypeExpr)
12184       return false;
12185 
12186     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12187 
12188     switch (TypeExpr->getStmtClass()) {
12189     case Stmt::UnaryOperatorClass: {
12190       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12191       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12192         TypeExpr = UO->getSubExpr();
12193         continue;
12194       }
12195       return false;
12196     }
12197 
12198     case Stmt::DeclRefExprClass: {
12199       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12200       *VD = DRE->getDecl();
12201       return true;
12202     }
12203 
12204     case Stmt::IntegerLiteralClass: {
12205       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12206       llvm::APInt MagicValueAPInt = IL->getValue();
12207       if (MagicValueAPInt.getActiveBits() <= 64) {
12208         *MagicValue = MagicValueAPInt.getZExtValue();
12209         return true;
12210       } else
12211         return false;
12212     }
12213 
12214     case Stmt::BinaryConditionalOperatorClass:
12215     case Stmt::ConditionalOperatorClass: {
12216       const AbstractConditionalOperator *ACO =
12217           cast<AbstractConditionalOperator>(TypeExpr);
12218       bool Result;
12219       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12220         if (Result)
12221           TypeExpr = ACO->getTrueExpr();
12222         else
12223           TypeExpr = ACO->getFalseExpr();
12224         continue;
12225       }
12226       return false;
12227     }
12228 
12229     case Stmt::BinaryOperatorClass: {
12230       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12231       if (BO->getOpcode() == BO_Comma) {
12232         TypeExpr = BO->getRHS();
12233         continue;
12234       }
12235       return false;
12236     }
12237 
12238     default:
12239       return false;
12240     }
12241   }
12242 }
12243 
12244 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12245 ///
12246 /// \param TypeExpr Expression that specifies a type tag.
12247 ///
12248 /// \param MagicValues Registered magic values.
12249 ///
12250 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12251 ///        kind.
12252 ///
12253 /// \param TypeInfo Information about the corresponding C type.
12254 ///
12255 /// \returns true if the corresponding C type was found.
12256 static bool GetMatchingCType(
12257         const IdentifierInfo *ArgumentKind,
12258         const Expr *TypeExpr, const ASTContext &Ctx,
12259         const llvm::DenseMap<Sema::TypeTagMagicValue,
12260                              Sema::TypeTagData> *MagicValues,
12261         bool &FoundWrongKind,
12262         Sema::TypeTagData &TypeInfo) {
12263   FoundWrongKind = false;
12264 
12265   // Variable declaration that has type_tag_for_datatype attribute.
12266   const ValueDecl *VD = nullptr;
12267 
12268   uint64_t MagicValue;
12269 
12270   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12271     return false;
12272 
12273   if (VD) {
12274     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12275       if (I->getArgumentKind() != ArgumentKind) {
12276         FoundWrongKind = true;
12277         return false;
12278       }
12279       TypeInfo.Type = I->getMatchingCType();
12280       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12281       TypeInfo.MustBeNull = I->getMustBeNull();
12282       return true;
12283     }
12284     return false;
12285   }
12286 
12287   if (!MagicValues)
12288     return false;
12289 
12290   llvm::DenseMap<Sema::TypeTagMagicValue,
12291                  Sema::TypeTagData>::const_iterator I =
12292       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12293   if (I == MagicValues->end())
12294     return false;
12295 
12296   TypeInfo = I->second;
12297   return true;
12298 }
12299 
12300 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12301                                       uint64_t MagicValue, QualType Type,
12302                                       bool LayoutCompatible,
12303                                       bool MustBeNull) {
12304   if (!TypeTagForDatatypeMagicValues)
12305     TypeTagForDatatypeMagicValues.reset(
12306         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12307 
12308   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12309   (*TypeTagForDatatypeMagicValues)[Magic] =
12310       TypeTagData(Type, LayoutCompatible, MustBeNull);
12311 }
12312 
12313 static bool IsSameCharType(QualType T1, QualType T2) {
12314   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12315   if (!BT1)
12316     return false;
12317 
12318   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12319   if (!BT2)
12320     return false;
12321 
12322   BuiltinType::Kind T1Kind = BT1->getKind();
12323   BuiltinType::Kind T2Kind = BT2->getKind();
12324 
12325   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12326          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12327          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12328          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12329 }
12330 
12331 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12332                                     const ArrayRef<const Expr *> ExprArgs,
12333                                     SourceLocation CallSiteLoc) {
12334   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12335   bool IsPointerAttr = Attr->getIsPointer();
12336 
12337   // Retrieve the argument representing the 'type_tag'.
12338   if (Attr->getTypeTagIdx() >= ExprArgs.size()) {
12339     // Add 1 to display the user's specified value.
12340     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12341         << 0 << Attr->getTypeTagIdx() + 1;
12342     return;
12343   }
12344   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12345   bool FoundWrongKind;
12346   TypeTagData TypeInfo;
12347   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12348                         TypeTagForDatatypeMagicValues.get(),
12349                         FoundWrongKind, TypeInfo)) {
12350     if (FoundWrongKind)
12351       Diag(TypeTagExpr->getExprLoc(),
12352            diag::warn_type_tag_for_datatype_wrong_kind)
12353         << TypeTagExpr->getSourceRange();
12354     return;
12355   }
12356 
12357   // Retrieve the argument representing the 'arg_idx'.
12358   if (Attr->getArgumentIdx() >= ExprArgs.size()) {
12359     // Add 1 to display the user's specified value.
12360     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12361         << 1 << Attr->getArgumentIdx() + 1;
12362     return;
12363   }
12364   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12365   if (IsPointerAttr) {
12366     // Skip implicit cast of pointer to `void *' (as a function argument).
12367     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12368       if (ICE->getType()->isVoidPointerType() &&
12369           ICE->getCastKind() == CK_BitCast)
12370         ArgumentExpr = ICE->getSubExpr();
12371   }
12372   QualType ArgumentType = ArgumentExpr->getType();
12373 
12374   // Passing a `void*' pointer shouldn't trigger a warning.
12375   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12376     return;
12377 
12378   if (TypeInfo.MustBeNull) {
12379     // Type tag with matching void type requires a null pointer.
12380     if (!ArgumentExpr->isNullPointerConstant(Context,
12381                                              Expr::NPC_ValueDependentIsNotNull)) {
12382       Diag(ArgumentExpr->getExprLoc(),
12383            diag::warn_type_safety_null_pointer_required)
12384           << ArgumentKind->getName()
12385           << ArgumentExpr->getSourceRange()
12386           << TypeTagExpr->getSourceRange();
12387     }
12388     return;
12389   }
12390 
12391   QualType RequiredType = TypeInfo.Type;
12392   if (IsPointerAttr)
12393     RequiredType = Context.getPointerType(RequiredType);
12394 
12395   bool mismatch = false;
12396   if (!TypeInfo.LayoutCompatible) {
12397     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12398 
12399     // C++11 [basic.fundamental] p1:
12400     // Plain char, signed char, and unsigned char are three distinct types.
12401     //
12402     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12403     // char' depending on the current char signedness mode.
12404     if (mismatch)
12405       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12406                                            RequiredType->getPointeeType())) ||
12407           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12408         mismatch = false;
12409   } else
12410     if (IsPointerAttr)
12411       mismatch = !isLayoutCompatible(Context,
12412                                      ArgumentType->getPointeeType(),
12413                                      RequiredType->getPointeeType());
12414     else
12415       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12416 
12417   if (mismatch)
12418     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12419         << ArgumentType << ArgumentKind
12420         << TypeInfo.LayoutCompatible << RequiredType
12421         << ArgumentExpr->getSourceRange()
12422         << TypeTagExpr->getSourceRange();
12423 }
12424 
12425 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12426                                          CharUnits Alignment) {
12427   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12428 }
12429 
12430 void Sema::DiagnoseMisalignedMembers() {
12431   for (MisalignedMember &m : MisalignedMembers) {
12432     const NamedDecl *ND = m.RD;
12433     if (ND->getName().empty()) {
12434       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12435         ND = TD;
12436     }
12437     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12438         << m.MD << ND << m.E->getSourceRange();
12439   }
12440   MisalignedMembers.clear();
12441 }
12442 
12443 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12444   E = E->IgnoreParens();
12445   if (!T->isPointerType() && !T->isIntegerType())
12446     return;
12447   if (isa<UnaryOperator>(E) &&
12448       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12449     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12450     if (isa<MemberExpr>(Op)) {
12451       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12452                           MisalignedMember(Op));
12453       if (MA != MisalignedMembers.end() &&
12454           (T->isIntegerType() ||
12455            (T->isPointerType() &&
12456             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12457         MisalignedMembers.erase(MA);
12458     }
12459   }
12460 }
12461 
12462 void Sema::RefersToMemberWithReducedAlignment(
12463     Expr *E,
12464     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12465         Action) {
12466   const auto *ME = dyn_cast<MemberExpr>(E);
12467   if (!ME)
12468     return;
12469 
12470   // No need to check expressions with an __unaligned-qualified type.
12471   if (E->getType().getQualifiers().hasUnaligned())
12472     return;
12473 
12474   // For a chain of MemberExpr like "a.b.c.d" this list
12475   // will keep FieldDecl's like [d, c, b].
12476   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12477   const MemberExpr *TopME = nullptr;
12478   bool AnyIsPacked = false;
12479   do {
12480     QualType BaseType = ME->getBase()->getType();
12481     if (ME->isArrow())
12482       BaseType = BaseType->getPointeeType();
12483     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12484     if (RD->isInvalidDecl())
12485       return;
12486 
12487     ValueDecl *MD = ME->getMemberDecl();
12488     auto *FD = dyn_cast<FieldDecl>(MD);
12489     // We do not care about non-data members.
12490     if (!FD || FD->isInvalidDecl())
12491       return;
12492 
12493     AnyIsPacked =
12494         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12495     ReverseMemberChain.push_back(FD);
12496 
12497     TopME = ME;
12498     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12499   } while (ME);
12500   assert(TopME && "We did not compute a topmost MemberExpr!");
12501 
12502   // Not the scope of this diagnostic.
12503   if (!AnyIsPacked)
12504     return;
12505 
12506   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12507   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12508   // TODO: The innermost base of the member expression may be too complicated.
12509   // For now, just disregard these cases. This is left for future
12510   // improvement.
12511   if (!DRE && !isa<CXXThisExpr>(TopBase))
12512       return;
12513 
12514   // Alignment expected by the whole expression.
12515   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12516 
12517   // No need to do anything else with this case.
12518   if (ExpectedAlignment.isOne())
12519     return;
12520 
12521   // Synthesize offset of the whole access.
12522   CharUnits Offset;
12523   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12524        I++) {
12525     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12526   }
12527 
12528   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12529   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12530       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12531 
12532   // The base expression of the innermost MemberExpr may give
12533   // stronger guarantees than the class containing the member.
12534   if (DRE && !TopME->isArrow()) {
12535     const ValueDecl *VD = DRE->getDecl();
12536     if (!VD->getType()->isReferenceType())
12537       CompleteObjectAlignment =
12538           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12539   }
12540 
12541   // Check if the synthesized offset fulfills the alignment.
12542   if (Offset % ExpectedAlignment != 0 ||
12543       // It may fulfill the offset it but the effective alignment may still be
12544       // lower than the expected expression alignment.
12545       CompleteObjectAlignment < ExpectedAlignment) {
12546     // If this happens, we want to determine a sensible culprit of this.
12547     // Intuitively, watching the chain of member expressions from right to
12548     // left, we start with the required alignment (as required by the field
12549     // type) but some packed attribute in that chain has reduced the alignment.
12550     // It may happen that another packed structure increases it again. But if
12551     // we are here such increase has not been enough. So pointing the first
12552     // FieldDecl that either is packed or else its RecordDecl is,
12553     // seems reasonable.
12554     FieldDecl *FD = nullptr;
12555     CharUnits Alignment;
12556     for (FieldDecl *FDI : ReverseMemberChain) {
12557       if (FDI->hasAttr<PackedAttr>() ||
12558           FDI->getParent()->hasAttr<PackedAttr>()) {
12559         FD = FDI;
12560         Alignment = std::min(
12561             Context.getTypeAlignInChars(FD->getType()),
12562             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12563         break;
12564       }
12565     }
12566     assert(FD && "We did not find a packed FieldDecl!");
12567     Action(E, FD->getParent(), FD, Alignment);
12568   }
12569 }
12570 
12571 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12572   using namespace std::placeholders;
12573 
12574   RefersToMemberWithReducedAlignment(
12575       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12576                      _2, _3, _4));
12577 }
12578