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 #include "clang/Basic/arm_fp16.inc"
1357 #undef GET_NEON_OVERLOAD_CHECK
1358   }
1359 
1360   // For NEON intrinsics which are overloaded on vector element type, validate
1361   // the immediate which specifies which variant to emit.
1362   unsigned ImmArg = TheCall->getNumArgs()-1;
1363   if (mask) {
1364     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1365       return true;
1366 
1367     TV = Result.getLimitedValue(64);
1368     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1369       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1370         << TheCall->getArg(ImmArg)->getSourceRange();
1371   }
1372 
1373   if (PtrArgNum >= 0) {
1374     // Check that pointer arguments have the specified type.
1375     Expr *Arg = TheCall->getArg(PtrArgNum);
1376     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1377       Arg = ICE->getSubExpr();
1378     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1379     QualType RHSTy = RHS.get()->getType();
1380 
1381     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1382     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1383                           Arch == llvm::Triple::aarch64_be;
1384     bool IsInt64Long =
1385         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1386     QualType EltTy =
1387         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1388     if (HasConstPtr)
1389       EltTy = EltTy.withConst();
1390     QualType LHSTy = Context.getPointerType(EltTy);
1391     AssignConvertType ConvTy;
1392     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1393     if (RHS.isInvalid())
1394       return true;
1395     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1396                                  RHS.get(), AA_Assigning))
1397       return true;
1398   }
1399 
1400   // For NEON intrinsics which take an immediate value as part of the
1401   // instruction, range check them here.
1402   unsigned i = 0, l = 0, u = 0;
1403   switch (BuiltinID) {
1404   default:
1405     return false;
1406 #define GET_NEON_IMMEDIATE_CHECK
1407 #include "clang/Basic/arm_neon.inc"
1408 #include "clang/Basic/arm_fp16.inc"
1409 #undef GET_NEON_IMMEDIATE_CHECK
1410   }
1411 
1412   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1413 }
1414 
1415 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1416                                         unsigned MaxWidth) {
1417   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1418           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1419           BuiltinID == ARM::BI__builtin_arm_strex ||
1420           BuiltinID == ARM::BI__builtin_arm_stlex ||
1421           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1422           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1423           BuiltinID == AArch64::BI__builtin_arm_strex ||
1424           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1425          "unexpected ARM builtin");
1426   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1427                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1428                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1429                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1430 
1431   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1432 
1433   // Ensure that we have the proper number of arguments.
1434   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1435     return true;
1436 
1437   // Inspect the pointer argument of the atomic builtin.  This should always be
1438   // a pointer type, whose element is an integral scalar or pointer type.
1439   // Because it is a pointer type, we don't have to worry about any implicit
1440   // casts here.
1441   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1442   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1443   if (PointerArgRes.isInvalid())
1444     return true;
1445   PointerArg = PointerArgRes.get();
1446 
1447   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1448   if (!pointerType) {
1449     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1450       << PointerArg->getType() << PointerArg->getSourceRange();
1451     return true;
1452   }
1453 
1454   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1455   // task is to insert the appropriate casts into the AST. First work out just
1456   // what the appropriate type is.
1457   QualType ValType = pointerType->getPointeeType();
1458   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1459   if (IsLdrex)
1460     AddrType.addConst();
1461 
1462   // Issue a warning if the cast is dodgy.
1463   CastKind CastNeeded = CK_NoOp;
1464   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1465     CastNeeded = CK_BitCast;
1466     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1467       << PointerArg->getType()
1468       << Context.getPointerType(AddrType)
1469       << AA_Passing << PointerArg->getSourceRange();
1470   }
1471 
1472   // Finally, do the cast and replace the argument with the corrected version.
1473   AddrType = Context.getPointerType(AddrType);
1474   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1475   if (PointerArgRes.isInvalid())
1476     return true;
1477   PointerArg = PointerArgRes.get();
1478 
1479   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1480 
1481   // In general, we allow ints, floats and pointers to be loaded and stored.
1482   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1483       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1484     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1485       << PointerArg->getType() << PointerArg->getSourceRange();
1486     return true;
1487   }
1488 
1489   // But ARM doesn't have instructions to deal with 128-bit versions.
1490   if (Context.getTypeSize(ValType) > MaxWidth) {
1491     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1492     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1493       << PointerArg->getType() << PointerArg->getSourceRange();
1494     return true;
1495   }
1496 
1497   switch (ValType.getObjCLifetime()) {
1498   case Qualifiers::OCL_None:
1499   case Qualifiers::OCL_ExplicitNone:
1500     // okay
1501     break;
1502 
1503   case Qualifiers::OCL_Weak:
1504   case Qualifiers::OCL_Strong:
1505   case Qualifiers::OCL_Autoreleasing:
1506     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1507       << ValType << PointerArg->getSourceRange();
1508     return true;
1509   }
1510 
1511   if (IsLdrex) {
1512     TheCall->setType(ValType);
1513     return false;
1514   }
1515 
1516   // Initialize the argument to be stored.
1517   ExprResult ValArg = TheCall->getArg(0);
1518   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1519       Context, ValType, /*consume*/ false);
1520   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1521   if (ValArg.isInvalid())
1522     return true;
1523   TheCall->setArg(0, ValArg.get());
1524 
1525   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1526   // but the custom checker bypasses all default analysis.
1527   TheCall->setType(Context.IntTy);
1528   return false;
1529 }
1530 
1531 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1532   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1533       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1534       BuiltinID == ARM::BI__builtin_arm_strex ||
1535       BuiltinID == ARM::BI__builtin_arm_stlex) {
1536     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1537   }
1538 
1539   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1540     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1541       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1542   }
1543 
1544   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1545       BuiltinID == ARM::BI__builtin_arm_wsr64)
1546     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1547 
1548   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1549       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1550       BuiltinID == ARM::BI__builtin_arm_wsr ||
1551       BuiltinID == ARM::BI__builtin_arm_wsrp)
1552     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1553 
1554   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1555     return true;
1556 
1557   // For intrinsics which take an immediate value as part of the instruction,
1558   // range check them here.
1559   // FIXME: VFP Intrinsics should error if VFP not present.
1560   switch (BuiltinID) {
1561   default: return false;
1562   case ARM::BI__builtin_arm_ssat:
1563     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
1564   case ARM::BI__builtin_arm_usat:
1565     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
1566   case ARM::BI__builtin_arm_ssat16:
1567     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
1568   case ARM::BI__builtin_arm_usat16:
1569     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
1570   case ARM::BI__builtin_arm_vcvtr_f:
1571   case ARM::BI__builtin_arm_vcvtr_d:
1572     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
1573   case ARM::BI__builtin_arm_dmb:
1574   case ARM::BI__builtin_arm_dsb:
1575   case ARM::BI__builtin_arm_isb:
1576   case ARM::BI__builtin_arm_dbg:
1577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
1578   }
1579 }
1580 
1581 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1582                                          CallExpr *TheCall) {
1583   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1584       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1585       BuiltinID == AArch64::BI__builtin_arm_strex ||
1586       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1587     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1588   }
1589 
1590   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1591     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1592       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1593       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1594       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1595   }
1596 
1597   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1598       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1599     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1600 
1601   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1602       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1603       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1604       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1605     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1606 
1607   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1608     return true;
1609 
1610   // For intrinsics which take an immediate value as part of the instruction,
1611   // range check them here.
1612   unsigned i = 0, l = 0, u = 0;
1613   switch (BuiltinID) {
1614   default: return false;
1615   case AArch64::BI__builtin_arm_dmb:
1616   case AArch64::BI__builtin_arm_dsb:
1617   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1618   }
1619 
1620   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1621 }
1622 
1623 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1624 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1625 // ordering for DSP is unspecified. MSA is ordered by the data format used
1626 // by the underlying instruction i.e., df/m, df/n and then by size.
1627 //
1628 // FIXME: The size tests here should instead be tablegen'd along with the
1629 //        definitions from include/clang/Basic/BuiltinsMips.def.
1630 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1631 //        be too.
1632 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1633   unsigned i = 0, l = 0, u = 0, m = 0;
1634   switch (BuiltinID) {
1635   default: return false;
1636   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1637   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1638   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1639   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1640   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1641   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1642   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1643   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1644   // df/m field.
1645   // These intrinsics take an unsigned 3 bit immediate.
1646   case Mips::BI__builtin_msa_bclri_b:
1647   case Mips::BI__builtin_msa_bnegi_b:
1648   case Mips::BI__builtin_msa_bseti_b:
1649   case Mips::BI__builtin_msa_sat_s_b:
1650   case Mips::BI__builtin_msa_sat_u_b:
1651   case Mips::BI__builtin_msa_slli_b:
1652   case Mips::BI__builtin_msa_srai_b:
1653   case Mips::BI__builtin_msa_srari_b:
1654   case Mips::BI__builtin_msa_srli_b:
1655   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1656   case Mips::BI__builtin_msa_binsli_b:
1657   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1658   // These intrinsics take an unsigned 4 bit immediate.
1659   case Mips::BI__builtin_msa_bclri_h:
1660   case Mips::BI__builtin_msa_bnegi_h:
1661   case Mips::BI__builtin_msa_bseti_h:
1662   case Mips::BI__builtin_msa_sat_s_h:
1663   case Mips::BI__builtin_msa_sat_u_h:
1664   case Mips::BI__builtin_msa_slli_h:
1665   case Mips::BI__builtin_msa_srai_h:
1666   case Mips::BI__builtin_msa_srari_h:
1667   case Mips::BI__builtin_msa_srli_h:
1668   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1669   case Mips::BI__builtin_msa_binsli_h:
1670   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1671   // These intrinsics take an unsigned 5 bit immedate.
1672   // The first block of intrinsics actually have an unsigned 5 bit field,
1673   // not a df/n field.
1674   case Mips::BI__builtin_msa_clei_u_b:
1675   case Mips::BI__builtin_msa_clei_u_h:
1676   case Mips::BI__builtin_msa_clei_u_w:
1677   case Mips::BI__builtin_msa_clei_u_d:
1678   case Mips::BI__builtin_msa_clti_u_b:
1679   case Mips::BI__builtin_msa_clti_u_h:
1680   case Mips::BI__builtin_msa_clti_u_w:
1681   case Mips::BI__builtin_msa_clti_u_d:
1682   case Mips::BI__builtin_msa_maxi_u_b:
1683   case Mips::BI__builtin_msa_maxi_u_h:
1684   case Mips::BI__builtin_msa_maxi_u_w:
1685   case Mips::BI__builtin_msa_maxi_u_d:
1686   case Mips::BI__builtin_msa_mini_u_b:
1687   case Mips::BI__builtin_msa_mini_u_h:
1688   case Mips::BI__builtin_msa_mini_u_w:
1689   case Mips::BI__builtin_msa_mini_u_d:
1690   case Mips::BI__builtin_msa_addvi_b:
1691   case Mips::BI__builtin_msa_addvi_h:
1692   case Mips::BI__builtin_msa_addvi_w:
1693   case Mips::BI__builtin_msa_addvi_d:
1694   case Mips::BI__builtin_msa_bclri_w:
1695   case Mips::BI__builtin_msa_bnegi_w:
1696   case Mips::BI__builtin_msa_bseti_w:
1697   case Mips::BI__builtin_msa_sat_s_w:
1698   case Mips::BI__builtin_msa_sat_u_w:
1699   case Mips::BI__builtin_msa_slli_w:
1700   case Mips::BI__builtin_msa_srai_w:
1701   case Mips::BI__builtin_msa_srari_w:
1702   case Mips::BI__builtin_msa_srli_w:
1703   case Mips::BI__builtin_msa_srlri_w:
1704   case Mips::BI__builtin_msa_subvi_b:
1705   case Mips::BI__builtin_msa_subvi_h:
1706   case Mips::BI__builtin_msa_subvi_w:
1707   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1708   case Mips::BI__builtin_msa_binsli_w:
1709   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1710   // These intrinsics take an unsigned 6 bit immediate.
1711   case Mips::BI__builtin_msa_bclri_d:
1712   case Mips::BI__builtin_msa_bnegi_d:
1713   case Mips::BI__builtin_msa_bseti_d:
1714   case Mips::BI__builtin_msa_sat_s_d:
1715   case Mips::BI__builtin_msa_sat_u_d:
1716   case Mips::BI__builtin_msa_slli_d:
1717   case Mips::BI__builtin_msa_srai_d:
1718   case Mips::BI__builtin_msa_srari_d:
1719   case Mips::BI__builtin_msa_srli_d:
1720   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1721   case Mips::BI__builtin_msa_binsli_d:
1722   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1723   // These intrinsics take a signed 5 bit immediate.
1724   case Mips::BI__builtin_msa_ceqi_b:
1725   case Mips::BI__builtin_msa_ceqi_h:
1726   case Mips::BI__builtin_msa_ceqi_w:
1727   case Mips::BI__builtin_msa_ceqi_d:
1728   case Mips::BI__builtin_msa_clti_s_b:
1729   case Mips::BI__builtin_msa_clti_s_h:
1730   case Mips::BI__builtin_msa_clti_s_w:
1731   case Mips::BI__builtin_msa_clti_s_d:
1732   case Mips::BI__builtin_msa_clei_s_b:
1733   case Mips::BI__builtin_msa_clei_s_h:
1734   case Mips::BI__builtin_msa_clei_s_w:
1735   case Mips::BI__builtin_msa_clei_s_d:
1736   case Mips::BI__builtin_msa_maxi_s_b:
1737   case Mips::BI__builtin_msa_maxi_s_h:
1738   case Mips::BI__builtin_msa_maxi_s_w:
1739   case Mips::BI__builtin_msa_maxi_s_d:
1740   case Mips::BI__builtin_msa_mini_s_b:
1741   case Mips::BI__builtin_msa_mini_s_h:
1742   case Mips::BI__builtin_msa_mini_s_w:
1743   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1744   // These intrinsics take an unsigned 8 bit immediate.
1745   case Mips::BI__builtin_msa_andi_b:
1746   case Mips::BI__builtin_msa_nori_b:
1747   case Mips::BI__builtin_msa_ori_b:
1748   case Mips::BI__builtin_msa_shf_b:
1749   case Mips::BI__builtin_msa_shf_h:
1750   case Mips::BI__builtin_msa_shf_w:
1751   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1752   case Mips::BI__builtin_msa_bseli_b:
1753   case Mips::BI__builtin_msa_bmnzi_b:
1754   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1755   // df/n format
1756   // These intrinsics take an unsigned 4 bit immediate.
1757   case Mips::BI__builtin_msa_copy_s_b:
1758   case Mips::BI__builtin_msa_copy_u_b:
1759   case Mips::BI__builtin_msa_insve_b:
1760   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1761   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1762   // These intrinsics take an unsigned 3 bit immediate.
1763   case Mips::BI__builtin_msa_copy_s_h:
1764   case Mips::BI__builtin_msa_copy_u_h:
1765   case Mips::BI__builtin_msa_insve_h:
1766   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1767   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1768   // These intrinsics take an unsigned 2 bit immediate.
1769   case Mips::BI__builtin_msa_copy_s_w:
1770   case Mips::BI__builtin_msa_copy_u_w:
1771   case Mips::BI__builtin_msa_insve_w:
1772   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1773   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1774   // These intrinsics take an unsigned 1 bit immediate.
1775   case Mips::BI__builtin_msa_copy_s_d:
1776   case Mips::BI__builtin_msa_copy_u_d:
1777   case Mips::BI__builtin_msa_insve_d:
1778   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1779   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1780   // Memory offsets and immediate loads.
1781   // These intrinsics take a signed 10 bit immediate.
1782   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1783   case Mips::BI__builtin_msa_ldi_h:
1784   case Mips::BI__builtin_msa_ldi_w:
1785   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1786   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1787   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1788   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1789   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1790   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1791   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1792   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1793   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1794   }
1795 
1796   if (!m)
1797     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1798 
1799   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1800          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1801 }
1802 
1803 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1804   unsigned i = 0, l = 0, u = 0;
1805   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1806                       BuiltinID == PPC::BI__builtin_divdeu ||
1807                       BuiltinID == PPC::BI__builtin_bpermd;
1808   bool IsTarget64Bit = Context.getTargetInfo()
1809                               .getTypeWidth(Context
1810                                             .getTargetInfo()
1811                                             .getIntPtrType()) == 64;
1812   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1813                        BuiltinID == PPC::BI__builtin_divweu ||
1814                        BuiltinID == PPC::BI__builtin_divde ||
1815                        BuiltinID == PPC::BI__builtin_divdeu;
1816 
1817   if (Is64BitBltin && !IsTarget64Bit)
1818       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1819              << TheCall->getSourceRange();
1820 
1821   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1822       (BuiltinID == PPC::BI__builtin_bpermd &&
1823        !Context.getTargetInfo().hasFeature("bpermd")))
1824     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1825            << TheCall->getSourceRange();
1826 
1827   switch (BuiltinID) {
1828   default: return false;
1829   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1830   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1831     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1832            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1833   case PPC::BI__builtin_tbegin:
1834   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1835   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1836   case PPC::BI__builtin_tabortwc:
1837   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1838   case PPC::BI__builtin_tabortwci:
1839   case PPC::BI__builtin_tabortdci:
1840     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1841            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1842   case PPC::BI__builtin_vsx_xxpermdi:
1843   case PPC::BI__builtin_vsx_xxsldwi:
1844     return SemaBuiltinVSX(TheCall);
1845   }
1846   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1847 }
1848 
1849 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1850                                            CallExpr *TheCall) {
1851   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1852     Expr *Arg = TheCall->getArg(0);
1853     llvm::APSInt AbortCode(32);
1854     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1855         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1856       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1857              << Arg->getSourceRange();
1858   }
1859 
1860   // For intrinsics which take an immediate value as part of the instruction,
1861   // range check them here.
1862   unsigned i = 0, l = 0, u = 0;
1863   switch (BuiltinID) {
1864   default: return false;
1865   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1866   case SystemZ::BI__builtin_s390_verimb:
1867   case SystemZ::BI__builtin_s390_verimh:
1868   case SystemZ::BI__builtin_s390_verimf:
1869   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1870   case SystemZ::BI__builtin_s390_vfaeb:
1871   case SystemZ::BI__builtin_s390_vfaeh:
1872   case SystemZ::BI__builtin_s390_vfaef:
1873   case SystemZ::BI__builtin_s390_vfaebs:
1874   case SystemZ::BI__builtin_s390_vfaehs:
1875   case SystemZ::BI__builtin_s390_vfaefs:
1876   case SystemZ::BI__builtin_s390_vfaezb:
1877   case SystemZ::BI__builtin_s390_vfaezh:
1878   case SystemZ::BI__builtin_s390_vfaezf:
1879   case SystemZ::BI__builtin_s390_vfaezbs:
1880   case SystemZ::BI__builtin_s390_vfaezhs:
1881   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1882   case SystemZ::BI__builtin_s390_vfisb:
1883   case SystemZ::BI__builtin_s390_vfidb:
1884     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1885            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1886   case SystemZ::BI__builtin_s390_vftcisb:
1887   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1888   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1889   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1890   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1891   case SystemZ::BI__builtin_s390_vstrcb:
1892   case SystemZ::BI__builtin_s390_vstrch:
1893   case SystemZ::BI__builtin_s390_vstrcf:
1894   case SystemZ::BI__builtin_s390_vstrczb:
1895   case SystemZ::BI__builtin_s390_vstrczh:
1896   case SystemZ::BI__builtin_s390_vstrczf:
1897   case SystemZ::BI__builtin_s390_vstrcbs:
1898   case SystemZ::BI__builtin_s390_vstrchs:
1899   case SystemZ::BI__builtin_s390_vstrcfs:
1900   case SystemZ::BI__builtin_s390_vstrczbs:
1901   case SystemZ::BI__builtin_s390_vstrczhs:
1902   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1903   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1904   case SystemZ::BI__builtin_s390_vfminsb:
1905   case SystemZ::BI__builtin_s390_vfmaxsb:
1906   case SystemZ::BI__builtin_s390_vfmindb:
1907   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1908   }
1909   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1910 }
1911 
1912 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1913 /// This checks that the target supports __builtin_cpu_supports and
1914 /// that the string argument is constant and valid.
1915 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1916   Expr *Arg = TheCall->getArg(0);
1917 
1918   // Check if the argument is a string literal.
1919   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1920     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1921            << Arg->getSourceRange();
1922 
1923   // Check the contents of the string.
1924   StringRef Feature =
1925       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1926   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1927     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1928            << Arg->getSourceRange();
1929   return false;
1930 }
1931 
1932 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1933 /// This checks that the target supports __builtin_cpu_is and
1934 /// that the string argument is constant and valid.
1935 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1936   Expr *Arg = TheCall->getArg(0);
1937 
1938   // Check if the argument is a string literal.
1939   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1940     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1941            << Arg->getSourceRange();
1942 
1943   // Check the contents of the string.
1944   StringRef Feature =
1945       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1946   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1947     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1948            << Arg->getSourceRange();
1949   return false;
1950 }
1951 
1952 // Check if the rounding mode is legal.
1953 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1954   // Indicates if this instruction has rounding control or just SAE.
1955   bool HasRC = false;
1956 
1957   unsigned ArgNum = 0;
1958   switch (BuiltinID) {
1959   default:
1960     return false;
1961   case X86::BI__builtin_ia32_vcvttsd2si32:
1962   case X86::BI__builtin_ia32_vcvttsd2si64:
1963   case X86::BI__builtin_ia32_vcvttsd2usi32:
1964   case X86::BI__builtin_ia32_vcvttsd2usi64:
1965   case X86::BI__builtin_ia32_vcvttss2si32:
1966   case X86::BI__builtin_ia32_vcvttss2si64:
1967   case X86::BI__builtin_ia32_vcvttss2usi32:
1968   case X86::BI__builtin_ia32_vcvttss2usi64:
1969     ArgNum = 1;
1970     break;
1971   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1972   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1973   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1974   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1975   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1976   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1977   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1978   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1979   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1980   case X86::BI__builtin_ia32_exp2pd_mask:
1981   case X86::BI__builtin_ia32_exp2ps_mask:
1982   case X86::BI__builtin_ia32_getexppd512_mask:
1983   case X86::BI__builtin_ia32_getexpps512_mask:
1984   case X86::BI__builtin_ia32_rcp28pd_mask:
1985   case X86::BI__builtin_ia32_rcp28ps_mask:
1986   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1987   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1988   case X86::BI__builtin_ia32_vcomisd:
1989   case X86::BI__builtin_ia32_vcomiss:
1990   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1991     ArgNum = 3;
1992     break;
1993   case X86::BI__builtin_ia32_cmppd512_mask:
1994   case X86::BI__builtin_ia32_cmpps512_mask:
1995   case X86::BI__builtin_ia32_cmpsd_mask:
1996   case X86::BI__builtin_ia32_cmpss_mask:
1997   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1998   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1999   case X86::BI__builtin_ia32_getexpss128_round_mask:
2000   case X86::BI__builtin_ia32_maxpd512_mask:
2001   case X86::BI__builtin_ia32_maxps512_mask:
2002   case X86::BI__builtin_ia32_maxsd_round_mask:
2003   case X86::BI__builtin_ia32_maxss_round_mask:
2004   case X86::BI__builtin_ia32_minpd512_mask:
2005   case X86::BI__builtin_ia32_minps512_mask:
2006   case X86::BI__builtin_ia32_minsd_round_mask:
2007   case X86::BI__builtin_ia32_minss_round_mask:
2008   case X86::BI__builtin_ia32_rcp28sd_round_mask:
2009   case X86::BI__builtin_ia32_rcp28ss_round_mask:
2010   case X86::BI__builtin_ia32_reducepd512_mask:
2011   case X86::BI__builtin_ia32_reduceps512_mask:
2012   case X86::BI__builtin_ia32_rndscalepd_mask:
2013   case X86::BI__builtin_ia32_rndscaleps_mask:
2014   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
2015   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
2016     ArgNum = 4;
2017     break;
2018   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2019   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2020   case X86::BI__builtin_ia32_fixupimmps512_mask:
2021   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2022   case X86::BI__builtin_ia32_fixupimmsd_mask:
2023   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2024   case X86::BI__builtin_ia32_fixupimmss_mask:
2025   case X86::BI__builtin_ia32_fixupimmss_maskz:
2026   case X86::BI__builtin_ia32_rangepd512_mask:
2027   case X86::BI__builtin_ia32_rangeps512_mask:
2028   case X86::BI__builtin_ia32_rangesd128_round_mask:
2029   case X86::BI__builtin_ia32_rangess128_round_mask:
2030   case X86::BI__builtin_ia32_reducesd_mask:
2031   case X86::BI__builtin_ia32_reducess_mask:
2032   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2033   case X86::BI__builtin_ia32_rndscaless_round_mask:
2034     ArgNum = 5;
2035     break;
2036   case X86::BI__builtin_ia32_vcvtsd2si64:
2037   case X86::BI__builtin_ia32_vcvtsd2si32:
2038   case X86::BI__builtin_ia32_vcvtsd2usi32:
2039   case X86::BI__builtin_ia32_vcvtsd2usi64:
2040   case X86::BI__builtin_ia32_vcvtss2si32:
2041   case X86::BI__builtin_ia32_vcvtss2si64:
2042   case X86::BI__builtin_ia32_vcvtss2usi32:
2043   case X86::BI__builtin_ia32_vcvtss2usi64:
2044     ArgNum = 1;
2045     HasRC = true;
2046     break;
2047   case X86::BI__builtin_ia32_cvtsi2sd64:
2048   case X86::BI__builtin_ia32_cvtsi2ss32:
2049   case X86::BI__builtin_ia32_cvtsi2ss64:
2050   case X86::BI__builtin_ia32_cvtusi2sd64:
2051   case X86::BI__builtin_ia32_cvtusi2ss32:
2052   case X86::BI__builtin_ia32_cvtusi2ss64:
2053     ArgNum = 2;
2054     HasRC = true;
2055     break;
2056   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
2057   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
2058   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2059   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2060   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2061   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2062   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2063   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2064   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2065   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2066   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2067   case X86::BI__builtin_ia32_sqrtpd512_mask:
2068   case X86::BI__builtin_ia32_sqrtps512_mask:
2069     ArgNum = 3;
2070     HasRC = true;
2071     break;
2072   case X86::BI__builtin_ia32_addpd512_mask:
2073   case X86::BI__builtin_ia32_addps512_mask:
2074   case X86::BI__builtin_ia32_divpd512_mask:
2075   case X86::BI__builtin_ia32_divps512_mask:
2076   case X86::BI__builtin_ia32_mulpd512_mask:
2077   case X86::BI__builtin_ia32_mulps512_mask:
2078   case X86::BI__builtin_ia32_subpd512_mask:
2079   case X86::BI__builtin_ia32_subps512_mask:
2080   case X86::BI__builtin_ia32_addss_round_mask:
2081   case X86::BI__builtin_ia32_addsd_round_mask:
2082   case X86::BI__builtin_ia32_divss_round_mask:
2083   case X86::BI__builtin_ia32_divsd_round_mask:
2084   case X86::BI__builtin_ia32_mulss_round_mask:
2085   case X86::BI__builtin_ia32_mulsd_round_mask:
2086   case X86::BI__builtin_ia32_subss_round_mask:
2087   case X86::BI__builtin_ia32_subsd_round_mask:
2088   case X86::BI__builtin_ia32_scalefpd512_mask:
2089   case X86::BI__builtin_ia32_scalefps512_mask:
2090   case X86::BI__builtin_ia32_scalefsd_round_mask:
2091   case X86::BI__builtin_ia32_scalefss_round_mask:
2092   case X86::BI__builtin_ia32_getmantpd512_mask:
2093   case X86::BI__builtin_ia32_getmantps512_mask:
2094   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2095   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2096   case X86::BI__builtin_ia32_sqrtss_round_mask:
2097   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2098   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2099   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2100   case X86::BI__builtin_ia32_vfmaddps512_mask:
2101   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2102   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2103   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2104   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2105   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2106   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2107   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2108   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2109   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2110   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2111   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2112   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2113   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2114   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2115   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2116   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2117   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2118   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2119   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2120   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2121   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2122   case X86::BI__builtin_ia32_vfmaddss3_mask:
2123   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2124   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2125     ArgNum = 4;
2126     HasRC = true;
2127     break;
2128   case X86::BI__builtin_ia32_getmantsd_round_mask:
2129   case X86::BI__builtin_ia32_getmantss_round_mask:
2130     ArgNum = 5;
2131     HasRC = true;
2132     break;
2133   }
2134 
2135   llvm::APSInt Result;
2136 
2137   // We can't check the value of a dependent argument.
2138   Expr *Arg = TheCall->getArg(ArgNum);
2139   if (Arg->isTypeDependent() || Arg->isValueDependent())
2140     return false;
2141 
2142   // Check constant-ness first.
2143   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2144     return true;
2145 
2146   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2147   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2148   // combined with ROUND_NO_EXC.
2149   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2150       Result == 8/*ROUND_NO_EXC*/ ||
2151       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2152     return false;
2153 
2154   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2155     << Arg->getSourceRange();
2156 }
2157 
2158 // Check if the gather/scatter scale is legal.
2159 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2160                                              CallExpr *TheCall) {
2161   unsigned ArgNum = 0;
2162   switch (BuiltinID) {
2163   default:
2164     return false;
2165   case X86::BI__builtin_ia32_gatherpfdpd:
2166   case X86::BI__builtin_ia32_gatherpfdps:
2167   case X86::BI__builtin_ia32_gatherpfqpd:
2168   case X86::BI__builtin_ia32_gatherpfqps:
2169   case X86::BI__builtin_ia32_scatterpfdpd:
2170   case X86::BI__builtin_ia32_scatterpfdps:
2171   case X86::BI__builtin_ia32_scatterpfqpd:
2172   case X86::BI__builtin_ia32_scatterpfqps:
2173     ArgNum = 3;
2174     break;
2175   case X86::BI__builtin_ia32_gatherd_pd:
2176   case X86::BI__builtin_ia32_gatherd_pd256:
2177   case X86::BI__builtin_ia32_gatherq_pd:
2178   case X86::BI__builtin_ia32_gatherq_pd256:
2179   case X86::BI__builtin_ia32_gatherd_ps:
2180   case X86::BI__builtin_ia32_gatherd_ps256:
2181   case X86::BI__builtin_ia32_gatherq_ps:
2182   case X86::BI__builtin_ia32_gatherq_ps256:
2183   case X86::BI__builtin_ia32_gatherd_q:
2184   case X86::BI__builtin_ia32_gatherd_q256:
2185   case X86::BI__builtin_ia32_gatherq_q:
2186   case X86::BI__builtin_ia32_gatherq_q256:
2187   case X86::BI__builtin_ia32_gatherd_d:
2188   case X86::BI__builtin_ia32_gatherd_d256:
2189   case X86::BI__builtin_ia32_gatherq_d:
2190   case X86::BI__builtin_ia32_gatherq_d256:
2191   case X86::BI__builtin_ia32_gather3div2df:
2192   case X86::BI__builtin_ia32_gather3div2di:
2193   case X86::BI__builtin_ia32_gather3div4df:
2194   case X86::BI__builtin_ia32_gather3div4di:
2195   case X86::BI__builtin_ia32_gather3div4sf:
2196   case X86::BI__builtin_ia32_gather3div4si:
2197   case X86::BI__builtin_ia32_gather3div8sf:
2198   case X86::BI__builtin_ia32_gather3div8si:
2199   case X86::BI__builtin_ia32_gather3siv2df:
2200   case X86::BI__builtin_ia32_gather3siv2di:
2201   case X86::BI__builtin_ia32_gather3siv4df:
2202   case X86::BI__builtin_ia32_gather3siv4di:
2203   case X86::BI__builtin_ia32_gather3siv4sf:
2204   case X86::BI__builtin_ia32_gather3siv4si:
2205   case X86::BI__builtin_ia32_gather3siv8sf:
2206   case X86::BI__builtin_ia32_gather3siv8si:
2207   case X86::BI__builtin_ia32_gathersiv8df:
2208   case X86::BI__builtin_ia32_gathersiv16sf:
2209   case X86::BI__builtin_ia32_gatherdiv8df:
2210   case X86::BI__builtin_ia32_gatherdiv16sf:
2211   case X86::BI__builtin_ia32_gathersiv8di:
2212   case X86::BI__builtin_ia32_gathersiv16si:
2213   case X86::BI__builtin_ia32_gatherdiv8di:
2214   case X86::BI__builtin_ia32_gatherdiv16si:
2215   case X86::BI__builtin_ia32_scatterdiv2df:
2216   case X86::BI__builtin_ia32_scatterdiv2di:
2217   case X86::BI__builtin_ia32_scatterdiv4df:
2218   case X86::BI__builtin_ia32_scatterdiv4di:
2219   case X86::BI__builtin_ia32_scatterdiv4sf:
2220   case X86::BI__builtin_ia32_scatterdiv4si:
2221   case X86::BI__builtin_ia32_scatterdiv8sf:
2222   case X86::BI__builtin_ia32_scatterdiv8si:
2223   case X86::BI__builtin_ia32_scattersiv2df:
2224   case X86::BI__builtin_ia32_scattersiv2di:
2225   case X86::BI__builtin_ia32_scattersiv4df:
2226   case X86::BI__builtin_ia32_scattersiv4di:
2227   case X86::BI__builtin_ia32_scattersiv4sf:
2228   case X86::BI__builtin_ia32_scattersiv4si:
2229   case X86::BI__builtin_ia32_scattersiv8sf:
2230   case X86::BI__builtin_ia32_scattersiv8si:
2231   case X86::BI__builtin_ia32_scattersiv8df:
2232   case X86::BI__builtin_ia32_scattersiv16sf:
2233   case X86::BI__builtin_ia32_scatterdiv8df:
2234   case X86::BI__builtin_ia32_scatterdiv16sf:
2235   case X86::BI__builtin_ia32_scattersiv8di:
2236   case X86::BI__builtin_ia32_scattersiv16si:
2237   case X86::BI__builtin_ia32_scatterdiv8di:
2238   case X86::BI__builtin_ia32_scatterdiv16si:
2239     ArgNum = 4;
2240     break;
2241   }
2242 
2243   llvm::APSInt Result;
2244 
2245   // We can't check the value of a dependent argument.
2246   Expr *Arg = TheCall->getArg(ArgNum);
2247   if (Arg->isTypeDependent() || Arg->isValueDependent())
2248     return false;
2249 
2250   // Check constant-ness first.
2251   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2252     return true;
2253 
2254   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2255     return false;
2256 
2257   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2258     << Arg->getSourceRange();
2259 }
2260 
2261 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2262   if (BuiltinID == X86::BI__builtin_cpu_supports)
2263     return SemaBuiltinCpuSupports(*this, TheCall);
2264 
2265   if (BuiltinID == X86::BI__builtin_cpu_is)
2266     return SemaBuiltinCpuIs(*this, TheCall);
2267 
2268   // If the intrinsic has rounding or SAE make sure its valid.
2269   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2270     return true;
2271 
2272   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2273   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2274     return true;
2275 
2276   // For intrinsics which take an immediate value as part of the instruction,
2277   // range check them here.
2278   int i = 0, l = 0, u = 0;
2279   switch (BuiltinID) {
2280   default:
2281     return false;
2282   case X86::BI_mm_prefetch:
2283     i = 1; l = 0; u = 7;
2284     break;
2285   case X86::BI__builtin_ia32_sha1rnds4:
2286   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2287   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2288   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2289   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2290     i = 2; l = 0; u = 3;
2291     break;
2292   case X86::BI__builtin_ia32_vpermil2pd:
2293   case X86::BI__builtin_ia32_vpermil2pd256:
2294   case X86::BI__builtin_ia32_vpermil2ps:
2295   case X86::BI__builtin_ia32_vpermil2ps256:
2296     i = 3; l = 0; u = 3;
2297     break;
2298   case X86::BI__builtin_ia32_cmpb128_mask:
2299   case X86::BI__builtin_ia32_cmpw128_mask:
2300   case X86::BI__builtin_ia32_cmpd128_mask:
2301   case X86::BI__builtin_ia32_cmpq128_mask:
2302   case X86::BI__builtin_ia32_cmpb256_mask:
2303   case X86::BI__builtin_ia32_cmpw256_mask:
2304   case X86::BI__builtin_ia32_cmpd256_mask:
2305   case X86::BI__builtin_ia32_cmpq256_mask:
2306   case X86::BI__builtin_ia32_cmpb512_mask:
2307   case X86::BI__builtin_ia32_cmpw512_mask:
2308   case X86::BI__builtin_ia32_cmpd512_mask:
2309   case X86::BI__builtin_ia32_cmpq512_mask:
2310   case X86::BI__builtin_ia32_ucmpb128_mask:
2311   case X86::BI__builtin_ia32_ucmpw128_mask:
2312   case X86::BI__builtin_ia32_ucmpd128_mask:
2313   case X86::BI__builtin_ia32_ucmpq128_mask:
2314   case X86::BI__builtin_ia32_ucmpb256_mask:
2315   case X86::BI__builtin_ia32_ucmpw256_mask:
2316   case X86::BI__builtin_ia32_ucmpd256_mask:
2317   case X86::BI__builtin_ia32_ucmpq256_mask:
2318   case X86::BI__builtin_ia32_ucmpb512_mask:
2319   case X86::BI__builtin_ia32_ucmpw512_mask:
2320   case X86::BI__builtin_ia32_ucmpd512_mask:
2321   case X86::BI__builtin_ia32_ucmpq512_mask:
2322   case X86::BI__builtin_ia32_vpcomub:
2323   case X86::BI__builtin_ia32_vpcomuw:
2324   case X86::BI__builtin_ia32_vpcomud:
2325   case X86::BI__builtin_ia32_vpcomuq:
2326   case X86::BI__builtin_ia32_vpcomb:
2327   case X86::BI__builtin_ia32_vpcomw:
2328   case X86::BI__builtin_ia32_vpcomd:
2329   case X86::BI__builtin_ia32_vpcomq:
2330     i = 2; l = 0; u = 7;
2331     break;
2332   case X86::BI__builtin_ia32_roundps:
2333   case X86::BI__builtin_ia32_roundpd:
2334   case X86::BI__builtin_ia32_roundps256:
2335   case X86::BI__builtin_ia32_roundpd256:
2336     i = 1; l = 0; u = 15;
2337     break;
2338   case X86::BI__builtin_ia32_roundss:
2339   case X86::BI__builtin_ia32_roundsd:
2340   case X86::BI__builtin_ia32_rangepd128_mask:
2341   case X86::BI__builtin_ia32_rangepd256_mask:
2342   case X86::BI__builtin_ia32_rangepd512_mask:
2343   case X86::BI__builtin_ia32_rangeps128_mask:
2344   case X86::BI__builtin_ia32_rangeps256_mask:
2345   case X86::BI__builtin_ia32_rangeps512_mask:
2346   case X86::BI__builtin_ia32_getmantsd_round_mask:
2347   case X86::BI__builtin_ia32_getmantss_round_mask:
2348     i = 2; l = 0; u = 15;
2349     break;
2350   case X86::BI__builtin_ia32_cmpps:
2351   case X86::BI__builtin_ia32_cmpss:
2352   case X86::BI__builtin_ia32_cmppd:
2353   case X86::BI__builtin_ia32_cmpsd:
2354   case X86::BI__builtin_ia32_cmpps256:
2355   case X86::BI__builtin_ia32_cmppd256:
2356   case X86::BI__builtin_ia32_cmpps128_mask:
2357   case X86::BI__builtin_ia32_cmppd128_mask:
2358   case X86::BI__builtin_ia32_cmpps256_mask:
2359   case X86::BI__builtin_ia32_cmppd256_mask:
2360   case X86::BI__builtin_ia32_cmpps512_mask:
2361   case X86::BI__builtin_ia32_cmppd512_mask:
2362   case X86::BI__builtin_ia32_cmpsd_mask:
2363   case X86::BI__builtin_ia32_cmpss_mask:
2364     i = 2; l = 0; u = 31;
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_palignr128:
2404   case X86::BI__builtin_ia32_palignr256:
2405   case X86::BI__builtin_ia32_palignr512_mask:
2406   case X86::BI__builtin_ia32_vcomisd:
2407   case X86::BI__builtin_ia32_vcomiss:
2408   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2409   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2410   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2411   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2412   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2413   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2414   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2415   case X86::BI__builtin_ia32_vpshldd128_mask:
2416   case X86::BI__builtin_ia32_vpshldd256_mask:
2417   case X86::BI__builtin_ia32_vpshldd512_mask:
2418   case X86::BI__builtin_ia32_vpshldq128_mask:
2419   case X86::BI__builtin_ia32_vpshldq256_mask:
2420   case X86::BI__builtin_ia32_vpshldq512_mask:
2421   case X86::BI__builtin_ia32_vpshldw128_mask:
2422   case X86::BI__builtin_ia32_vpshldw256_mask:
2423   case X86::BI__builtin_ia32_vpshldw512_mask:
2424   case X86::BI__builtin_ia32_vpshrdd128_mask:
2425   case X86::BI__builtin_ia32_vpshrdd256_mask:
2426   case X86::BI__builtin_ia32_vpshrdd512_mask:
2427   case X86::BI__builtin_ia32_vpshrdq128_mask:
2428   case X86::BI__builtin_ia32_vpshrdq256_mask:
2429   case X86::BI__builtin_ia32_vpshrdq512_mask:
2430   case X86::BI__builtin_ia32_vpshrdw128_mask:
2431   case X86::BI__builtin_ia32_vpshrdw256_mask:
2432   case X86::BI__builtin_ia32_vpshrdw512_mask:
2433     i = 2; l = 0; u = 255;
2434     break;
2435   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2436   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2437   case X86::BI__builtin_ia32_fixupimmps512_mask:
2438   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2439   case X86::BI__builtin_ia32_fixupimmsd_mask:
2440   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2441   case X86::BI__builtin_ia32_fixupimmss_mask:
2442   case X86::BI__builtin_ia32_fixupimmss_maskz:
2443   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2444   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2445   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2446   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2447   case X86::BI__builtin_ia32_fixupimmps128_mask:
2448   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2449   case X86::BI__builtin_ia32_fixupimmps256_mask:
2450   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2451   case X86::BI__builtin_ia32_pternlogd512_mask:
2452   case X86::BI__builtin_ia32_pternlogd512_maskz:
2453   case X86::BI__builtin_ia32_pternlogq512_mask:
2454   case X86::BI__builtin_ia32_pternlogq512_maskz:
2455   case X86::BI__builtin_ia32_pternlogd128_mask:
2456   case X86::BI__builtin_ia32_pternlogd128_maskz:
2457   case X86::BI__builtin_ia32_pternlogd256_mask:
2458   case X86::BI__builtin_ia32_pternlogd256_maskz:
2459   case X86::BI__builtin_ia32_pternlogq128_mask:
2460   case X86::BI__builtin_ia32_pternlogq128_maskz:
2461   case X86::BI__builtin_ia32_pternlogq256_mask:
2462   case X86::BI__builtin_ia32_pternlogq256_maskz:
2463     i = 3; l = 0; u = 255;
2464     break;
2465   case X86::BI__builtin_ia32_gatherpfdpd:
2466   case X86::BI__builtin_ia32_gatherpfdps:
2467   case X86::BI__builtin_ia32_gatherpfqpd:
2468   case X86::BI__builtin_ia32_gatherpfqps:
2469   case X86::BI__builtin_ia32_scatterpfdpd:
2470   case X86::BI__builtin_ia32_scatterpfdps:
2471   case X86::BI__builtin_ia32_scatterpfqpd:
2472   case X86::BI__builtin_ia32_scatterpfqps:
2473     i = 4; l = 2; u = 3;
2474     break;
2475   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2476   case X86::BI__builtin_ia32_rndscaless_round_mask:
2477     i = 4; l = 0; u = 255;
2478     break;
2479   }
2480   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2481 }
2482 
2483 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2484 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2485 /// Returns true when the format fits the function and the FormatStringInfo has
2486 /// been populated.
2487 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2488                                FormatStringInfo *FSI) {
2489   FSI->HasVAListArg = Format->getFirstArg() == 0;
2490   FSI->FormatIdx = Format->getFormatIdx() - 1;
2491   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2492 
2493   // The way the format attribute works in GCC, the implicit this argument
2494   // of member functions is counted. However, it doesn't appear in our own
2495   // lists, so decrement format_idx in that case.
2496   if (IsCXXMember) {
2497     if(FSI->FormatIdx == 0)
2498       return false;
2499     --FSI->FormatIdx;
2500     if (FSI->FirstDataArg != 0)
2501       --FSI->FirstDataArg;
2502   }
2503   return true;
2504 }
2505 
2506 /// Checks if a the given expression evaluates to null.
2507 ///
2508 /// \brief Returns true if the value evaluates to null.
2509 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2510   // If the expression has non-null type, it doesn't evaluate to null.
2511   if (auto nullability
2512         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2513     if (*nullability == NullabilityKind::NonNull)
2514       return false;
2515   }
2516 
2517   // As a special case, transparent unions initialized with zero are
2518   // considered null for the purposes of the nonnull attribute.
2519   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2520     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2521       if (const CompoundLiteralExpr *CLE =
2522           dyn_cast<CompoundLiteralExpr>(Expr))
2523         if (const InitListExpr *ILE =
2524             dyn_cast<InitListExpr>(CLE->getInitializer()))
2525           Expr = ILE->getInit(0);
2526   }
2527 
2528   bool Result;
2529   return (!Expr->isValueDependent() &&
2530           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2531           !Result);
2532 }
2533 
2534 static void CheckNonNullArgument(Sema &S,
2535                                  const Expr *ArgExpr,
2536                                  SourceLocation CallSiteLoc) {
2537   if (CheckNonNullExpr(S, ArgExpr))
2538     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2539            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2540 }
2541 
2542 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2543   FormatStringInfo FSI;
2544   if ((GetFormatStringType(Format) == FST_NSString) &&
2545       getFormatStringInfo(Format, false, &FSI)) {
2546     Idx = FSI.FormatIdx;
2547     return true;
2548   }
2549   return false;
2550 }
2551 
2552 /// \brief Diagnose use of %s directive in an NSString which is being passed
2553 /// as formatting string to formatting method.
2554 static void
2555 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2556                                         const NamedDecl *FDecl,
2557                                         Expr **Args,
2558                                         unsigned NumArgs) {
2559   unsigned Idx = 0;
2560   bool Format = false;
2561   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2562   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2563     Idx = 2;
2564     Format = true;
2565   }
2566   else
2567     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2568       if (S.GetFormatNSStringIdx(I, Idx)) {
2569         Format = true;
2570         break;
2571       }
2572     }
2573   if (!Format || NumArgs <= Idx)
2574     return;
2575   const Expr *FormatExpr = Args[Idx];
2576   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2577     FormatExpr = CSCE->getSubExpr();
2578   const StringLiteral *FormatString;
2579   if (const ObjCStringLiteral *OSL =
2580       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2581     FormatString = OSL->getString();
2582   else
2583     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2584   if (!FormatString)
2585     return;
2586   if (S.FormatStringHasSArg(FormatString)) {
2587     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2588       << "%s" << 1 << 1;
2589     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2590       << FDecl->getDeclName();
2591   }
2592 }
2593 
2594 /// Determine whether the given type has a non-null nullability annotation.
2595 static bool isNonNullType(ASTContext &ctx, QualType type) {
2596   if (auto nullability = type->getNullability(ctx))
2597     return *nullability == NullabilityKind::NonNull;
2598 
2599   return false;
2600 }
2601 
2602 static void CheckNonNullArguments(Sema &S,
2603                                   const NamedDecl *FDecl,
2604                                   const FunctionProtoType *Proto,
2605                                   ArrayRef<const Expr *> Args,
2606                                   SourceLocation CallSiteLoc) {
2607   assert((FDecl || Proto) && "Need a function declaration or prototype");
2608 
2609   // Check the attributes attached to the method/function itself.
2610   llvm::SmallBitVector NonNullArgs;
2611   if (FDecl) {
2612     // Handle the nonnull attribute on the function/method declaration itself.
2613     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2614       if (!NonNull->args_size()) {
2615         // Easy case: all pointer arguments are nonnull.
2616         for (const auto *Arg : Args)
2617           if (S.isValidPointerAttrType(Arg->getType()))
2618             CheckNonNullArgument(S, Arg, CallSiteLoc);
2619         return;
2620       }
2621 
2622       for (const ParamIdx &Idx : NonNull->args()) {
2623         unsigned IdxAST = Idx.getASTIndex();
2624         if (IdxAST >= Args.size())
2625           continue;
2626         if (NonNullArgs.empty())
2627           NonNullArgs.resize(Args.size());
2628         NonNullArgs.set(IdxAST);
2629       }
2630     }
2631   }
2632 
2633   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2634     // Handle the nonnull attribute on the parameters of the
2635     // function/method.
2636     ArrayRef<ParmVarDecl*> parms;
2637     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2638       parms = FD->parameters();
2639     else
2640       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2641 
2642     unsigned ParamIndex = 0;
2643     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2644          I != E; ++I, ++ParamIndex) {
2645       const ParmVarDecl *PVD = *I;
2646       if (PVD->hasAttr<NonNullAttr>() ||
2647           isNonNullType(S.Context, PVD->getType())) {
2648         if (NonNullArgs.empty())
2649           NonNullArgs.resize(Args.size());
2650 
2651         NonNullArgs.set(ParamIndex);
2652       }
2653     }
2654   } else {
2655     // If we have a non-function, non-method declaration but no
2656     // function prototype, try to dig out the function prototype.
2657     if (!Proto) {
2658       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2659         QualType type = VD->getType().getNonReferenceType();
2660         if (auto pointerType = type->getAs<PointerType>())
2661           type = pointerType->getPointeeType();
2662         else if (auto blockType = type->getAs<BlockPointerType>())
2663           type = blockType->getPointeeType();
2664         // FIXME: data member pointers?
2665 
2666         // Dig out the function prototype, if there is one.
2667         Proto = type->getAs<FunctionProtoType>();
2668       }
2669     }
2670 
2671     // Fill in non-null argument information from the nullability
2672     // information on the parameter types (if we have them).
2673     if (Proto) {
2674       unsigned Index = 0;
2675       for (auto paramType : Proto->getParamTypes()) {
2676         if (isNonNullType(S.Context, paramType)) {
2677           if (NonNullArgs.empty())
2678             NonNullArgs.resize(Args.size());
2679 
2680           NonNullArgs.set(Index);
2681         }
2682 
2683         ++Index;
2684       }
2685     }
2686   }
2687 
2688   // Check for non-null arguments.
2689   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2690        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2691     if (NonNullArgs[ArgIndex])
2692       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2693   }
2694 }
2695 
2696 /// Handles the checks for format strings, non-POD arguments to vararg
2697 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2698 /// attributes.
2699 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2700                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2701                      bool IsMemberFunction, SourceLocation Loc,
2702                      SourceRange Range, VariadicCallType CallType) {
2703   // FIXME: We should check as much as we can in the template definition.
2704   if (CurContext->isDependentContext())
2705     return;
2706 
2707   // Printf and scanf checking.
2708   llvm::SmallBitVector CheckedVarArgs;
2709   if (FDecl) {
2710     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2711       // Only create vector if there are format attributes.
2712       CheckedVarArgs.resize(Args.size());
2713 
2714       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2715                            CheckedVarArgs);
2716     }
2717   }
2718 
2719   // Refuse POD arguments that weren't caught by the format string
2720   // checks above.
2721   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2722   if (CallType != VariadicDoesNotApply &&
2723       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2724     unsigned NumParams = Proto ? Proto->getNumParams()
2725                        : FDecl && isa<FunctionDecl>(FDecl)
2726                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2727                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2728                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2729                        : 0;
2730 
2731     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2732       // Args[ArgIdx] can be null in malformed code.
2733       if (const Expr *Arg = Args[ArgIdx]) {
2734         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2735           checkVariadicArgument(Arg, CallType);
2736       }
2737     }
2738   }
2739 
2740   if (FDecl || Proto) {
2741     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2742 
2743     // Type safety checking.
2744     if (FDecl) {
2745       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2746         CheckArgumentWithTypeTag(I, Args, Loc);
2747     }
2748   }
2749 
2750   if (FD)
2751     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2752 }
2753 
2754 /// CheckConstructorCall - Check a constructor call for correctness and safety
2755 /// properties not enforced by the C type system.
2756 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2757                                 ArrayRef<const Expr *> Args,
2758                                 const FunctionProtoType *Proto,
2759                                 SourceLocation Loc) {
2760   VariadicCallType CallType =
2761     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2762   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2763             Loc, SourceRange(), CallType);
2764 }
2765 
2766 /// CheckFunctionCall - Check a direct function call for various correctness
2767 /// and safety properties not strictly enforced by the C type system.
2768 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2769                              const FunctionProtoType *Proto) {
2770   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2771                               isa<CXXMethodDecl>(FDecl);
2772   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2773                           IsMemberOperatorCall;
2774   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2775                                                   TheCall->getCallee());
2776   Expr** Args = TheCall->getArgs();
2777   unsigned NumArgs = TheCall->getNumArgs();
2778 
2779   Expr *ImplicitThis = nullptr;
2780   if (IsMemberOperatorCall) {
2781     // If this is a call to a member operator, hide the first argument
2782     // from checkCall.
2783     // FIXME: Our choice of AST representation here is less than ideal.
2784     ImplicitThis = Args[0];
2785     ++Args;
2786     --NumArgs;
2787   } else if (IsMemberFunction)
2788     ImplicitThis =
2789         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2790 
2791   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2792             IsMemberFunction, TheCall->getRParenLoc(),
2793             TheCall->getCallee()->getSourceRange(), CallType);
2794 
2795   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2796   // None of the checks below are needed for functions that don't have
2797   // simple names (e.g., C++ conversion functions).
2798   if (!FnInfo)
2799     return false;
2800 
2801   CheckAbsoluteValueFunction(TheCall, FDecl);
2802   CheckMaxUnsignedZero(TheCall, FDecl);
2803 
2804   if (getLangOpts().ObjC1)
2805     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2806 
2807   unsigned CMId = FDecl->getMemoryFunctionKind();
2808   if (CMId == 0)
2809     return false;
2810 
2811   // Handle memory setting and copying functions.
2812   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2813     CheckStrlcpycatArguments(TheCall, FnInfo);
2814   else if (CMId == Builtin::BIstrncat)
2815     CheckStrncatArguments(TheCall, FnInfo);
2816   else
2817     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2818 
2819   return false;
2820 }
2821 
2822 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2823                                ArrayRef<const Expr *> Args) {
2824   VariadicCallType CallType =
2825       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2826 
2827   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2828             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2829             CallType);
2830 
2831   return false;
2832 }
2833 
2834 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2835                             const FunctionProtoType *Proto) {
2836   QualType Ty;
2837   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2838     Ty = V->getType().getNonReferenceType();
2839   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2840     Ty = F->getType().getNonReferenceType();
2841   else
2842     return false;
2843 
2844   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2845       !Ty->isFunctionProtoType())
2846     return false;
2847 
2848   VariadicCallType CallType;
2849   if (!Proto || !Proto->isVariadic()) {
2850     CallType = VariadicDoesNotApply;
2851   } else if (Ty->isBlockPointerType()) {
2852     CallType = VariadicBlock;
2853   } else { // Ty->isFunctionPointerType()
2854     CallType = VariadicFunction;
2855   }
2856 
2857   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2858             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2859             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2860             TheCall->getCallee()->getSourceRange(), CallType);
2861 
2862   return false;
2863 }
2864 
2865 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2866 /// such as function pointers returned from functions.
2867 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2868   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2869                                                   TheCall->getCallee());
2870   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2871             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2872             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2873             TheCall->getCallee()->getSourceRange(), CallType);
2874 
2875   return false;
2876 }
2877 
2878 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2879   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2880     return false;
2881 
2882   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2883   switch (Op) {
2884   case AtomicExpr::AO__c11_atomic_init:
2885   case AtomicExpr::AO__opencl_atomic_init:
2886     llvm_unreachable("There is no ordering argument for an init");
2887 
2888   case AtomicExpr::AO__c11_atomic_load:
2889   case AtomicExpr::AO__opencl_atomic_load:
2890   case AtomicExpr::AO__atomic_load_n:
2891   case AtomicExpr::AO__atomic_load:
2892     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2893            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2894 
2895   case AtomicExpr::AO__c11_atomic_store:
2896   case AtomicExpr::AO__opencl_atomic_store:
2897   case AtomicExpr::AO__atomic_store:
2898   case AtomicExpr::AO__atomic_store_n:
2899     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2900            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2901            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2902 
2903   default:
2904     return true;
2905   }
2906 }
2907 
2908 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2909                                          AtomicExpr::AtomicOp Op) {
2910   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2911   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2912 
2913   // All the non-OpenCL operations take one of the following forms.
2914   // The OpenCL operations take the __c11 forms with one extra argument for
2915   // synchronization scope.
2916   enum {
2917     // C    __c11_atomic_init(A *, C)
2918     Init,
2919 
2920     // C    __c11_atomic_load(A *, int)
2921     Load,
2922 
2923     // void __atomic_load(A *, CP, int)
2924     LoadCopy,
2925 
2926     // void __atomic_store(A *, CP, int)
2927     Copy,
2928 
2929     // C    __c11_atomic_add(A *, M, int)
2930     Arithmetic,
2931 
2932     // C    __atomic_exchange_n(A *, CP, int)
2933     Xchg,
2934 
2935     // void __atomic_exchange(A *, C *, CP, int)
2936     GNUXchg,
2937 
2938     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2939     C11CmpXchg,
2940 
2941     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2942     GNUCmpXchg
2943   } Form = Init;
2944 
2945   const unsigned NumForm = GNUCmpXchg + 1;
2946   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2947   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2948   // where:
2949   //   C is an appropriate type,
2950   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2951   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2952   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2953   //   the int parameters are for orderings.
2954 
2955   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2956       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2957       "need to update code for modified forms");
2958   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2959                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2960                         AtomicExpr::AO__atomic_load,
2961                 "need to update code for modified C11 atomics");
2962   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2963                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2964   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2965                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2966                IsOpenCL;
2967   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2968              Op == AtomicExpr::AO__atomic_store_n ||
2969              Op == AtomicExpr::AO__atomic_exchange_n ||
2970              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2971   bool IsAddSub = false;
2972 
2973   switch (Op) {
2974   case AtomicExpr::AO__c11_atomic_init:
2975   case AtomicExpr::AO__opencl_atomic_init:
2976     Form = Init;
2977     break;
2978 
2979   case AtomicExpr::AO__c11_atomic_load:
2980   case AtomicExpr::AO__opencl_atomic_load:
2981   case AtomicExpr::AO__atomic_load_n:
2982     Form = Load;
2983     break;
2984 
2985   case AtomicExpr::AO__atomic_load:
2986     Form = LoadCopy;
2987     break;
2988 
2989   case AtomicExpr::AO__c11_atomic_store:
2990   case AtomicExpr::AO__opencl_atomic_store:
2991   case AtomicExpr::AO__atomic_store:
2992   case AtomicExpr::AO__atomic_store_n:
2993     Form = Copy;
2994     break;
2995 
2996   case AtomicExpr::AO__c11_atomic_fetch_add:
2997   case AtomicExpr::AO__c11_atomic_fetch_sub:
2998   case AtomicExpr::AO__opencl_atomic_fetch_add:
2999   case AtomicExpr::AO__opencl_atomic_fetch_sub:
3000   case AtomicExpr::AO__opencl_atomic_fetch_min:
3001   case AtomicExpr::AO__opencl_atomic_fetch_max:
3002   case AtomicExpr::AO__atomic_fetch_add:
3003   case AtomicExpr::AO__atomic_fetch_sub:
3004   case AtomicExpr::AO__atomic_add_fetch:
3005   case AtomicExpr::AO__atomic_sub_fetch:
3006     IsAddSub = true;
3007     LLVM_FALLTHROUGH;
3008   case AtomicExpr::AO__c11_atomic_fetch_and:
3009   case AtomicExpr::AO__c11_atomic_fetch_or:
3010   case AtomicExpr::AO__c11_atomic_fetch_xor:
3011   case AtomicExpr::AO__opencl_atomic_fetch_and:
3012   case AtomicExpr::AO__opencl_atomic_fetch_or:
3013   case AtomicExpr::AO__opencl_atomic_fetch_xor:
3014   case AtomicExpr::AO__atomic_fetch_and:
3015   case AtomicExpr::AO__atomic_fetch_or:
3016   case AtomicExpr::AO__atomic_fetch_xor:
3017   case AtomicExpr::AO__atomic_fetch_nand:
3018   case AtomicExpr::AO__atomic_and_fetch:
3019   case AtomicExpr::AO__atomic_or_fetch:
3020   case AtomicExpr::AO__atomic_xor_fetch:
3021   case AtomicExpr::AO__atomic_nand_fetch:
3022     Form = Arithmetic;
3023     break;
3024 
3025   case AtomicExpr::AO__c11_atomic_exchange:
3026   case AtomicExpr::AO__opencl_atomic_exchange:
3027   case AtomicExpr::AO__atomic_exchange_n:
3028     Form = Xchg;
3029     break;
3030 
3031   case AtomicExpr::AO__atomic_exchange:
3032     Form = GNUXchg;
3033     break;
3034 
3035   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
3036   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
3037   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
3038   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
3039     Form = C11CmpXchg;
3040     break;
3041 
3042   case AtomicExpr::AO__atomic_compare_exchange:
3043   case AtomicExpr::AO__atomic_compare_exchange_n:
3044     Form = GNUCmpXchg;
3045     break;
3046   }
3047 
3048   unsigned AdjustedNumArgs = NumArgs[Form];
3049   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
3050     ++AdjustedNumArgs;
3051   // Check we have the right number of arguments.
3052   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3053     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3054       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3055       << TheCall->getCallee()->getSourceRange();
3056     return ExprError();
3057   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3058     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3059          diag::err_typecheck_call_too_many_args)
3060       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3061       << TheCall->getCallee()->getSourceRange();
3062     return ExprError();
3063   }
3064 
3065   // Inspect the first argument of the atomic operation.
3066   Expr *Ptr = TheCall->getArg(0);
3067   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3068   if (ConvertedPtr.isInvalid())
3069     return ExprError();
3070 
3071   Ptr = ConvertedPtr.get();
3072   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3073   if (!pointerType) {
3074     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3075       << Ptr->getType() << Ptr->getSourceRange();
3076     return ExprError();
3077   }
3078 
3079   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3080   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3081   QualType ValType = AtomTy; // 'C'
3082   if (IsC11) {
3083     if (!AtomTy->isAtomicType()) {
3084       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3085         << Ptr->getType() << Ptr->getSourceRange();
3086       return ExprError();
3087     }
3088     if (AtomTy.isConstQualified() ||
3089         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3090       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3091           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3092           << Ptr->getSourceRange();
3093       return ExprError();
3094     }
3095     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3096   } else if (Form != Load && Form != LoadCopy) {
3097     if (ValType.isConstQualified()) {
3098       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3099         << Ptr->getType() << Ptr->getSourceRange();
3100       return ExprError();
3101     }
3102   }
3103 
3104   // For an arithmetic operation, the implied arithmetic must be well-formed.
3105   if (Form == Arithmetic) {
3106     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3107     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3108       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3109         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3110       return ExprError();
3111     }
3112     if (!IsAddSub && !ValType->isIntegerType()) {
3113       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3114         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3115       return ExprError();
3116     }
3117     if (IsC11 && ValType->isPointerType() &&
3118         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3119                             diag::err_incomplete_type)) {
3120       return ExprError();
3121     }
3122   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3123     // For __atomic_*_n operations, the value type must be a scalar integral or
3124     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3125     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3126       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3127     return ExprError();
3128   }
3129 
3130   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3131       !AtomTy->isScalarType()) {
3132     // For GNU atomics, require a trivially-copyable type. This is not part of
3133     // the GNU atomics specification, but we enforce it for sanity.
3134     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3135       << Ptr->getType() << Ptr->getSourceRange();
3136     return ExprError();
3137   }
3138 
3139   switch (ValType.getObjCLifetime()) {
3140   case Qualifiers::OCL_None:
3141   case Qualifiers::OCL_ExplicitNone:
3142     // okay
3143     break;
3144 
3145   case Qualifiers::OCL_Weak:
3146   case Qualifiers::OCL_Strong:
3147   case Qualifiers::OCL_Autoreleasing:
3148     // FIXME: Can this happen? By this point, ValType should be known
3149     // to be trivially copyable.
3150     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3151       << ValType << Ptr->getSourceRange();
3152     return ExprError();
3153   }
3154 
3155   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3156   // volatile-ness of the pointee-type inject itself into the result or the
3157   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3158   ValType.removeLocalVolatile();
3159   ValType.removeLocalConst();
3160   QualType ResultType = ValType;
3161   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3162       Form == Init)
3163     ResultType = Context.VoidTy;
3164   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3165     ResultType = Context.BoolTy;
3166 
3167   // The type of a parameter passed 'by value'. In the GNU atomics, such
3168   // arguments are actually passed as pointers.
3169   QualType ByValType = ValType; // 'CP'
3170   if (!IsC11 && !IsN)
3171     ByValType = Ptr->getType();
3172 
3173   // The first argument --- the pointer --- has a fixed type; we
3174   // deduce the types of the rest of the arguments accordingly.  Walk
3175   // the remaining arguments, converting them to the deduced value type.
3176   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3177     QualType Ty;
3178     if (i < NumVals[Form] + 1) {
3179       switch (i) {
3180       case 1:
3181         // The second argument is the non-atomic operand. For arithmetic, this
3182         // is always passed by value, and for a compare_exchange it is always
3183         // passed by address. For the rest, GNU uses by-address and C11 uses
3184         // by-value.
3185         assert(Form != Load);
3186         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3187           Ty = ValType;
3188         else if (Form == Copy || Form == Xchg)
3189           Ty = ByValType;
3190         else if (Form == Arithmetic)
3191           Ty = Context.getPointerDiffType();
3192         else {
3193           Expr *ValArg = TheCall->getArg(i);
3194           // Treat this argument as _Nonnull as we want to show a warning if
3195           // NULL is passed into it.
3196           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3197           LangAS AS = LangAS::Default;
3198           // Keep address space of non-atomic pointer type.
3199           if (const PointerType *PtrTy =
3200                   ValArg->getType()->getAs<PointerType>()) {
3201             AS = PtrTy->getPointeeType().getAddressSpace();
3202           }
3203           Ty = Context.getPointerType(
3204               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3205         }
3206         break;
3207       case 2:
3208         // The third argument to compare_exchange / GNU exchange is a
3209         // (pointer to a) desired value.
3210         Ty = ByValType;
3211         break;
3212       case 3:
3213         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3214         Ty = Context.BoolTy;
3215         break;
3216       }
3217     } else {
3218       // The order(s) and scope are always converted to int.
3219       Ty = Context.IntTy;
3220     }
3221 
3222     InitializedEntity Entity =
3223         InitializedEntity::InitializeParameter(Context, Ty, false);
3224     ExprResult Arg = TheCall->getArg(i);
3225     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3226     if (Arg.isInvalid())
3227       return true;
3228     TheCall->setArg(i, Arg.get());
3229   }
3230 
3231   // Permute the arguments into a 'consistent' order.
3232   SmallVector<Expr*, 5> SubExprs;
3233   SubExprs.push_back(Ptr);
3234   switch (Form) {
3235   case Init:
3236     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3237     SubExprs.push_back(TheCall->getArg(1)); // Val1
3238     break;
3239   case Load:
3240     SubExprs.push_back(TheCall->getArg(1)); // Order
3241     break;
3242   case LoadCopy:
3243   case Copy:
3244   case Arithmetic:
3245   case Xchg:
3246     SubExprs.push_back(TheCall->getArg(2)); // Order
3247     SubExprs.push_back(TheCall->getArg(1)); // Val1
3248     break;
3249   case GNUXchg:
3250     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3251     SubExprs.push_back(TheCall->getArg(3)); // Order
3252     SubExprs.push_back(TheCall->getArg(1)); // Val1
3253     SubExprs.push_back(TheCall->getArg(2)); // Val2
3254     break;
3255   case C11CmpXchg:
3256     SubExprs.push_back(TheCall->getArg(3)); // Order
3257     SubExprs.push_back(TheCall->getArg(1)); // Val1
3258     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3259     SubExprs.push_back(TheCall->getArg(2)); // Val2
3260     break;
3261   case GNUCmpXchg:
3262     SubExprs.push_back(TheCall->getArg(4)); // Order
3263     SubExprs.push_back(TheCall->getArg(1)); // Val1
3264     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3265     SubExprs.push_back(TheCall->getArg(2)); // Val2
3266     SubExprs.push_back(TheCall->getArg(3)); // Weak
3267     break;
3268   }
3269 
3270   if (SubExprs.size() >= 2 && Form != Init) {
3271     llvm::APSInt Result(32);
3272     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3273         !isValidOrderingForOp(Result.getSExtValue(), Op))
3274       Diag(SubExprs[1]->getLocStart(),
3275            diag::warn_atomic_op_has_invalid_memory_order)
3276           << SubExprs[1]->getSourceRange();
3277   }
3278 
3279   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3280     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3281     llvm::APSInt Result(32);
3282     if (Scope->isIntegerConstantExpr(Result, Context) &&
3283         !ScopeModel->isValid(Result.getZExtValue())) {
3284       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3285           << Scope->getSourceRange();
3286     }
3287     SubExprs.push_back(Scope);
3288   }
3289 
3290   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3291                                             SubExprs, ResultType, Op,
3292                                             TheCall->getRParenLoc());
3293 
3294   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3295        Op == AtomicExpr::AO__c11_atomic_store ||
3296        Op == AtomicExpr::AO__opencl_atomic_load ||
3297        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3298       Context.AtomicUsesUnsupportedLibcall(AE))
3299     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3300         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3301             Op == AtomicExpr::AO__opencl_atomic_load)
3302                 ? 0 : 1);
3303 
3304   return AE;
3305 }
3306 
3307 /// checkBuiltinArgument - Given a call to a builtin function, perform
3308 /// normal type-checking on the given argument, updating the call in
3309 /// place.  This is useful when a builtin function requires custom
3310 /// type-checking for some of its arguments but not necessarily all of
3311 /// them.
3312 ///
3313 /// Returns true on error.
3314 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3315   FunctionDecl *Fn = E->getDirectCallee();
3316   assert(Fn && "builtin call without direct callee!");
3317 
3318   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3319   InitializedEntity Entity =
3320     InitializedEntity::InitializeParameter(S.Context, Param);
3321 
3322   ExprResult Arg = E->getArg(0);
3323   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3324   if (Arg.isInvalid())
3325     return true;
3326 
3327   E->setArg(ArgIndex, Arg.get());
3328   return false;
3329 }
3330 
3331 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3332 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3333 /// type of its first argument.  The main ActOnCallExpr routines have already
3334 /// promoted the types of arguments because all of these calls are prototyped as
3335 /// void(...).
3336 ///
3337 /// This function goes through and does final semantic checking for these
3338 /// builtins,
3339 ExprResult
3340 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3341   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3342   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3343   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3344 
3345   // Ensure that we have at least one argument to do type inference from.
3346   if (TheCall->getNumArgs() < 1) {
3347     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3348       << 0 << 1 << TheCall->getNumArgs()
3349       << TheCall->getCallee()->getSourceRange();
3350     return ExprError();
3351   }
3352 
3353   // Inspect the first argument of the atomic builtin.  This should always be
3354   // a pointer type, whose element is an integral scalar or pointer type.
3355   // Because it is a pointer type, we don't have to worry about any implicit
3356   // casts here.
3357   // FIXME: We don't allow floating point scalars as input.
3358   Expr *FirstArg = TheCall->getArg(0);
3359   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3360   if (FirstArgResult.isInvalid())
3361     return ExprError();
3362   FirstArg = FirstArgResult.get();
3363   TheCall->setArg(0, FirstArg);
3364 
3365   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3366   if (!pointerType) {
3367     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3368       << FirstArg->getType() << FirstArg->getSourceRange();
3369     return ExprError();
3370   }
3371 
3372   QualType ValType = pointerType->getPointeeType();
3373   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3374       !ValType->isBlockPointerType()) {
3375     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3376       << FirstArg->getType() << FirstArg->getSourceRange();
3377     return ExprError();
3378   }
3379 
3380   switch (ValType.getObjCLifetime()) {
3381   case Qualifiers::OCL_None:
3382   case Qualifiers::OCL_ExplicitNone:
3383     // okay
3384     break;
3385 
3386   case Qualifiers::OCL_Weak:
3387   case Qualifiers::OCL_Strong:
3388   case Qualifiers::OCL_Autoreleasing:
3389     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3390       << ValType << FirstArg->getSourceRange();
3391     return ExprError();
3392   }
3393 
3394   // Strip any qualifiers off ValType.
3395   ValType = ValType.getUnqualifiedType();
3396 
3397   // The majority of builtins return a value, but a few have special return
3398   // types, so allow them to override appropriately below.
3399   QualType ResultType = ValType;
3400 
3401   // We need to figure out which concrete builtin this maps onto.  For example,
3402   // __sync_fetch_and_add with a 2 byte object turns into
3403   // __sync_fetch_and_add_2.
3404 #define BUILTIN_ROW(x) \
3405   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3406     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3407 
3408   static const unsigned BuiltinIndices[][5] = {
3409     BUILTIN_ROW(__sync_fetch_and_add),
3410     BUILTIN_ROW(__sync_fetch_and_sub),
3411     BUILTIN_ROW(__sync_fetch_and_or),
3412     BUILTIN_ROW(__sync_fetch_and_and),
3413     BUILTIN_ROW(__sync_fetch_and_xor),
3414     BUILTIN_ROW(__sync_fetch_and_nand),
3415 
3416     BUILTIN_ROW(__sync_add_and_fetch),
3417     BUILTIN_ROW(__sync_sub_and_fetch),
3418     BUILTIN_ROW(__sync_and_and_fetch),
3419     BUILTIN_ROW(__sync_or_and_fetch),
3420     BUILTIN_ROW(__sync_xor_and_fetch),
3421     BUILTIN_ROW(__sync_nand_and_fetch),
3422 
3423     BUILTIN_ROW(__sync_val_compare_and_swap),
3424     BUILTIN_ROW(__sync_bool_compare_and_swap),
3425     BUILTIN_ROW(__sync_lock_test_and_set),
3426     BUILTIN_ROW(__sync_lock_release),
3427     BUILTIN_ROW(__sync_swap)
3428   };
3429 #undef BUILTIN_ROW
3430 
3431   // Determine the index of the size.
3432   unsigned SizeIndex;
3433   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3434   case 1: SizeIndex = 0; break;
3435   case 2: SizeIndex = 1; break;
3436   case 4: SizeIndex = 2; break;
3437   case 8: SizeIndex = 3; break;
3438   case 16: SizeIndex = 4; break;
3439   default:
3440     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3441       << FirstArg->getType() << FirstArg->getSourceRange();
3442     return ExprError();
3443   }
3444 
3445   // Each of these builtins has one pointer argument, followed by some number of
3446   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3447   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3448   // as the number of fixed args.
3449   unsigned BuiltinID = FDecl->getBuiltinID();
3450   unsigned BuiltinIndex, NumFixed = 1;
3451   bool WarnAboutSemanticsChange = false;
3452   switch (BuiltinID) {
3453   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3454   case Builtin::BI__sync_fetch_and_add:
3455   case Builtin::BI__sync_fetch_and_add_1:
3456   case Builtin::BI__sync_fetch_and_add_2:
3457   case Builtin::BI__sync_fetch_and_add_4:
3458   case Builtin::BI__sync_fetch_and_add_8:
3459   case Builtin::BI__sync_fetch_and_add_16:
3460     BuiltinIndex = 0;
3461     break;
3462 
3463   case Builtin::BI__sync_fetch_and_sub:
3464   case Builtin::BI__sync_fetch_and_sub_1:
3465   case Builtin::BI__sync_fetch_and_sub_2:
3466   case Builtin::BI__sync_fetch_and_sub_4:
3467   case Builtin::BI__sync_fetch_and_sub_8:
3468   case Builtin::BI__sync_fetch_and_sub_16:
3469     BuiltinIndex = 1;
3470     break;
3471 
3472   case Builtin::BI__sync_fetch_and_or:
3473   case Builtin::BI__sync_fetch_and_or_1:
3474   case Builtin::BI__sync_fetch_and_or_2:
3475   case Builtin::BI__sync_fetch_and_or_4:
3476   case Builtin::BI__sync_fetch_and_or_8:
3477   case Builtin::BI__sync_fetch_and_or_16:
3478     BuiltinIndex = 2;
3479     break;
3480 
3481   case Builtin::BI__sync_fetch_and_and:
3482   case Builtin::BI__sync_fetch_and_and_1:
3483   case Builtin::BI__sync_fetch_and_and_2:
3484   case Builtin::BI__sync_fetch_and_and_4:
3485   case Builtin::BI__sync_fetch_and_and_8:
3486   case Builtin::BI__sync_fetch_and_and_16:
3487     BuiltinIndex = 3;
3488     break;
3489 
3490   case Builtin::BI__sync_fetch_and_xor:
3491   case Builtin::BI__sync_fetch_and_xor_1:
3492   case Builtin::BI__sync_fetch_and_xor_2:
3493   case Builtin::BI__sync_fetch_and_xor_4:
3494   case Builtin::BI__sync_fetch_and_xor_8:
3495   case Builtin::BI__sync_fetch_and_xor_16:
3496     BuiltinIndex = 4;
3497     break;
3498 
3499   case Builtin::BI__sync_fetch_and_nand:
3500   case Builtin::BI__sync_fetch_and_nand_1:
3501   case Builtin::BI__sync_fetch_and_nand_2:
3502   case Builtin::BI__sync_fetch_and_nand_4:
3503   case Builtin::BI__sync_fetch_and_nand_8:
3504   case Builtin::BI__sync_fetch_and_nand_16:
3505     BuiltinIndex = 5;
3506     WarnAboutSemanticsChange = true;
3507     break;
3508 
3509   case Builtin::BI__sync_add_and_fetch:
3510   case Builtin::BI__sync_add_and_fetch_1:
3511   case Builtin::BI__sync_add_and_fetch_2:
3512   case Builtin::BI__sync_add_and_fetch_4:
3513   case Builtin::BI__sync_add_and_fetch_8:
3514   case Builtin::BI__sync_add_and_fetch_16:
3515     BuiltinIndex = 6;
3516     break;
3517 
3518   case Builtin::BI__sync_sub_and_fetch:
3519   case Builtin::BI__sync_sub_and_fetch_1:
3520   case Builtin::BI__sync_sub_and_fetch_2:
3521   case Builtin::BI__sync_sub_and_fetch_4:
3522   case Builtin::BI__sync_sub_and_fetch_8:
3523   case Builtin::BI__sync_sub_and_fetch_16:
3524     BuiltinIndex = 7;
3525     break;
3526 
3527   case Builtin::BI__sync_and_and_fetch:
3528   case Builtin::BI__sync_and_and_fetch_1:
3529   case Builtin::BI__sync_and_and_fetch_2:
3530   case Builtin::BI__sync_and_and_fetch_4:
3531   case Builtin::BI__sync_and_and_fetch_8:
3532   case Builtin::BI__sync_and_and_fetch_16:
3533     BuiltinIndex = 8;
3534     break;
3535 
3536   case Builtin::BI__sync_or_and_fetch:
3537   case Builtin::BI__sync_or_and_fetch_1:
3538   case Builtin::BI__sync_or_and_fetch_2:
3539   case Builtin::BI__sync_or_and_fetch_4:
3540   case Builtin::BI__sync_or_and_fetch_8:
3541   case Builtin::BI__sync_or_and_fetch_16:
3542     BuiltinIndex = 9;
3543     break;
3544 
3545   case Builtin::BI__sync_xor_and_fetch:
3546   case Builtin::BI__sync_xor_and_fetch_1:
3547   case Builtin::BI__sync_xor_and_fetch_2:
3548   case Builtin::BI__sync_xor_and_fetch_4:
3549   case Builtin::BI__sync_xor_and_fetch_8:
3550   case Builtin::BI__sync_xor_and_fetch_16:
3551     BuiltinIndex = 10;
3552     break;
3553 
3554   case Builtin::BI__sync_nand_and_fetch:
3555   case Builtin::BI__sync_nand_and_fetch_1:
3556   case Builtin::BI__sync_nand_and_fetch_2:
3557   case Builtin::BI__sync_nand_and_fetch_4:
3558   case Builtin::BI__sync_nand_and_fetch_8:
3559   case Builtin::BI__sync_nand_and_fetch_16:
3560     BuiltinIndex = 11;
3561     WarnAboutSemanticsChange = true;
3562     break;
3563 
3564   case Builtin::BI__sync_val_compare_and_swap:
3565   case Builtin::BI__sync_val_compare_and_swap_1:
3566   case Builtin::BI__sync_val_compare_and_swap_2:
3567   case Builtin::BI__sync_val_compare_and_swap_4:
3568   case Builtin::BI__sync_val_compare_and_swap_8:
3569   case Builtin::BI__sync_val_compare_and_swap_16:
3570     BuiltinIndex = 12;
3571     NumFixed = 2;
3572     break;
3573 
3574   case Builtin::BI__sync_bool_compare_and_swap:
3575   case Builtin::BI__sync_bool_compare_and_swap_1:
3576   case Builtin::BI__sync_bool_compare_and_swap_2:
3577   case Builtin::BI__sync_bool_compare_and_swap_4:
3578   case Builtin::BI__sync_bool_compare_and_swap_8:
3579   case Builtin::BI__sync_bool_compare_and_swap_16:
3580     BuiltinIndex = 13;
3581     NumFixed = 2;
3582     ResultType = Context.BoolTy;
3583     break;
3584 
3585   case Builtin::BI__sync_lock_test_and_set:
3586   case Builtin::BI__sync_lock_test_and_set_1:
3587   case Builtin::BI__sync_lock_test_and_set_2:
3588   case Builtin::BI__sync_lock_test_and_set_4:
3589   case Builtin::BI__sync_lock_test_and_set_8:
3590   case Builtin::BI__sync_lock_test_and_set_16:
3591     BuiltinIndex = 14;
3592     break;
3593 
3594   case Builtin::BI__sync_lock_release:
3595   case Builtin::BI__sync_lock_release_1:
3596   case Builtin::BI__sync_lock_release_2:
3597   case Builtin::BI__sync_lock_release_4:
3598   case Builtin::BI__sync_lock_release_8:
3599   case Builtin::BI__sync_lock_release_16:
3600     BuiltinIndex = 15;
3601     NumFixed = 0;
3602     ResultType = Context.VoidTy;
3603     break;
3604 
3605   case Builtin::BI__sync_swap:
3606   case Builtin::BI__sync_swap_1:
3607   case Builtin::BI__sync_swap_2:
3608   case Builtin::BI__sync_swap_4:
3609   case Builtin::BI__sync_swap_8:
3610   case Builtin::BI__sync_swap_16:
3611     BuiltinIndex = 16;
3612     break;
3613   }
3614 
3615   // Now that we know how many fixed arguments we expect, first check that we
3616   // have at least that many.
3617   if (TheCall->getNumArgs() < 1+NumFixed) {
3618     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3619       << 0 << 1+NumFixed << TheCall->getNumArgs()
3620       << TheCall->getCallee()->getSourceRange();
3621     return ExprError();
3622   }
3623 
3624   if (WarnAboutSemanticsChange) {
3625     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3626       << TheCall->getCallee()->getSourceRange();
3627   }
3628 
3629   // Get the decl for the concrete builtin from this, we can tell what the
3630   // concrete integer type we should convert to is.
3631   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3632   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3633   FunctionDecl *NewBuiltinDecl;
3634   if (NewBuiltinID == BuiltinID)
3635     NewBuiltinDecl = FDecl;
3636   else {
3637     // Perform builtin lookup to avoid redeclaring it.
3638     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3639     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3640     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3641     assert(Res.getFoundDecl());
3642     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3643     if (!NewBuiltinDecl)
3644       return ExprError();
3645   }
3646 
3647   // The first argument --- the pointer --- has a fixed type; we
3648   // deduce the types of the rest of the arguments accordingly.  Walk
3649   // the remaining arguments, converting them to the deduced value type.
3650   for (unsigned i = 0; i != NumFixed; ++i) {
3651     ExprResult Arg = TheCall->getArg(i+1);
3652 
3653     // GCC does an implicit conversion to the pointer or integer ValType.  This
3654     // can fail in some cases (1i -> int**), check for this error case now.
3655     // Initialize the argument.
3656     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3657                                                    ValType, /*consume*/ false);
3658     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3659     if (Arg.isInvalid())
3660       return ExprError();
3661 
3662     // Okay, we have something that *can* be converted to the right type.  Check
3663     // to see if there is a potentially weird extension going on here.  This can
3664     // happen when you do an atomic operation on something like an char* and
3665     // pass in 42.  The 42 gets converted to char.  This is even more strange
3666     // for things like 45.123 -> char, etc.
3667     // FIXME: Do this check.
3668     TheCall->setArg(i+1, Arg.get());
3669   }
3670 
3671   ASTContext& Context = this->getASTContext();
3672 
3673   // Create a new DeclRefExpr to refer to the new decl.
3674   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3675       Context,
3676       DRE->getQualifierLoc(),
3677       SourceLocation(),
3678       NewBuiltinDecl,
3679       /*enclosing*/ false,
3680       DRE->getLocation(),
3681       Context.BuiltinFnTy,
3682       DRE->getValueKind());
3683 
3684   // Set the callee in the CallExpr.
3685   // FIXME: This loses syntactic information.
3686   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3687   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3688                                               CK_BuiltinFnToFnPtr);
3689   TheCall->setCallee(PromotedCall.get());
3690 
3691   // Change the result type of the call to match the original value type. This
3692   // is arbitrary, but the codegen for these builtins ins design to handle it
3693   // gracefully.
3694   TheCall->setType(ResultType);
3695 
3696   return TheCallResult;
3697 }
3698 
3699 /// SemaBuiltinNontemporalOverloaded - We have a call to
3700 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3701 /// overloaded function based on the pointer type of its last argument.
3702 ///
3703 /// This function goes through and does final semantic checking for these
3704 /// builtins.
3705 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3706   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3707   DeclRefExpr *DRE =
3708       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3709   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3710   unsigned BuiltinID = FDecl->getBuiltinID();
3711   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3712           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3713          "Unexpected nontemporal load/store builtin!");
3714   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3715   unsigned numArgs = isStore ? 2 : 1;
3716 
3717   // Ensure that we have the proper number of arguments.
3718   if (checkArgCount(*this, TheCall, numArgs))
3719     return ExprError();
3720 
3721   // Inspect the last argument of the nontemporal builtin.  This should always
3722   // be a pointer type, from which we imply the type of the memory access.
3723   // Because it is a pointer type, we don't have to worry about any implicit
3724   // casts here.
3725   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3726   ExprResult PointerArgResult =
3727       DefaultFunctionArrayLvalueConversion(PointerArg);
3728 
3729   if (PointerArgResult.isInvalid())
3730     return ExprError();
3731   PointerArg = PointerArgResult.get();
3732   TheCall->setArg(numArgs - 1, PointerArg);
3733 
3734   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3735   if (!pointerType) {
3736     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3737         << PointerArg->getType() << PointerArg->getSourceRange();
3738     return ExprError();
3739   }
3740 
3741   QualType ValType = pointerType->getPointeeType();
3742 
3743   // Strip any qualifiers off ValType.
3744   ValType = ValType.getUnqualifiedType();
3745   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3746       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3747       !ValType->isVectorType()) {
3748     Diag(DRE->getLocStart(),
3749          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3750         << PointerArg->getType() << PointerArg->getSourceRange();
3751     return ExprError();
3752   }
3753 
3754   if (!isStore) {
3755     TheCall->setType(ValType);
3756     return TheCallResult;
3757   }
3758 
3759   ExprResult ValArg = TheCall->getArg(0);
3760   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3761       Context, ValType, /*consume*/ false);
3762   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3763   if (ValArg.isInvalid())
3764     return ExprError();
3765 
3766   TheCall->setArg(0, ValArg.get());
3767   TheCall->setType(Context.VoidTy);
3768   return TheCallResult;
3769 }
3770 
3771 /// CheckObjCString - Checks that the argument to the builtin
3772 /// CFString constructor is correct
3773 /// Note: It might also make sense to do the UTF-16 conversion here (would
3774 /// simplify the backend).
3775 bool Sema::CheckObjCString(Expr *Arg) {
3776   Arg = Arg->IgnoreParenCasts();
3777   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3778 
3779   if (!Literal || !Literal->isAscii()) {
3780     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3781       << Arg->getSourceRange();
3782     return true;
3783   }
3784 
3785   if (Literal->containsNonAsciiOrNull()) {
3786     StringRef String = Literal->getString();
3787     unsigned NumBytes = String.size();
3788     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3789     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3790     llvm::UTF16 *ToPtr = &ToBuf[0];
3791 
3792     llvm::ConversionResult Result =
3793         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3794                                  ToPtr + NumBytes, llvm::strictConversion);
3795     // Check for conversion failure.
3796     if (Result != llvm::conversionOK)
3797       Diag(Arg->getLocStart(),
3798            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3799   }
3800   return false;
3801 }
3802 
3803 /// CheckObjCString - Checks that the format string argument to the os_log()
3804 /// and os_trace() functions is correct, and converts it to const char *.
3805 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3806   Arg = Arg->IgnoreParenCasts();
3807   auto *Literal = dyn_cast<StringLiteral>(Arg);
3808   if (!Literal) {
3809     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3810       Literal = ObjcLiteral->getString();
3811     }
3812   }
3813 
3814   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3815     return ExprError(
3816         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3817         << Arg->getSourceRange());
3818   }
3819 
3820   ExprResult Result(Literal);
3821   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3822   InitializedEntity Entity =
3823       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3824   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3825   return Result;
3826 }
3827 
3828 /// Check that the user is calling the appropriate va_start builtin for the
3829 /// target and calling convention.
3830 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3831   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3832   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3833   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3834   bool IsWindows = TT.isOSWindows();
3835   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3836   if (IsX64 || IsAArch64) {
3837     CallingConv CC = CC_C;
3838     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3839       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3840     if (IsMSVAStart) {
3841       // Don't allow this in System V ABI functions.
3842       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3843         return S.Diag(Fn->getLocStart(),
3844                       diag::err_ms_va_start_used_in_sysv_function);
3845     } else {
3846       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3847       // On x64 Windows, don't allow this in System V ABI functions.
3848       // (Yes, that means there's no corresponding way to support variadic
3849       // System V ABI functions on Windows.)
3850       if ((IsWindows && CC == CC_X86_64SysV) ||
3851           (!IsWindows && CC == CC_Win64))
3852         return S.Diag(Fn->getLocStart(),
3853                       diag::err_va_start_used_in_wrong_abi_function)
3854                << !IsWindows;
3855     }
3856     return false;
3857   }
3858 
3859   if (IsMSVAStart)
3860     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3861   return false;
3862 }
3863 
3864 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3865                                              ParmVarDecl **LastParam = nullptr) {
3866   // Determine whether the current function, block, or obj-c method is variadic
3867   // and get its parameter list.
3868   bool IsVariadic = false;
3869   ArrayRef<ParmVarDecl *> Params;
3870   DeclContext *Caller = S.CurContext;
3871   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3872     IsVariadic = Block->isVariadic();
3873     Params = Block->parameters();
3874   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3875     IsVariadic = FD->isVariadic();
3876     Params = FD->parameters();
3877   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3878     IsVariadic = MD->isVariadic();
3879     // FIXME: This isn't correct for methods (results in bogus warning).
3880     Params = MD->parameters();
3881   } else if (isa<CapturedDecl>(Caller)) {
3882     // We don't support va_start in a CapturedDecl.
3883     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3884     return true;
3885   } else {
3886     // This must be some other declcontext that parses exprs.
3887     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3888     return true;
3889   }
3890 
3891   if (!IsVariadic) {
3892     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3893     return true;
3894   }
3895 
3896   if (LastParam)
3897     *LastParam = Params.empty() ? nullptr : Params.back();
3898 
3899   return false;
3900 }
3901 
3902 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3903 /// for validity.  Emit an error and return true on failure; return false
3904 /// on success.
3905 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3906   Expr *Fn = TheCall->getCallee();
3907 
3908   if (checkVAStartABI(*this, BuiltinID, Fn))
3909     return true;
3910 
3911   if (TheCall->getNumArgs() > 2) {
3912     Diag(TheCall->getArg(2)->getLocStart(),
3913          diag::err_typecheck_call_too_many_args)
3914       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3915       << Fn->getSourceRange()
3916       << SourceRange(TheCall->getArg(2)->getLocStart(),
3917                      (*(TheCall->arg_end()-1))->getLocEnd());
3918     return true;
3919   }
3920 
3921   if (TheCall->getNumArgs() < 2) {
3922     return Diag(TheCall->getLocEnd(),
3923       diag::err_typecheck_call_too_few_args_at_least)
3924       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3925   }
3926 
3927   // Type-check the first argument normally.
3928   if (checkBuiltinArgument(*this, TheCall, 0))
3929     return true;
3930 
3931   // Check that the current function is variadic, and get its last parameter.
3932   ParmVarDecl *LastParam;
3933   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3934     return true;
3935 
3936   // Verify that the second argument to the builtin is the last argument of the
3937   // current function or method.
3938   bool SecondArgIsLastNamedArgument = false;
3939   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3940 
3941   // These are valid if SecondArgIsLastNamedArgument is false after the next
3942   // block.
3943   QualType Type;
3944   SourceLocation ParamLoc;
3945   bool IsCRegister = false;
3946 
3947   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3948     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3949       SecondArgIsLastNamedArgument = PV == LastParam;
3950 
3951       Type = PV->getType();
3952       ParamLoc = PV->getLocation();
3953       IsCRegister =
3954           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3955     }
3956   }
3957 
3958   if (!SecondArgIsLastNamedArgument)
3959     Diag(TheCall->getArg(1)->getLocStart(),
3960          diag::warn_second_arg_of_va_start_not_last_named_param);
3961   else if (IsCRegister || Type->isReferenceType() ||
3962            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3963              // Promotable integers are UB, but enumerations need a bit of
3964              // extra checking to see what their promotable type actually is.
3965              if (!Type->isPromotableIntegerType())
3966                return false;
3967              if (!Type->isEnumeralType())
3968                return true;
3969              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3970              return !(ED &&
3971                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3972            }()) {
3973     unsigned Reason = 0;
3974     if (Type->isReferenceType())  Reason = 1;
3975     else if (IsCRegister)         Reason = 2;
3976     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3977     Diag(ParamLoc, diag::note_parameter_type) << Type;
3978   }
3979 
3980   TheCall->setType(Context.VoidTy);
3981   return false;
3982 }
3983 
3984 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3985   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3986   //                 const char *named_addr);
3987 
3988   Expr *Func = Call->getCallee();
3989 
3990   if (Call->getNumArgs() < 3)
3991     return Diag(Call->getLocEnd(),
3992                 diag::err_typecheck_call_too_few_args_at_least)
3993            << 0 /*function call*/ << 3 << Call->getNumArgs();
3994 
3995   // Type-check the first argument normally.
3996   if (checkBuiltinArgument(*this, Call, 0))
3997     return true;
3998 
3999   // Check that the current function is variadic.
4000   if (checkVAStartIsInVariadicFunction(*this, Func))
4001     return true;
4002 
4003   // __va_start on Windows does not validate the parameter qualifiers
4004 
4005   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
4006   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
4007 
4008   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
4009   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
4010 
4011   const QualType &ConstCharPtrTy =
4012       Context.getPointerType(Context.CharTy.withConst());
4013   if (!Arg1Ty->isPointerType() ||
4014       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
4015     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
4016         << Arg1->getType() << ConstCharPtrTy
4017         << 1 /* different class */
4018         << 0 /* qualifier difference */
4019         << 3 /* parameter mismatch */
4020         << 2 << Arg1->getType() << ConstCharPtrTy;
4021 
4022   const QualType SizeTy = Context.getSizeType();
4023   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
4024     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
4025         << Arg2->getType() << SizeTy
4026         << 1 /* different class */
4027         << 0 /* qualifier difference */
4028         << 3 /* parameter mismatch */
4029         << 3 << Arg2->getType() << SizeTy;
4030 
4031   return false;
4032 }
4033 
4034 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
4035 /// friends.  This is declared to take (...), so we have to check everything.
4036 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
4037   if (TheCall->getNumArgs() < 2)
4038     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4039       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
4040   if (TheCall->getNumArgs() > 2)
4041     return Diag(TheCall->getArg(2)->getLocStart(),
4042                 diag::err_typecheck_call_too_many_args)
4043       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4044       << SourceRange(TheCall->getArg(2)->getLocStart(),
4045                      (*(TheCall->arg_end()-1))->getLocEnd());
4046 
4047   ExprResult OrigArg0 = TheCall->getArg(0);
4048   ExprResult OrigArg1 = TheCall->getArg(1);
4049 
4050   // Do standard promotions between the two arguments, returning their common
4051   // type.
4052   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4053   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4054     return true;
4055 
4056   // Make sure any conversions are pushed back into the call; this is
4057   // type safe since unordered compare builtins are declared as "_Bool
4058   // foo(...)".
4059   TheCall->setArg(0, OrigArg0.get());
4060   TheCall->setArg(1, OrigArg1.get());
4061 
4062   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4063     return false;
4064 
4065   // If the common type isn't a real floating type, then the arguments were
4066   // invalid for this operation.
4067   if (Res.isNull() || !Res->isRealFloatingType())
4068     return Diag(OrigArg0.get()->getLocStart(),
4069                 diag::err_typecheck_call_invalid_ordered_compare)
4070       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4071       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4072 
4073   return false;
4074 }
4075 
4076 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4077 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4078 /// to check everything. We expect the last argument to be a floating point
4079 /// value.
4080 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4081   if (TheCall->getNumArgs() < NumArgs)
4082     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4083       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4084   if (TheCall->getNumArgs() > NumArgs)
4085     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4086                 diag::err_typecheck_call_too_many_args)
4087       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4088       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4089                      (*(TheCall->arg_end()-1))->getLocEnd());
4090 
4091   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4092 
4093   if (OrigArg->isTypeDependent())
4094     return false;
4095 
4096   // This operation requires a non-_Complex floating-point number.
4097   if (!OrigArg->getType()->isRealFloatingType())
4098     return Diag(OrigArg->getLocStart(),
4099                 diag::err_typecheck_call_invalid_unary_fp)
4100       << OrigArg->getType() << OrigArg->getSourceRange();
4101 
4102   // If this is an implicit conversion from float -> float or double, remove it.
4103   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4104     // Only remove standard FloatCasts, leaving other casts inplace
4105     if (Cast->getCastKind() == CK_FloatingCast) {
4106       Expr *CastArg = Cast->getSubExpr();
4107       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4108           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4109                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4110                "promotion from float to either float or double is the only expected cast here");
4111         Cast->setSubExpr(nullptr);
4112         TheCall->setArg(NumArgs-1, CastArg);
4113       }
4114     }
4115   }
4116 
4117   return false;
4118 }
4119 
4120 // Customized Sema Checking for VSX builtins that have the following signature:
4121 // vector [...] builtinName(vector [...], vector [...], const int);
4122 // Which takes the same type of vectors (any legal vector type) for the first
4123 // two arguments and takes compile time constant for the third argument.
4124 // Example builtins are :
4125 // vector double vec_xxpermdi(vector double, vector double, int);
4126 // vector short vec_xxsldwi(vector short, vector short, int);
4127 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4128   unsigned ExpectedNumArgs = 3;
4129   if (TheCall->getNumArgs() < ExpectedNumArgs)
4130     return Diag(TheCall->getLocEnd(),
4131                 diag::err_typecheck_call_too_few_args_at_least)
4132            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4133            << TheCall->getSourceRange();
4134 
4135   if (TheCall->getNumArgs() > ExpectedNumArgs)
4136     return Diag(TheCall->getLocEnd(),
4137                 diag::err_typecheck_call_too_many_args_at_most)
4138            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4139            << TheCall->getSourceRange();
4140 
4141   // Check the third argument is a compile time constant
4142   llvm::APSInt Value;
4143   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4144     return Diag(TheCall->getLocStart(),
4145                 diag::err_vsx_builtin_nonconstant_argument)
4146            << 3 /* argument index */ << TheCall->getDirectCallee()
4147            << SourceRange(TheCall->getArg(2)->getLocStart(),
4148                           TheCall->getArg(2)->getLocEnd());
4149 
4150   QualType Arg1Ty = TheCall->getArg(0)->getType();
4151   QualType Arg2Ty = TheCall->getArg(1)->getType();
4152 
4153   // Check the type of argument 1 and argument 2 are vectors.
4154   SourceLocation BuiltinLoc = TheCall->getLocStart();
4155   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4156       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4157     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4158            << TheCall->getDirectCallee()
4159            << SourceRange(TheCall->getArg(0)->getLocStart(),
4160                           TheCall->getArg(1)->getLocEnd());
4161   }
4162 
4163   // Check the first two arguments are the same type.
4164   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4165     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4166            << TheCall->getDirectCallee()
4167            << SourceRange(TheCall->getArg(0)->getLocStart(),
4168                           TheCall->getArg(1)->getLocEnd());
4169   }
4170 
4171   // When default clang type checking is turned off and the customized type
4172   // checking is used, the returning type of the function must be explicitly
4173   // set. Otherwise it is _Bool by default.
4174   TheCall->setType(Arg1Ty);
4175 
4176   return false;
4177 }
4178 
4179 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4180 // This is declared to take (...), so we have to check everything.
4181 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4182   if (TheCall->getNumArgs() < 2)
4183     return ExprError(Diag(TheCall->getLocEnd(),
4184                           diag::err_typecheck_call_too_few_args_at_least)
4185                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4186                      << TheCall->getSourceRange());
4187 
4188   // Determine which of the following types of shufflevector we're checking:
4189   // 1) unary, vector mask: (lhs, mask)
4190   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4191   QualType resType = TheCall->getArg(0)->getType();
4192   unsigned numElements = 0;
4193 
4194   if (!TheCall->getArg(0)->isTypeDependent() &&
4195       !TheCall->getArg(1)->isTypeDependent()) {
4196     QualType LHSType = TheCall->getArg(0)->getType();
4197     QualType RHSType = TheCall->getArg(1)->getType();
4198 
4199     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4200       return ExprError(Diag(TheCall->getLocStart(),
4201                             diag::err_vec_builtin_non_vector)
4202                        << TheCall->getDirectCallee()
4203                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4204                                       TheCall->getArg(1)->getLocEnd()));
4205 
4206     numElements = LHSType->getAs<VectorType>()->getNumElements();
4207     unsigned numResElements = TheCall->getNumArgs() - 2;
4208 
4209     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4210     // with mask.  If so, verify that RHS is an integer vector type with the
4211     // same number of elts as lhs.
4212     if (TheCall->getNumArgs() == 2) {
4213       if (!RHSType->hasIntegerRepresentation() ||
4214           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4215         return ExprError(Diag(TheCall->getLocStart(),
4216                               diag::err_vec_builtin_incompatible_vector)
4217                          << TheCall->getDirectCallee()
4218                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4219                                         TheCall->getArg(1)->getLocEnd()));
4220     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4221       return ExprError(Diag(TheCall->getLocStart(),
4222                             diag::err_vec_builtin_incompatible_vector)
4223                        << TheCall->getDirectCallee()
4224                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4225                                       TheCall->getArg(1)->getLocEnd()));
4226     } else if (numElements != numResElements) {
4227       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4228       resType = Context.getVectorType(eltType, numResElements,
4229                                       VectorType::GenericVector);
4230     }
4231   }
4232 
4233   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4234     if (TheCall->getArg(i)->isTypeDependent() ||
4235         TheCall->getArg(i)->isValueDependent())
4236       continue;
4237 
4238     llvm::APSInt Result(32);
4239     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4240       return ExprError(Diag(TheCall->getLocStart(),
4241                             diag::err_shufflevector_nonconstant_argument)
4242                        << TheCall->getArg(i)->getSourceRange());
4243 
4244     // Allow -1 which will be translated to undef in the IR.
4245     if (Result.isSigned() && Result.isAllOnesValue())
4246       continue;
4247 
4248     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4249       return ExprError(Diag(TheCall->getLocStart(),
4250                             diag::err_shufflevector_argument_too_large)
4251                        << TheCall->getArg(i)->getSourceRange());
4252   }
4253 
4254   SmallVector<Expr*, 32> exprs;
4255 
4256   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4257     exprs.push_back(TheCall->getArg(i));
4258     TheCall->setArg(i, nullptr);
4259   }
4260 
4261   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4262                                          TheCall->getCallee()->getLocStart(),
4263                                          TheCall->getRParenLoc());
4264 }
4265 
4266 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4267 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4268                                        SourceLocation BuiltinLoc,
4269                                        SourceLocation RParenLoc) {
4270   ExprValueKind VK = VK_RValue;
4271   ExprObjectKind OK = OK_Ordinary;
4272   QualType DstTy = TInfo->getType();
4273   QualType SrcTy = E->getType();
4274 
4275   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4276     return ExprError(Diag(BuiltinLoc,
4277                           diag::err_convertvector_non_vector)
4278                      << E->getSourceRange());
4279   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4280     return ExprError(Diag(BuiltinLoc,
4281                           diag::err_convertvector_non_vector_type));
4282 
4283   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4284     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4285     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4286     if (SrcElts != DstElts)
4287       return ExprError(Diag(BuiltinLoc,
4288                             diag::err_convertvector_incompatible_vector)
4289                        << E->getSourceRange());
4290   }
4291 
4292   return new (Context)
4293       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4294 }
4295 
4296 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4297 // This is declared to take (const void*, ...) and can take two
4298 // optional constant int args.
4299 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4300   unsigned NumArgs = TheCall->getNumArgs();
4301 
4302   if (NumArgs > 3)
4303     return Diag(TheCall->getLocEnd(),
4304              diag::err_typecheck_call_too_many_args_at_most)
4305              << 0 /*function call*/ << 3 << NumArgs
4306              << TheCall->getSourceRange();
4307 
4308   // Argument 0 is checked for us and the remaining arguments must be
4309   // constant integers.
4310   for (unsigned i = 1; i != NumArgs; ++i)
4311     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4312       return true;
4313 
4314   return false;
4315 }
4316 
4317 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4318 // __assume does not evaluate its arguments, and should warn if its argument
4319 // has side effects.
4320 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4321   Expr *Arg = TheCall->getArg(0);
4322   if (Arg->isInstantiationDependent()) return false;
4323 
4324   if (Arg->HasSideEffects(Context))
4325     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4326       << Arg->getSourceRange()
4327       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4328 
4329   return false;
4330 }
4331 
4332 /// Handle __builtin_alloca_with_align. This is declared
4333 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4334 /// than 8.
4335 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4336   // The alignment must be a constant integer.
4337   Expr *Arg = TheCall->getArg(1);
4338 
4339   // We can't check the value of a dependent argument.
4340   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4341     if (const auto *UE =
4342             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4343       if (UE->getKind() == UETT_AlignOf)
4344         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4345           << Arg->getSourceRange();
4346 
4347     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4348 
4349     if (!Result.isPowerOf2())
4350       return Diag(TheCall->getLocStart(),
4351                   diag::err_alignment_not_power_of_two)
4352            << Arg->getSourceRange();
4353 
4354     if (Result < Context.getCharWidth())
4355       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4356            << (unsigned)Context.getCharWidth()
4357            << Arg->getSourceRange();
4358 
4359     if (Result > std::numeric_limits<int32_t>::max())
4360       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4361            << std::numeric_limits<int32_t>::max()
4362            << Arg->getSourceRange();
4363   }
4364 
4365   return false;
4366 }
4367 
4368 /// Handle __builtin_assume_aligned. This is declared
4369 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4370 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4371   unsigned NumArgs = TheCall->getNumArgs();
4372 
4373   if (NumArgs > 3)
4374     return Diag(TheCall->getLocEnd(),
4375              diag::err_typecheck_call_too_many_args_at_most)
4376              << 0 /*function call*/ << 3 << NumArgs
4377              << TheCall->getSourceRange();
4378 
4379   // The alignment must be a constant integer.
4380   Expr *Arg = TheCall->getArg(1);
4381 
4382   // We can't check the value of a dependent argument.
4383   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4384     llvm::APSInt Result;
4385     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4386       return true;
4387 
4388     if (!Result.isPowerOf2())
4389       return Diag(TheCall->getLocStart(),
4390                   diag::err_alignment_not_power_of_two)
4391            << Arg->getSourceRange();
4392   }
4393 
4394   if (NumArgs > 2) {
4395     ExprResult Arg(TheCall->getArg(2));
4396     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4397       Context.getSizeType(), false);
4398     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4399     if (Arg.isInvalid()) return true;
4400     TheCall->setArg(2, Arg.get());
4401   }
4402 
4403   return false;
4404 }
4405 
4406 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4407   unsigned BuiltinID =
4408       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4409   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4410 
4411   unsigned NumArgs = TheCall->getNumArgs();
4412   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4413   if (NumArgs < NumRequiredArgs) {
4414     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4415            << 0 /* function call */ << NumRequiredArgs << NumArgs
4416            << TheCall->getSourceRange();
4417   }
4418   if (NumArgs >= NumRequiredArgs + 0x100) {
4419     return Diag(TheCall->getLocEnd(),
4420                 diag::err_typecheck_call_too_many_args_at_most)
4421            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4422            << TheCall->getSourceRange();
4423   }
4424   unsigned i = 0;
4425 
4426   // For formatting call, check buffer arg.
4427   if (!IsSizeCall) {
4428     ExprResult Arg(TheCall->getArg(i));
4429     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4430         Context, Context.VoidPtrTy, false);
4431     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4432     if (Arg.isInvalid())
4433       return true;
4434     TheCall->setArg(i, Arg.get());
4435     i++;
4436   }
4437 
4438   // Check string literal arg.
4439   unsigned FormatIdx = i;
4440   {
4441     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4442     if (Arg.isInvalid())
4443       return true;
4444     TheCall->setArg(i, Arg.get());
4445     i++;
4446   }
4447 
4448   // Make sure variadic args are scalar.
4449   unsigned FirstDataArg = i;
4450   while (i < NumArgs) {
4451     ExprResult Arg = DefaultVariadicArgumentPromotion(
4452         TheCall->getArg(i), VariadicFunction, nullptr);
4453     if (Arg.isInvalid())
4454       return true;
4455     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4456     if (ArgSize.getQuantity() >= 0x100) {
4457       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4458              << i << (int)ArgSize.getQuantity() << 0xff
4459              << TheCall->getSourceRange();
4460     }
4461     TheCall->setArg(i, Arg.get());
4462     i++;
4463   }
4464 
4465   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4466   // call to avoid duplicate diagnostics.
4467   if (!IsSizeCall) {
4468     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4469     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4470     bool Success = CheckFormatArguments(
4471         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4472         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4473         CheckedVarArgs);
4474     if (!Success)
4475       return true;
4476   }
4477 
4478   if (IsSizeCall) {
4479     TheCall->setType(Context.getSizeType());
4480   } else {
4481     TheCall->setType(Context.VoidPtrTy);
4482   }
4483   return false;
4484 }
4485 
4486 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4487 /// TheCall is a constant expression.
4488 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4489                                   llvm::APSInt &Result) {
4490   Expr *Arg = TheCall->getArg(ArgNum);
4491   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4492   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4493 
4494   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4495 
4496   if (!Arg->isIntegerConstantExpr(Result, Context))
4497     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4498                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4499 
4500   return false;
4501 }
4502 
4503 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4504 /// TheCall is a constant expression in the range [Low, High].
4505 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4506                                        int Low, int High) {
4507   llvm::APSInt Result;
4508 
4509   // We can't check the value of a dependent argument.
4510   Expr *Arg = TheCall->getArg(ArgNum);
4511   if (Arg->isTypeDependent() || Arg->isValueDependent())
4512     return false;
4513 
4514   // Check constant-ness first.
4515   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4516     return true;
4517 
4518   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4519     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4520       << Low << High << Arg->getSourceRange();
4521 
4522   return false;
4523 }
4524 
4525 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4526 /// TheCall is a constant expression is a multiple of Num..
4527 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4528                                           unsigned Num) {
4529   llvm::APSInt Result;
4530 
4531   // We can't check the value of a dependent argument.
4532   Expr *Arg = TheCall->getArg(ArgNum);
4533   if (Arg->isTypeDependent() || Arg->isValueDependent())
4534     return false;
4535 
4536   // Check constant-ness first.
4537   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4538     return true;
4539 
4540   if (Result.getSExtValue() % Num != 0)
4541     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4542       << Num << Arg->getSourceRange();
4543 
4544   return false;
4545 }
4546 
4547 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4548 /// TheCall is an ARM/AArch64 special register string literal.
4549 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4550                                     int ArgNum, unsigned ExpectedFieldNum,
4551                                     bool AllowName) {
4552   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4553                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4554                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4555                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4556                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4557                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4558   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4559                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4560                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4561                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4562                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4563                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4564   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4565 
4566   // We can't check the value of a dependent argument.
4567   Expr *Arg = TheCall->getArg(ArgNum);
4568   if (Arg->isTypeDependent() || Arg->isValueDependent())
4569     return false;
4570 
4571   // Check if the argument is a string literal.
4572   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4573     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4574            << Arg->getSourceRange();
4575 
4576   // Check the type of special register given.
4577   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4578   SmallVector<StringRef, 6> Fields;
4579   Reg.split(Fields, ":");
4580 
4581   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4582     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4583            << Arg->getSourceRange();
4584 
4585   // If the string is the name of a register then we cannot check that it is
4586   // valid here but if the string is of one the forms described in ACLE then we
4587   // can check that the supplied fields are integers and within the valid
4588   // ranges.
4589   if (Fields.size() > 1) {
4590     bool FiveFields = Fields.size() == 5;
4591 
4592     bool ValidString = true;
4593     if (IsARMBuiltin) {
4594       ValidString &= Fields[0].startswith_lower("cp") ||
4595                      Fields[0].startswith_lower("p");
4596       if (ValidString)
4597         Fields[0] =
4598           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4599 
4600       ValidString &= Fields[2].startswith_lower("c");
4601       if (ValidString)
4602         Fields[2] = Fields[2].drop_front(1);
4603 
4604       if (FiveFields) {
4605         ValidString &= Fields[3].startswith_lower("c");
4606         if (ValidString)
4607           Fields[3] = Fields[3].drop_front(1);
4608       }
4609     }
4610 
4611     SmallVector<int, 5> Ranges;
4612     if (FiveFields)
4613       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4614     else
4615       Ranges.append({15, 7, 15});
4616 
4617     for (unsigned i=0; i<Fields.size(); ++i) {
4618       int IntField;
4619       ValidString &= !Fields[i].getAsInteger(10, IntField);
4620       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4621     }
4622 
4623     if (!ValidString)
4624       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4625              << Arg->getSourceRange();
4626   } else if (IsAArch64Builtin && Fields.size() == 1) {
4627     // If the register name is one of those that appear in the condition below
4628     // and the special register builtin being used is one of the write builtins,
4629     // then we require that the argument provided for writing to the register
4630     // is an integer constant expression. This is because it will be lowered to
4631     // an MSR (immediate) instruction, so we need to know the immediate at
4632     // compile time.
4633     if (TheCall->getNumArgs() != 2)
4634       return false;
4635 
4636     std::string RegLower = Reg.lower();
4637     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4638         RegLower != "pan" && RegLower != "uao")
4639       return false;
4640 
4641     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4642   }
4643 
4644   return false;
4645 }
4646 
4647 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4648 /// This checks that the target supports __builtin_longjmp and
4649 /// that val is a constant 1.
4650 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4651   if (!Context.getTargetInfo().hasSjLjLowering())
4652     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4653              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4654 
4655   Expr *Arg = TheCall->getArg(1);
4656   llvm::APSInt Result;
4657 
4658   // TODO: This is less than ideal. Overload this to take a value.
4659   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4660     return true;
4661 
4662   if (Result != 1)
4663     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4664              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4665 
4666   return false;
4667 }
4668 
4669 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4670 /// This checks that the target supports __builtin_setjmp.
4671 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4672   if (!Context.getTargetInfo().hasSjLjLowering())
4673     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4674              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4675   return false;
4676 }
4677 
4678 namespace {
4679 
4680 class UncoveredArgHandler {
4681   enum { Unknown = -1, AllCovered = -2 };
4682 
4683   signed FirstUncoveredArg = Unknown;
4684   SmallVector<const Expr *, 4> DiagnosticExprs;
4685 
4686 public:
4687   UncoveredArgHandler() = default;
4688 
4689   bool hasUncoveredArg() const {
4690     return (FirstUncoveredArg >= 0);
4691   }
4692 
4693   unsigned getUncoveredArg() const {
4694     assert(hasUncoveredArg() && "no uncovered argument");
4695     return FirstUncoveredArg;
4696   }
4697 
4698   void setAllCovered() {
4699     // A string has been found with all arguments covered, so clear out
4700     // the diagnostics.
4701     DiagnosticExprs.clear();
4702     FirstUncoveredArg = AllCovered;
4703   }
4704 
4705   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4706     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4707 
4708     // Don't update if a previous string covers all arguments.
4709     if (FirstUncoveredArg == AllCovered)
4710       return;
4711 
4712     // UncoveredArgHandler tracks the highest uncovered argument index
4713     // and with it all the strings that match this index.
4714     if (NewFirstUncoveredArg == FirstUncoveredArg)
4715       DiagnosticExprs.push_back(StrExpr);
4716     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4717       DiagnosticExprs.clear();
4718       DiagnosticExprs.push_back(StrExpr);
4719       FirstUncoveredArg = NewFirstUncoveredArg;
4720     }
4721   }
4722 
4723   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4724 };
4725 
4726 enum StringLiteralCheckType {
4727   SLCT_NotALiteral,
4728   SLCT_UncheckedLiteral,
4729   SLCT_CheckedLiteral
4730 };
4731 
4732 } // namespace
4733 
4734 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4735                                      BinaryOperatorKind BinOpKind,
4736                                      bool AddendIsRight) {
4737   unsigned BitWidth = Offset.getBitWidth();
4738   unsigned AddendBitWidth = Addend.getBitWidth();
4739   // There might be negative interim results.
4740   if (Addend.isUnsigned()) {
4741     Addend = Addend.zext(++AddendBitWidth);
4742     Addend.setIsSigned(true);
4743   }
4744   // Adjust the bit width of the APSInts.
4745   if (AddendBitWidth > BitWidth) {
4746     Offset = Offset.sext(AddendBitWidth);
4747     BitWidth = AddendBitWidth;
4748   } else if (BitWidth > AddendBitWidth) {
4749     Addend = Addend.sext(BitWidth);
4750   }
4751 
4752   bool Ov = false;
4753   llvm::APSInt ResOffset = Offset;
4754   if (BinOpKind == BO_Add)
4755     ResOffset = Offset.sadd_ov(Addend, Ov);
4756   else {
4757     assert(AddendIsRight && BinOpKind == BO_Sub &&
4758            "operator must be add or sub with addend on the right");
4759     ResOffset = Offset.ssub_ov(Addend, Ov);
4760   }
4761 
4762   // We add an offset to a pointer here so we should support an offset as big as
4763   // possible.
4764   if (Ov) {
4765     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
4766            "index (intermediate) result too big");
4767     Offset = Offset.sext(2 * BitWidth);
4768     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4769     return;
4770   }
4771 
4772   Offset = ResOffset;
4773 }
4774 
4775 namespace {
4776 
4777 // This is a wrapper class around StringLiteral to support offsetted string
4778 // literals as format strings. It takes the offset into account when returning
4779 // the string and its length or the source locations to display notes correctly.
4780 class FormatStringLiteral {
4781   const StringLiteral *FExpr;
4782   int64_t Offset;
4783 
4784  public:
4785   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4786       : FExpr(fexpr), Offset(Offset) {}
4787 
4788   StringRef getString() const {
4789     return FExpr->getString().drop_front(Offset);
4790   }
4791 
4792   unsigned getByteLength() const {
4793     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4794   }
4795 
4796   unsigned getLength() const { return FExpr->getLength() - Offset; }
4797   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4798 
4799   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4800 
4801   QualType getType() const { return FExpr->getType(); }
4802 
4803   bool isAscii() const { return FExpr->isAscii(); }
4804   bool isWide() const { return FExpr->isWide(); }
4805   bool isUTF8() const { return FExpr->isUTF8(); }
4806   bool isUTF16() const { return FExpr->isUTF16(); }
4807   bool isUTF32() const { return FExpr->isUTF32(); }
4808   bool isPascal() const { return FExpr->isPascal(); }
4809 
4810   SourceLocation getLocationOfByte(
4811       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4812       const TargetInfo &Target, unsigned *StartToken = nullptr,
4813       unsigned *StartTokenByteOffset = nullptr) const {
4814     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4815                                     StartToken, StartTokenByteOffset);
4816   }
4817 
4818   SourceLocation getLocStart() const LLVM_READONLY {
4819     return FExpr->getLocStart().getLocWithOffset(Offset);
4820   }
4821 
4822   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4823 };
4824 
4825 }  // namespace
4826 
4827 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4828                               const Expr *OrigFormatExpr,
4829                               ArrayRef<const Expr *> Args,
4830                               bool HasVAListArg, unsigned format_idx,
4831                               unsigned firstDataArg,
4832                               Sema::FormatStringType Type,
4833                               bool inFunctionCall,
4834                               Sema::VariadicCallType CallType,
4835                               llvm::SmallBitVector &CheckedVarArgs,
4836                               UncoveredArgHandler &UncoveredArg);
4837 
4838 // Determine if an expression is a string literal or constant string.
4839 // If this function returns false on the arguments to a function expecting a
4840 // format string, we will usually need to emit a warning.
4841 // True string literals are then checked by CheckFormatString.
4842 static StringLiteralCheckType
4843 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4844                       bool HasVAListArg, unsigned format_idx,
4845                       unsigned firstDataArg, Sema::FormatStringType Type,
4846                       Sema::VariadicCallType CallType, bool InFunctionCall,
4847                       llvm::SmallBitVector &CheckedVarArgs,
4848                       UncoveredArgHandler &UncoveredArg,
4849                       llvm::APSInt Offset) {
4850  tryAgain:
4851   assert(Offset.isSigned() && "invalid offset");
4852 
4853   if (E->isTypeDependent() || E->isValueDependent())
4854     return SLCT_NotALiteral;
4855 
4856   E = E->IgnoreParenCasts();
4857 
4858   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4859     // Technically -Wformat-nonliteral does not warn about this case.
4860     // The behavior of printf and friends in this case is implementation
4861     // dependent.  Ideally if the format string cannot be null then
4862     // it should have a 'nonnull' attribute in the function prototype.
4863     return SLCT_UncheckedLiteral;
4864 
4865   switch (E->getStmtClass()) {
4866   case Stmt::BinaryConditionalOperatorClass:
4867   case Stmt::ConditionalOperatorClass: {
4868     // The expression is a literal if both sub-expressions were, and it was
4869     // completely checked only if both sub-expressions were checked.
4870     const AbstractConditionalOperator *C =
4871         cast<AbstractConditionalOperator>(E);
4872 
4873     // Determine whether it is necessary to check both sub-expressions, for
4874     // example, because the condition expression is a constant that can be
4875     // evaluated at compile time.
4876     bool CheckLeft = true, CheckRight = true;
4877 
4878     bool Cond;
4879     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4880       if (Cond)
4881         CheckRight = false;
4882       else
4883         CheckLeft = false;
4884     }
4885 
4886     // We need to maintain the offsets for the right and the left hand side
4887     // separately to check if every possible indexed expression is a valid
4888     // string literal. They might have different offsets for different string
4889     // literals in the end.
4890     StringLiteralCheckType Left;
4891     if (!CheckLeft)
4892       Left = SLCT_UncheckedLiteral;
4893     else {
4894       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4895                                    HasVAListArg, format_idx, firstDataArg,
4896                                    Type, CallType, InFunctionCall,
4897                                    CheckedVarArgs, UncoveredArg, Offset);
4898       if (Left == SLCT_NotALiteral || !CheckRight) {
4899         return Left;
4900       }
4901     }
4902 
4903     StringLiteralCheckType Right =
4904         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4905                               HasVAListArg, format_idx, firstDataArg,
4906                               Type, CallType, InFunctionCall, CheckedVarArgs,
4907                               UncoveredArg, Offset);
4908 
4909     return (CheckLeft && Left < Right) ? Left : Right;
4910   }
4911 
4912   case Stmt::ImplicitCastExprClass:
4913     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4914     goto tryAgain;
4915 
4916   case Stmt::OpaqueValueExprClass:
4917     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4918       E = src;
4919       goto tryAgain;
4920     }
4921     return SLCT_NotALiteral;
4922 
4923   case Stmt::PredefinedExprClass:
4924     // While __func__, etc., are technically not string literals, they
4925     // cannot contain format specifiers and thus are not a security
4926     // liability.
4927     return SLCT_UncheckedLiteral;
4928 
4929   case Stmt::DeclRefExprClass: {
4930     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4931 
4932     // As an exception, do not flag errors for variables binding to
4933     // const string literals.
4934     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4935       bool isConstant = false;
4936       QualType T = DR->getType();
4937 
4938       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4939         isConstant = AT->getElementType().isConstant(S.Context);
4940       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4941         isConstant = T.isConstant(S.Context) &&
4942                      PT->getPointeeType().isConstant(S.Context);
4943       } else if (T->isObjCObjectPointerType()) {
4944         // In ObjC, there is usually no "const ObjectPointer" type,
4945         // so don't check if the pointee type is constant.
4946         isConstant = T.isConstant(S.Context);
4947       }
4948 
4949       if (isConstant) {
4950         if (const Expr *Init = VD->getAnyInitializer()) {
4951           // Look through initializers like const char c[] = { "foo" }
4952           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4953             if (InitList->isStringLiteralInit())
4954               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4955           }
4956           return checkFormatStringExpr(S, Init, Args,
4957                                        HasVAListArg, format_idx,
4958                                        firstDataArg, Type, CallType,
4959                                        /*InFunctionCall*/ false, CheckedVarArgs,
4960                                        UncoveredArg, Offset);
4961         }
4962       }
4963 
4964       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4965       // special check to see if the format string is a function parameter
4966       // of the function calling the printf function.  If the function
4967       // has an attribute indicating it is a printf-like function, then we
4968       // should suppress warnings concerning non-literals being used in a call
4969       // to a vprintf function.  For example:
4970       //
4971       // void
4972       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4973       //      va_list ap;
4974       //      va_start(ap, fmt);
4975       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4976       //      ...
4977       // }
4978       if (HasVAListArg) {
4979         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4980           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4981             int PVIndex = PV->getFunctionScopeIndex() + 1;
4982             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4983               // adjust for implicit parameter
4984               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4985                 if (MD->isInstance())
4986                   ++PVIndex;
4987               // We also check if the formats are compatible.
4988               // We can't pass a 'scanf' string to a 'printf' function.
4989               if (PVIndex == PVFormat->getFormatIdx() &&
4990                   Type == S.GetFormatStringType(PVFormat))
4991                 return SLCT_UncheckedLiteral;
4992             }
4993           }
4994         }
4995       }
4996     }
4997 
4998     return SLCT_NotALiteral;
4999   }
5000 
5001   case Stmt::CallExprClass:
5002   case Stmt::CXXMemberCallExprClass: {
5003     const CallExpr *CE = cast<CallExpr>(E);
5004     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
5005       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
5006         const Expr *Arg = CE->getArg(FA->formatIdx().getASTIndex());
5007         return checkFormatStringExpr(S, Arg, Args,
5008                                      HasVAListArg, format_idx, firstDataArg,
5009                                      Type, CallType, InFunctionCall,
5010                                      CheckedVarArgs, UncoveredArg, Offset);
5011       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5012         unsigned BuiltinID = FD->getBuiltinID();
5013         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5014             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
5015           const Expr *Arg = CE->getArg(0);
5016           return checkFormatStringExpr(S, Arg, Args,
5017                                        HasVAListArg, format_idx,
5018                                        firstDataArg, Type, CallType,
5019                                        InFunctionCall, CheckedVarArgs,
5020                                        UncoveredArg, Offset);
5021         }
5022       }
5023     }
5024 
5025     return SLCT_NotALiteral;
5026   }
5027   case Stmt::ObjCMessageExprClass: {
5028     const auto *ME = cast<ObjCMessageExpr>(E);
5029     if (const auto *ND = ME->getMethodDecl()) {
5030       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
5031         const Expr *Arg = ME->getArg(FA->formatIdx().getASTIndex());
5032         return checkFormatStringExpr(
5033             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
5034             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
5035       }
5036     }
5037 
5038     return SLCT_NotALiteral;
5039   }
5040   case Stmt::ObjCStringLiteralClass:
5041   case Stmt::StringLiteralClass: {
5042     const StringLiteral *StrE = nullptr;
5043 
5044     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
5045       StrE = ObjCFExpr->getString();
5046     else
5047       StrE = cast<StringLiteral>(E);
5048 
5049     if (StrE) {
5050       if (Offset.isNegative() || Offset > StrE->getLength()) {
5051         // TODO: It would be better to have an explicit warning for out of
5052         // bounds literals.
5053         return SLCT_NotALiteral;
5054       }
5055       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5056       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5057                         firstDataArg, Type, InFunctionCall, CallType,
5058                         CheckedVarArgs, UncoveredArg);
5059       return SLCT_CheckedLiteral;
5060     }
5061 
5062     return SLCT_NotALiteral;
5063   }
5064   case Stmt::BinaryOperatorClass: {
5065     llvm::APSInt LResult;
5066     llvm::APSInt RResult;
5067 
5068     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5069 
5070     // A string literal + an int offset is still a string literal.
5071     if (BinOp->isAdditiveOp()) {
5072       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5073       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5074 
5075       if (LIsInt != RIsInt) {
5076         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5077 
5078         if (LIsInt) {
5079           if (BinOpKind == BO_Add) {
5080             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5081             E = BinOp->getRHS();
5082             goto tryAgain;
5083           }
5084         } else {
5085           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5086           E = BinOp->getLHS();
5087           goto tryAgain;
5088         }
5089       }
5090     }
5091 
5092     return SLCT_NotALiteral;
5093   }
5094   case Stmt::UnaryOperatorClass: {
5095     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5096     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5097     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
5098       llvm::APSInt IndexResult;
5099       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5100         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5101         E = ASE->getBase();
5102         goto tryAgain;
5103       }
5104     }
5105 
5106     return SLCT_NotALiteral;
5107   }
5108 
5109   default:
5110     return SLCT_NotALiteral;
5111   }
5112 }
5113 
5114 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5115   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5116       .Case("scanf", FST_Scanf)
5117       .Cases("printf", "printf0", FST_Printf)
5118       .Cases("NSString", "CFString", FST_NSString)
5119       .Case("strftime", FST_Strftime)
5120       .Case("strfmon", FST_Strfmon)
5121       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5122       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5123       .Case("os_trace", FST_OSLog)
5124       .Case("os_log", FST_OSLog)
5125       .Default(FST_Unknown);
5126 }
5127 
5128 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5129 /// functions) for correct use of format strings.
5130 /// Returns true if a format string has been fully checked.
5131 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5132                                 ArrayRef<const Expr *> Args,
5133                                 bool IsCXXMember,
5134                                 VariadicCallType CallType,
5135                                 SourceLocation Loc, SourceRange Range,
5136                                 llvm::SmallBitVector &CheckedVarArgs) {
5137   FormatStringInfo FSI;
5138   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5139     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5140                                 FSI.FirstDataArg, GetFormatStringType(Format),
5141                                 CallType, Loc, Range, CheckedVarArgs);
5142   return false;
5143 }
5144 
5145 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5146                                 bool HasVAListArg, unsigned format_idx,
5147                                 unsigned firstDataArg, FormatStringType Type,
5148                                 VariadicCallType CallType,
5149                                 SourceLocation Loc, SourceRange Range,
5150                                 llvm::SmallBitVector &CheckedVarArgs) {
5151   // CHECK: printf/scanf-like function is called with no format string.
5152   if (format_idx >= Args.size()) {
5153     Diag(Loc, diag::warn_missing_format_string) << Range;
5154     return false;
5155   }
5156 
5157   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5158 
5159   // CHECK: format string is not a string literal.
5160   //
5161   // Dynamically generated format strings are difficult to
5162   // automatically vet at compile time.  Requiring that format strings
5163   // are string literals: (1) permits the checking of format strings by
5164   // the compiler and thereby (2) can practically remove the source of
5165   // many format string exploits.
5166 
5167   // Format string can be either ObjC string (e.g. @"%d") or
5168   // C string (e.g. "%d")
5169   // ObjC string uses the same format specifiers as C string, so we can use
5170   // the same format string checking logic for both ObjC and C strings.
5171   UncoveredArgHandler UncoveredArg;
5172   StringLiteralCheckType CT =
5173       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5174                             format_idx, firstDataArg, Type, CallType,
5175                             /*IsFunctionCall*/ true, CheckedVarArgs,
5176                             UncoveredArg,
5177                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5178 
5179   // Generate a diagnostic where an uncovered argument is detected.
5180   if (UncoveredArg.hasUncoveredArg()) {
5181     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5182     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5183     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5184   }
5185 
5186   if (CT != SLCT_NotALiteral)
5187     // Literal format string found, check done!
5188     return CT == SLCT_CheckedLiteral;
5189 
5190   // Strftime is particular as it always uses a single 'time' argument,
5191   // so it is safe to pass a non-literal string.
5192   if (Type == FST_Strftime)
5193     return false;
5194 
5195   // Do not emit diag when the string param is a macro expansion and the
5196   // format is either NSString or CFString. This is a hack to prevent
5197   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5198   // which are usually used in place of NS and CF string literals.
5199   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5200   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5201     return false;
5202 
5203   // If there are no arguments specified, warn with -Wformat-security, otherwise
5204   // warn only with -Wformat-nonliteral.
5205   if (Args.size() == firstDataArg) {
5206     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5207       << OrigFormatExpr->getSourceRange();
5208     switch (Type) {
5209     default:
5210       break;
5211     case FST_Kprintf:
5212     case FST_FreeBSDKPrintf:
5213     case FST_Printf:
5214       Diag(FormatLoc, diag::note_format_security_fixit)
5215         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5216       break;
5217     case FST_NSString:
5218       Diag(FormatLoc, diag::note_format_security_fixit)
5219         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5220       break;
5221     }
5222   } else {
5223     Diag(FormatLoc, diag::warn_format_nonliteral)
5224       << OrigFormatExpr->getSourceRange();
5225   }
5226   return false;
5227 }
5228 
5229 namespace {
5230 
5231 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5232 protected:
5233   Sema &S;
5234   const FormatStringLiteral *FExpr;
5235   const Expr *OrigFormatExpr;
5236   const Sema::FormatStringType FSType;
5237   const unsigned FirstDataArg;
5238   const unsigned NumDataArgs;
5239   const char *Beg; // Start of format string.
5240   const bool HasVAListArg;
5241   ArrayRef<const Expr *> Args;
5242   unsigned FormatIdx;
5243   llvm::SmallBitVector CoveredArgs;
5244   bool usesPositionalArgs = false;
5245   bool atFirstArg = true;
5246   bool inFunctionCall;
5247   Sema::VariadicCallType CallType;
5248   llvm::SmallBitVector &CheckedVarArgs;
5249   UncoveredArgHandler &UncoveredArg;
5250 
5251 public:
5252   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5253                      const Expr *origFormatExpr,
5254                      const Sema::FormatStringType type, unsigned firstDataArg,
5255                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5256                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5257                      bool inFunctionCall, Sema::VariadicCallType callType,
5258                      llvm::SmallBitVector &CheckedVarArgs,
5259                      UncoveredArgHandler &UncoveredArg)
5260       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5261         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5262         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5263         inFunctionCall(inFunctionCall), CallType(callType),
5264         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5265     CoveredArgs.resize(numDataArgs);
5266     CoveredArgs.reset();
5267   }
5268 
5269   void DoneProcessing();
5270 
5271   void HandleIncompleteSpecifier(const char *startSpecifier,
5272                                  unsigned specifierLen) override;
5273 
5274   void HandleInvalidLengthModifier(
5275                            const analyze_format_string::FormatSpecifier &FS,
5276                            const analyze_format_string::ConversionSpecifier &CS,
5277                            const char *startSpecifier, unsigned specifierLen,
5278                            unsigned DiagID);
5279 
5280   void HandleNonStandardLengthModifier(
5281                     const analyze_format_string::FormatSpecifier &FS,
5282                     const char *startSpecifier, unsigned specifierLen);
5283 
5284   void HandleNonStandardConversionSpecifier(
5285                     const analyze_format_string::ConversionSpecifier &CS,
5286                     const char *startSpecifier, unsigned specifierLen);
5287 
5288   void HandlePosition(const char *startPos, unsigned posLen) override;
5289 
5290   void HandleInvalidPosition(const char *startSpecifier,
5291                              unsigned specifierLen,
5292                              analyze_format_string::PositionContext p) override;
5293 
5294   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5295 
5296   void HandleNullChar(const char *nullCharacter) override;
5297 
5298   template <typename Range>
5299   static void
5300   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5301                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5302                        bool IsStringLocation, Range StringRange,
5303                        ArrayRef<FixItHint> Fixit = None);
5304 
5305 protected:
5306   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5307                                         const char *startSpec,
5308                                         unsigned specifierLen,
5309                                         const char *csStart, unsigned csLen);
5310 
5311   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5312                                          const char *startSpec,
5313                                          unsigned specifierLen);
5314 
5315   SourceRange getFormatStringRange();
5316   CharSourceRange getSpecifierRange(const char *startSpecifier,
5317                                     unsigned specifierLen);
5318   SourceLocation getLocationOfByte(const char *x);
5319 
5320   const Expr *getDataArg(unsigned i) const;
5321 
5322   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5323                     const analyze_format_string::ConversionSpecifier &CS,
5324                     const char *startSpecifier, unsigned specifierLen,
5325                     unsigned argIndex);
5326 
5327   template <typename Range>
5328   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5329                             bool IsStringLocation, Range StringRange,
5330                             ArrayRef<FixItHint> Fixit = None);
5331 };
5332 
5333 } // namespace
5334 
5335 SourceRange CheckFormatHandler::getFormatStringRange() {
5336   return OrigFormatExpr->getSourceRange();
5337 }
5338 
5339 CharSourceRange CheckFormatHandler::
5340 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5341   SourceLocation Start = getLocationOfByte(startSpecifier);
5342   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5343 
5344   // Advance the end SourceLocation by one due to half-open ranges.
5345   End = End.getLocWithOffset(1);
5346 
5347   return CharSourceRange::getCharRange(Start, End);
5348 }
5349 
5350 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5351   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5352                                   S.getLangOpts(), S.Context.getTargetInfo());
5353 }
5354 
5355 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5356                                                    unsigned specifierLen){
5357   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5358                        getLocationOfByte(startSpecifier),
5359                        /*IsStringLocation*/true,
5360                        getSpecifierRange(startSpecifier, specifierLen));
5361 }
5362 
5363 void CheckFormatHandler::HandleInvalidLengthModifier(
5364     const analyze_format_string::FormatSpecifier &FS,
5365     const analyze_format_string::ConversionSpecifier &CS,
5366     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5367   using namespace analyze_format_string;
5368 
5369   const LengthModifier &LM = FS.getLengthModifier();
5370   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5371 
5372   // See if we know how to fix this length modifier.
5373   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5374   if (FixedLM) {
5375     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5376                          getLocationOfByte(LM.getStart()),
5377                          /*IsStringLocation*/true,
5378                          getSpecifierRange(startSpecifier, specifierLen));
5379 
5380     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5381       << FixedLM->toString()
5382       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5383 
5384   } else {
5385     FixItHint Hint;
5386     if (DiagID == diag::warn_format_nonsensical_length)
5387       Hint = FixItHint::CreateRemoval(LMRange);
5388 
5389     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5390                          getLocationOfByte(LM.getStart()),
5391                          /*IsStringLocation*/true,
5392                          getSpecifierRange(startSpecifier, specifierLen),
5393                          Hint);
5394   }
5395 }
5396 
5397 void CheckFormatHandler::HandleNonStandardLengthModifier(
5398     const analyze_format_string::FormatSpecifier &FS,
5399     const char *startSpecifier, unsigned specifierLen) {
5400   using namespace analyze_format_string;
5401 
5402   const LengthModifier &LM = FS.getLengthModifier();
5403   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5404 
5405   // See if we know how to fix this length modifier.
5406   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5407   if (FixedLM) {
5408     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5409                            << LM.toString() << 0,
5410                          getLocationOfByte(LM.getStart()),
5411                          /*IsStringLocation*/true,
5412                          getSpecifierRange(startSpecifier, specifierLen));
5413 
5414     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5415       << FixedLM->toString()
5416       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5417 
5418   } else {
5419     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5420                            << LM.toString() << 0,
5421                          getLocationOfByte(LM.getStart()),
5422                          /*IsStringLocation*/true,
5423                          getSpecifierRange(startSpecifier, specifierLen));
5424   }
5425 }
5426 
5427 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5428     const analyze_format_string::ConversionSpecifier &CS,
5429     const char *startSpecifier, unsigned specifierLen) {
5430   using namespace analyze_format_string;
5431 
5432   // See if we know how to fix this conversion specifier.
5433   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5434   if (FixedCS) {
5435     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5436                           << CS.toString() << /*conversion specifier*/1,
5437                          getLocationOfByte(CS.getStart()),
5438                          /*IsStringLocation*/true,
5439                          getSpecifierRange(startSpecifier, specifierLen));
5440 
5441     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5442     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5443       << FixedCS->toString()
5444       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5445   } else {
5446     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5447                           << CS.toString() << /*conversion specifier*/1,
5448                          getLocationOfByte(CS.getStart()),
5449                          /*IsStringLocation*/true,
5450                          getSpecifierRange(startSpecifier, specifierLen));
5451   }
5452 }
5453 
5454 void CheckFormatHandler::HandlePosition(const char *startPos,
5455                                         unsigned posLen) {
5456   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5457                                getLocationOfByte(startPos),
5458                                /*IsStringLocation*/true,
5459                                getSpecifierRange(startPos, posLen));
5460 }
5461 
5462 void
5463 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5464                                      analyze_format_string::PositionContext p) {
5465   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5466                          << (unsigned) p,
5467                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5468                        getSpecifierRange(startPos, posLen));
5469 }
5470 
5471 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5472                                             unsigned posLen) {
5473   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5474                                getLocationOfByte(startPos),
5475                                /*IsStringLocation*/true,
5476                                getSpecifierRange(startPos, posLen));
5477 }
5478 
5479 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5480   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5481     // The presence of a null character is likely an error.
5482     EmitFormatDiagnostic(
5483       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5484       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5485       getFormatStringRange());
5486   }
5487 }
5488 
5489 // Note that this may return NULL if there was an error parsing or building
5490 // one of the argument expressions.
5491 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5492   return Args[FirstDataArg + i];
5493 }
5494 
5495 void CheckFormatHandler::DoneProcessing() {
5496   // Does the number of data arguments exceed the number of
5497   // format conversions in the format string?
5498   if (!HasVAListArg) {
5499       // Find any arguments that weren't covered.
5500     CoveredArgs.flip();
5501     signed notCoveredArg = CoveredArgs.find_first();
5502     if (notCoveredArg >= 0) {
5503       assert((unsigned)notCoveredArg < NumDataArgs);
5504       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5505     } else {
5506       UncoveredArg.setAllCovered();
5507     }
5508   }
5509 }
5510 
5511 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5512                                    const Expr *ArgExpr) {
5513   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5514          "Invalid state");
5515 
5516   if (!ArgExpr)
5517     return;
5518 
5519   SourceLocation Loc = ArgExpr->getLocStart();
5520 
5521   if (S.getSourceManager().isInSystemMacro(Loc))
5522     return;
5523 
5524   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5525   for (auto E : DiagnosticExprs)
5526     PDiag << E->getSourceRange();
5527 
5528   CheckFormatHandler::EmitFormatDiagnostic(
5529                                   S, IsFunctionCall, DiagnosticExprs[0],
5530                                   PDiag, Loc, /*IsStringLocation*/false,
5531                                   DiagnosticExprs[0]->getSourceRange());
5532 }
5533 
5534 bool
5535 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5536                                                      SourceLocation Loc,
5537                                                      const char *startSpec,
5538                                                      unsigned specifierLen,
5539                                                      const char *csStart,
5540                                                      unsigned csLen) {
5541   bool keepGoing = true;
5542   if (argIndex < NumDataArgs) {
5543     // Consider the argument coverered, even though the specifier doesn't
5544     // make sense.
5545     CoveredArgs.set(argIndex);
5546   }
5547   else {
5548     // If argIndex exceeds the number of data arguments we
5549     // don't issue a warning because that is just a cascade of warnings (and
5550     // they may have intended '%%' anyway). We don't want to continue processing
5551     // the format string after this point, however, as we will like just get
5552     // gibberish when trying to match arguments.
5553     keepGoing = false;
5554   }
5555 
5556   StringRef Specifier(csStart, csLen);
5557 
5558   // If the specifier in non-printable, it could be the first byte of a UTF-8
5559   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5560   // hex value.
5561   std::string CodePointStr;
5562   if (!llvm::sys::locale::isPrint(*csStart)) {
5563     llvm::UTF32 CodePoint;
5564     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5565     const llvm::UTF8 *E =
5566         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5567     llvm::ConversionResult Result =
5568         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5569 
5570     if (Result != llvm::conversionOK) {
5571       unsigned char FirstChar = *csStart;
5572       CodePoint = (llvm::UTF32)FirstChar;
5573     }
5574 
5575     llvm::raw_string_ostream OS(CodePointStr);
5576     if (CodePoint < 256)
5577       OS << "\\x" << llvm::format("%02x", CodePoint);
5578     else if (CodePoint <= 0xFFFF)
5579       OS << "\\u" << llvm::format("%04x", CodePoint);
5580     else
5581       OS << "\\U" << llvm::format("%08x", CodePoint);
5582     OS.flush();
5583     Specifier = CodePointStr;
5584   }
5585 
5586   EmitFormatDiagnostic(
5587       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5588       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5589 
5590   return keepGoing;
5591 }
5592 
5593 void
5594 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5595                                                       const char *startSpec,
5596                                                       unsigned specifierLen) {
5597   EmitFormatDiagnostic(
5598     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5599     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5600 }
5601 
5602 bool
5603 CheckFormatHandler::CheckNumArgs(
5604   const analyze_format_string::FormatSpecifier &FS,
5605   const analyze_format_string::ConversionSpecifier &CS,
5606   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5607 
5608   if (argIndex >= NumDataArgs) {
5609     PartialDiagnostic PDiag = FS.usesPositionalArg()
5610       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5611            << (argIndex+1) << NumDataArgs)
5612       : S.PDiag(diag::warn_printf_insufficient_data_args);
5613     EmitFormatDiagnostic(
5614       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5615       getSpecifierRange(startSpecifier, specifierLen));
5616 
5617     // Since more arguments than conversion tokens are given, by extension
5618     // all arguments are covered, so mark this as so.
5619     UncoveredArg.setAllCovered();
5620     return false;
5621   }
5622   return true;
5623 }
5624 
5625 template<typename Range>
5626 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5627                                               SourceLocation Loc,
5628                                               bool IsStringLocation,
5629                                               Range StringRange,
5630                                               ArrayRef<FixItHint> FixIt) {
5631   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5632                        Loc, IsStringLocation, StringRange, FixIt);
5633 }
5634 
5635 /// \brief If the format string is not within the funcion call, emit a note
5636 /// so that the function call and string are in diagnostic messages.
5637 ///
5638 /// \param InFunctionCall if true, the format string is within the function
5639 /// call and only one diagnostic message will be produced.  Otherwise, an
5640 /// extra note will be emitted pointing to location of the format string.
5641 ///
5642 /// \param ArgumentExpr the expression that is passed as the format string
5643 /// argument in the function call.  Used for getting locations when two
5644 /// diagnostics are emitted.
5645 ///
5646 /// \param PDiag the callee should already have provided any strings for the
5647 /// diagnostic message.  This function only adds locations and fixits
5648 /// to diagnostics.
5649 ///
5650 /// \param Loc primary location for diagnostic.  If two diagnostics are
5651 /// required, one will be at Loc and a new SourceLocation will be created for
5652 /// the other one.
5653 ///
5654 /// \param IsStringLocation if true, Loc points to the format string should be
5655 /// used for the note.  Otherwise, Loc points to the argument list and will
5656 /// be used with PDiag.
5657 ///
5658 /// \param StringRange some or all of the string to highlight.  This is
5659 /// templated so it can accept either a CharSourceRange or a SourceRange.
5660 ///
5661 /// \param FixIt optional fix it hint for the format string.
5662 template <typename Range>
5663 void CheckFormatHandler::EmitFormatDiagnostic(
5664     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5665     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5666     Range StringRange, ArrayRef<FixItHint> FixIt) {
5667   if (InFunctionCall) {
5668     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5669     D << StringRange;
5670     D << FixIt;
5671   } else {
5672     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5673       << ArgumentExpr->getSourceRange();
5674 
5675     const Sema::SemaDiagnosticBuilder &Note =
5676       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5677              diag::note_format_string_defined);
5678 
5679     Note << StringRange;
5680     Note << FixIt;
5681   }
5682 }
5683 
5684 //===--- CHECK: Printf format string checking ------------------------------===//
5685 
5686 namespace {
5687 
5688 class CheckPrintfHandler : public CheckFormatHandler {
5689 public:
5690   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5691                      const Expr *origFormatExpr,
5692                      const Sema::FormatStringType type, unsigned firstDataArg,
5693                      unsigned numDataArgs, bool isObjC, const char *beg,
5694                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5695                      unsigned formatIdx, bool inFunctionCall,
5696                      Sema::VariadicCallType CallType,
5697                      llvm::SmallBitVector &CheckedVarArgs,
5698                      UncoveredArgHandler &UncoveredArg)
5699       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5700                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5701                            inFunctionCall, CallType, CheckedVarArgs,
5702                            UncoveredArg) {}
5703 
5704   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5705 
5706   /// Returns true if '%@' specifiers are allowed in the format string.
5707   bool allowsObjCArg() const {
5708     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5709            FSType == Sema::FST_OSTrace;
5710   }
5711 
5712   bool HandleInvalidPrintfConversionSpecifier(
5713                                       const analyze_printf::PrintfSpecifier &FS,
5714                                       const char *startSpecifier,
5715                                       unsigned specifierLen) override;
5716 
5717   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5718                              const char *startSpecifier,
5719                              unsigned specifierLen) override;
5720   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5721                        const char *StartSpecifier,
5722                        unsigned SpecifierLen,
5723                        const Expr *E);
5724 
5725   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5726                     const char *startSpecifier, unsigned specifierLen);
5727   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5728                            const analyze_printf::OptionalAmount &Amt,
5729                            unsigned type,
5730                            const char *startSpecifier, unsigned specifierLen);
5731   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5732                   const analyze_printf::OptionalFlag &flag,
5733                   const char *startSpecifier, unsigned specifierLen);
5734   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5735                          const analyze_printf::OptionalFlag &ignoredFlag,
5736                          const analyze_printf::OptionalFlag &flag,
5737                          const char *startSpecifier, unsigned specifierLen);
5738   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5739                            const Expr *E);
5740 
5741   void HandleEmptyObjCModifierFlag(const char *startFlag,
5742                                    unsigned flagLen) override;
5743 
5744   void HandleInvalidObjCModifierFlag(const char *startFlag,
5745                                             unsigned flagLen) override;
5746 
5747   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5748                                            const char *flagsEnd,
5749                                            const char *conversionPosition)
5750                                              override;
5751 };
5752 
5753 } // namespace
5754 
5755 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5756                                       const analyze_printf::PrintfSpecifier &FS,
5757                                       const char *startSpecifier,
5758                                       unsigned specifierLen) {
5759   const analyze_printf::PrintfConversionSpecifier &CS =
5760     FS.getConversionSpecifier();
5761 
5762   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5763                                           getLocationOfByte(CS.getStart()),
5764                                           startSpecifier, specifierLen,
5765                                           CS.getStart(), CS.getLength());
5766 }
5767 
5768 bool CheckPrintfHandler::HandleAmount(
5769                                const analyze_format_string::OptionalAmount &Amt,
5770                                unsigned k, const char *startSpecifier,
5771                                unsigned specifierLen) {
5772   if (Amt.hasDataArgument()) {
5773     if (!HasVAListArg) {
5774       unsigned argIndex = Amt.getArgIndex();
5775       if (argIndex >= NumDataArgs) {
5776         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5777                                << k,
5778                              getLocationOfByte(Amt.getStart()),
5779                              /*IsStringLocation*/true,
5780                              getSpecifierRange(startSpecifier, specifierLen));
5781         // Don't do any more checking.  We will just emit
5782         // spurious errors.
5783         return false;
5784       }
5785 
5786       // Type check the data argument.  It should be an 'int'.
5787       // Although not in conformance with C99, we also allow the argument to be
5788       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5789       // doesn't emit a warning for that case.
5790       CoveredArgs.set(argIndex);
5791       const Expr *Arg = getDataArg(argIndex);
5792       if (!Arg)
5793         return false;
5794 
5795       QualType T = Arg->getType();
5796 
5797       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5798       assert(AT.isValid());
5799 
5800       if (!AT.matchesType(S.Context, T)) {
5801         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5802                                << k << AT.getRepresentativeTypeName(S.Context)
5803                                << T << Arg->getSourceRange(),
5804                              getLocationOfByte(Amt.getStart()),
5805                              /*IsStringLocation*/true,
5806                              getSpecifierRange(startSpecifier, specifierLen));
5807         // Don't do any more checking.  We will just emit
5808         // spurious errors.
5809         return false;
5810       }
5811     }
5812   }
5813   return true;
5814 }
5815 
5816 void CheckPrintfHandler::HandleInvalidAmount(
5817                                       const analyze_printf::PrintfSpecifier &FS,
5818                                       const analyze_printf::OptionalAmount &Amt,
5819                                       unsigned type,
5820                                       const char *startSpecifier,
5821                                       unsigned specifierLen) {
5822   const analyze_printf::PrintfConversionSpecifier &CS =
5823     FS.getConversionSpecifier();
5824 
5825   FixItHint fixit =
5826     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5827       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5828                                  Amt.getConstantLength()))
5829       : FixItHint();
5830 
5831   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5832                          << type << CS.toString(),
5833                        getLocationOfByte(Amt.getStart()),
5834                        /*IsStringLocation*/true,
5835                        getSpecifierRange(startSpecifier, specifierLen),
5836                        fixit);
5837 }
5838 
5839 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5840                                     const analyze_printf::OptionalFlag &flag,
5841                                     const char *startSpecifier,
5842                                     unsigned specifierLen) {
5843   // Warn about pointless flag with a fixit removal.
5844   const analyze_printf::PrintfConversionSpecifier &CS =
5845     FS.getConversionSpecifier();
5846   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5847                          << flag.toString() << CS.toString(),
5848                        getLocationOfByte(flag.getPosition()),
5849                        /*IsStringLocation*/true,
5850                        getSpecifierRange(startSpecifier, specifierLen),
5851                        FixItHint::CreateRemoval(
5852                          getSpecifierRange(flag.getPosition(), 1)));
5853 }
5854 
5855 void CheckPrintfHandler::HandleIgnoredFlag(
5856                                 const analyze_printf::PrintfSpecifier &FS,
5857                                 const analyze_printf::OptionalFlag &ignoredFlag,
5858                                 const analyze_printf::OptionalFlag &flag,
5859                                 const char *startSpecifier,
5860                                 unsigned specifierLen) {
5861   // Warn about ignored flag with a fixit removal.
5862   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5863                          << ignoredFlag.toString() << flag.toString(),
5864                        getLocationOfByte(ignoredFlag.getPosition()),
5865                        /*IsStringLocation*/true,
5866                        getSpecifierRange(startSpecifier, specifierLen),
5867                        FixItHint::CreateRemoval(
5868                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5869 }
5870 
5871 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5872                                                      unsigned flagLen) {
5873   // Warn about an empty flag.
5874   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5875                        getLocationOfByte(startFlag),
5876                        /*IsStringLocation*/true,
5877                        getSpecifierRange(startFlag, flagLen));
5878 }
5879 
5880 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5881                                                        unsigned flagLen) {
5882   // Warn about an invalid flag.
5883   auto Range = getSpecifierRange(startFlag, flagLen);
5884   StringRef flag(startFlag, flagLen);
5885   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5886                       getLocationOfByte(startFlag),
5887                       /*IsStringLocation*/true,
5888                       Range, FixItHint::CreateRemoval(Range));
5889 }
5890 
5891 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5892     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5893     // Warn about using '[...]' without a '@' conversion.
5894     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5895     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5896     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5897                          getLocationOfByte(conversionPosition),
5898                          /*IsStringLocation*/true,
5899                          Range, FixItHint::CreateRemoval(Range));
5900 }
5901 
5902 // Determines if the specified is a C++ class or struct containing
5903 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5904 // "c_str()").
5905 template<typename MemberKind>
5906 static llvm::SmallPtrSet<MemberKind*, 1>
5907 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5908   const RecordType *RT = Ty->getAs<RecordType>();
5909   llvm::SmallPtrSet<MemberKind*, 1> Results;
5910 
5911   if (!RT)
5912     return Results;
5913   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5914   if (!RD || !RD->getDefinition())
5915     return Results;
5916 
5917   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5918                  Sema::LookupMemberName);
5919   R.suppressDiagnostics();
5920 
5921   // We just need to include all members of the right kind turned up by the
5922   // filter, at this point.
5923   if (S.LookupQualifiedName(R, RT->getDecl()))
5924     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5925       NamedDecl *decl = (*I)->getUnderlyingDecl();
5926       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5927         Results.insert(FK);
5928     }
5929   return Results;
5930 }
5931 
5932 /// Check if we could call '.c_str()' on an object.
5933 ///
5934 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5935 /// allow the call, or if it would be ambiguous).
5936 bool Sema::hasCStrMethod(const Expr *E) {
5937   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5938 
5939   MethodSet Results =
5940       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5941   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5942        MI != ME; ++MI)
5943     if ((*MI)->getMinRequiredArguments() == 0)
5944       return true;
5945   return false;
5946 }
5947 
5948 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5949 // better diagnostic if so. AT is assumed to be valid.
5950 // Returns true when a c_str() conversion method is found.
5951 bool CheckPrintfHandler::checkForCStrMembers(
5952     const analyze_printf::ArgType &AT, const Expr *E) {
5953   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
5954 
5955   MethodSet Results =
5956       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5957 
5958   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5959        MI != ME; ++MI) {
5960     const CXXMethodDecl *Method = *MI;
5961     if (Method->getMinRequiredArguments() == 0 &&
5962         AT.matchesType(S.Context, Method->getReturnType())) {
5963       // FIXME: Suggest parens if the expression needs them.
5964       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5965       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5966           << "c_str()"
5967           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5968       return true;
5969     }
5970   }
5971 
5972   return false;
5973 }
5974 
5975 bool
5976 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5977                                             &FS,
5978                                           const char *startSpecifier,
5979                                           unsigned specifierLen) {
5980   using namespace analyze_format_string;
5981   using namespace analyze_printf;
5982 
5983   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5984 
5985   if (FS.consumesDataArgument()) {
5986     if (atFirstArg) {
5987         atFirstArg = false;
5988         usesPositionalArgs = FS.usesPositionalArg();
5989     }
5990     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5991       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5992                                         startSpecifier, specifierLen);
5993       return false;
5994     }
5995   }
5996 
5997   // First check if the field width, precision, and conversion specifier
5998   // have matching data arguments.
5999   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
6000                     startSpecifier, specifierLen)) {
6001     return false;
6002   }
6003 
6004   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
6005                     startSpecifier, specifierLen)) {
6006     return false;
6007   }
6008 
6009   if (!CS.consumesDataArgument()) {
6010     // FIXME: Technically specifying a precision or field width here
6011     // makes no sense.  Worth issuing a warning at some point.
6012     return true;
6013   }
6014 
6015   // Consume the argument.
6016   unsigned argIndex = FS.getArgIndex();
6017   if (argIndex < NumDataArgs) {
6018     // The check to see if the argIndex is valid will come later.
6019     // We set the bit here because we may exit early from this
6020     // function if we encounter some other error.
6021     CoveredArgs.set(argIndex);
6022   }
6023 
6024   // FreeBSD kernel extensions.
6025   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
6026       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
6027     // We need at least two arguments.
6028     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
6029       return false;
6030 
6031     // Claim the second argument.
6032     CoveredArgs.set(argIndex + 1);
6033 
6034     // Type check the first argument (int for %b, pointer for %D)
6035     const Expr *Ex = getDataArg(argIndex);
6036     const analyze_printf::ArgType &AT =
6037       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
6038         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
6039     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
6040       EmitFormatDiagnostic(
6041         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6042         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
6043         << false << Ex->getSourceRange(),
6044         Ex->getLocStart(), /*IsStringLocation*/false,
6045         getSpecifierRange(startSpecifier, specifierLen));
6046 
6047     // Type check the second argument (char * for both %b and %D)
6048     Ex = getDataArg(argIndex + 1);
6049     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
6050     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
6051       EmitFormatDiagnostic(
6052         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6053         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6054         << false << Ex->getSourceRange(),
6055         Ex->getLocStart(), /*IsStringLocation*/false,
6056         getSpecifierRange(startSpecifier, specifierLen));
6057 
6058      return true;
6059   }
6060 
6061   // Check for using an Objective-C specific conversion specifier
6062   // in a non-ObjC literal.
6063   if (!allowsObjCArg() && CS.isObjCArg()) {
6064     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6065                                                   specifierLen);
6066   }
6067 
6068   // %P can only be used with os_log.
6069   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6070     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6071                                                   specifierLen);
6072   }
6073 
6074   // %n is not allowed with os_log.
6075   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6076     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6077                          getLocationOfByte(CS.getStart()),
6078                          /*IsStringLocation*/ false,
6079                          getSpecifierRange(startSpecifier, specifierLen));
6080 
6081     return true;
6082   }
6083 
6084   // Only scalars are allowed for os_trace.
6085   if (FSType == Sema::FST_OSTrace &&
6086       (CS.getKind() == ConversionSpecifier::PArg ||
6087        CS.getKind() == ConversionSpecifier::sArg ||
6088        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6089     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6090                                                   specifierLen);
6091   }
6092 
6093   // Check for use of public/private annotation outside of os_log().
6094   if (FSType != Sema::FST_OSLog) {
6095     if (FS.isPublic().isSet()) {
6096       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6097                                << "public",
6098                            getLocationOfByte(FS.isPublic().getPosition()),
6099                            /*IsStringLocation*/ false,
6100                            getSpecifierRange(startSpecifier, specifierLen));
6101     }
6102     if (FS.isPrivate().isSet()) {
6103       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6104                                << "private",
6105                            getLocationOfByte(FS.isPrivate().getPosition()),
6106                            /*IsStringLocation*/ false,
6107                            getSpecifierRange(startSpecifier, specifierLen));
6108     }
6109   }
6110 
6111   // Check for invalid use of field width
6112   if (!FS.hasValidFieldWidth()) {
6113     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6114         startSpecifier, specifierLen);
6115   }
6116 
6117   // Check for invalid use of precision
6118   if (!FS.hasValidPrecision()) {
6119     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6120         startSpecifier, specifierLen);
6121   }
6122 
6123   // Precision is mandatory for %P specifier.
6124   if (CS.getKind() == ConversionSpecifier::PArg &&
6125       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6126     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6127                          getLocationOfByte(startSpecifier),
6128                          /*IsStringLocation*/ false,
6129                          getSpecifierRange(startSpecifier, specifierLen));
6130   }
6131 
6132   // Check each flag does not conflict with any other component.
6133   if (!FS.hasValidThousandsGroupingPrefix())
6134     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6135   if (!FS.hasValidLeadingZeros())
6136     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6137   if (!FS.hasValidPlusPrefix())
6138     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6139   if (!FS.hasValidSpacePrefix())
6140     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6141   if (!FS.hasValidAlternativeForm())
6142     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6143   if (!FS.hasValidLeftJustified())
6144     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6145 
6146   // Check that flags are not ignored by another flag
6147   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6148     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6149         startSpecifier, specifierLen);
6150   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6151     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6152             startSpecifier, specifierLen);
6153 
6154   // Check the length modifier is valid with the given conversion specifier.
6155   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6156     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6157                                 diag::warn_format_nonsensical_length);
6158   else if (!FS.hasStandardLengthModifier())
6159     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6160   else if (!FS.hasStandardLengthConversionCombination())
6161     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6162                                 diag::warn_format_non_standard_conversion_spec);
6163 
6164   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6165     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6166 
6167   // The remaining checks depend on the data arguments.
6168   if (HasVAListArg)
6169     return true;
6170 
6171   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6172     return false;
6173 
6174   const Expr *Arg = getDataArg(argIndex);
6175   if (!Arg)
6176     return true;
6177 
6178   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6179 }
6180 
6181 static bool requiresParensToAddCast(const Expr *E) {
6182   // FIXME: We should have a general way to reason about operator
6183   // precedence and whether parens are actually needed here.
6184   // Take care of a few common cases where they aren't.
6185   const Expr *Inside = E->IgnoreImpCasts();
6186   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6187     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6188 
6189   switch (Inside->getStmtClass()) {
6190   case Stmt::ArraySubscriptExprClass:
6191   case Stmt::CallExprClass:
6192   case Stmt::CharacterLiteralClass:
6193   case Stmt::CXXBoolLiteralExprClass:
6194   case Stmt::DeclRefExprClass:
6195   case Stmt::FloatingLiteralClass:
6196   case Stmt::IntegerLiteralClass:
6197   case Stmt::MemberExprClass:
6198   case Stmt::ObjCArrayLiteralClass:
6199   case Stmt::ObjCBoolLiteralExprClass:
6200   case Stmt::ObjCBoxedExprClass:
6201   case Stmt::ObjCDictionaryLiteralClass:
6202   case Stmt::ObjCEncodeExprClass:
6203   case Stmt::ObjCIvarRefExprClass:
6204   case Stmt::ObjCMessageExprClass:
6205   case Stmt::ObjCPropertyRefExprClass:
6206   case Stmt::ObjCStringLiteralClass:
6207   case Stmt::ObjCSubscriptRefExprClass:
6208   case Stmt::ParenExprClass:
6209   case Stmt::StringLiteralClass:
6210   case Stmt::UnaryOperatorClass:
6211     return false;
6212   default:
6213     return true;
6214   }
6215 }
6216 
6217 static std::pair<QualType, StringRef>
6218 shouldNotPrintDirectly(const ASTContext &Context,
6219                        QualType IntendedTy,
6220                        const Expr *E) {
6221   // Use a 'while' to peel off layers of typedefs.
6222   QualType TyTy = IntendedTy;
6223   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6224     StringRef Name = UserTy->getDecl()->getName();
6225     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6226       .Case("CFIndex", Context.getNSIntegerType())
6227       .Case("NSInteger", Context.getNSIntegerType())
6228       .Case("NSUInteger", Context.getNSUIntegerType())
6229       .Case("SInt32", Context.IntTy)
6230       .Case("UInt32", Context.UnsignedIntTy)
6231       .Default(QualType());
6232 
6233     if (!CastTy.isNull())
6234       return std::make_pair(CastTy, Name);
6235 
6236     TyTy = UserTy->desugar();
6237   }
6238 
6239   // Strip parens if necessary.
6240   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6241     return shouldNotPrintDirectly(Context,
6242                                   PE->getSubExpr()->getType(),
6243                                   PE->getSubExpr());
6244 
6245   // If this is a conditional expression, then its result type is constructed
6246   // via usual arithmetic conversions and thus there might be no necessary
6247   // typedef sugar there.  Recurse to operands to check for NSInteger &
6248   // Co. usage condition.
6249   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6250     QualType TrueTy, FalseTy;
6251     StringRef TrueName, FalseName;
6252 
6253     std::tie(TrueTy, TrueName) =
6254       shouldNotPrintDirectly(Context,
6255                              CO->getTrueExpr()->getType(),
6256                              CO->getTrueExpr());
6257     std::tie(FalseTy, FalseName) =
6258       shouldNotPrintDirectly(Context,
6259                              CO->getFalseExpr()->getType(),
6260                              CO->getFalseExpr());
6261 
6262     if (TrueTy == FalseTy)
6263       return std::make_pair(TrueTy, TrueName);
6264     else if (TrueTy.isNull())
6265       return std::make_pair(FalseTy, FalseName);
6266     else if (FalseTy.isNull())
6267       return std::make_pair(TrueTy, TrueName);
6268   }
6269 
6270   return std::make_pair(QualType(), StringRef());
6271 }
6272 
6273 bool
6274 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6275                                     const char *StartSpecifier,
6276                                     unsigned SpecifierLen,
6277                                     const Expr *E) {
6278   using namespace analyze_format_string;
6279   using namespace analyze_printf;
6280 
6281   // Now type check the data expression that matches the
6282   // format specifier.
6283   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6284   if (!AT.isValid())
6285     return true;
6286 
6287   QualType ExprTy = E->getType();
6288   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6289     ExprTy = TET->getUnderlyingExpr()->getType();
6290   }
6291 
6292   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6293 
6294   if (match == analyze_printf::ArgType::Match) {
6295     return true;
6296   }
6297 
6298   // Look through argument promotions for our error message's reported type.
6299   // This includes the integral and floating promotions, but excludes array
6300   // and function pointer decay; seeing that an argument intended to be a
6301   // string has type 'char [6]' is probably more confusing than 'char *'.
6302   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6303     if (ICE->getCastKind() == CK_IntegralCast ||
6304         ICE->getCastKind() == CK_FloatingCast) {
6305       E = ICE->getSubExpr();
6306       ExprTy = E->getType();
6307 
6308       // Check if we didn't match because of an implicit cast from a 'char'
6309       // or 'short' to an 'int'.  This is done because printf is a varargs
6310       // function.
6311       if (ICE->getType() == S.Context.IntTy ||
6312           ICE->getType() == S.Context.UnsignedIntTy) {
6313         // All further checking is done on the subexpression.
6314         if (AT.matchesType(S.Context, ExprTy))
6315           return true;
6316       }
6317     }
6318   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6319     // Special case for 'a', which has type 'int' in C.
6320     // Note, however, that we do /not/ want to treat multibyte constants like
6321     // 'MooV' as characters! This form is deprecated but still exists.
6322     if (ExprTy == S.Context.IntTy)
6323       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6324         ExprTy = S.Context.CharTy;
6325   }
6326 
6327   // Look through enums to their underlying type.
6328   bool IsEnum = false;
6329   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6330     ExprTy = EnumTy->getDecl()->getIntegerType();
6331     IsEnum = true;
6332   }
6333 
6334   // %C in an Objective-C context prints a unichar, not a wchar_t.
6335   // If the argument is an integer of some kind, believe the %C and suggest
6336   // a cast instead of changing the conversion specifier.
6337   QualType IntendedTy = ExprTy;
6338   if (isObjCContext() &&
6339       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6340     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6341         !ExprTy->isCharType()) {
6342       // 'unichar' is defined as a typedef of unsigned short, but we should
6343       // prefer using the typedef if it is visible.
6344       IntendedTy = S.Context.UnsignedShortTy;
6345 
6346       // While we are here, check if the value is an IntegerLiteral that happens
6347       // to be within the valid range.
6348       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6349         const llvm::APInt &V = IL->getValue();
6350         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6351           return true;
6352       }
6353 
6354       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6355                           Sema::LookupOrdinaryName);
6356       if (S.LookupName(Result, S.getCurScope())) {
6357         NamedDecl *ND = Result.getFoundDecl();
6358         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6359           if (TD->getUnderlyingType() == IntendedTy)
6360             IntendedTy = S.Context.getTypedefType(TD);
6361       }
6362     }
6363   }
6364 
6365   // Special-case some of Darwin's platform-independence types by suggesting
6366   // casts to primitive types that are known to be large enough.
6367   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6368   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6369     QualType CastTy;
6370     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6371     if (!CastTy.isNull()) {
6372       IntendedTy = CastTy;
6373       ShouldNotPrintDirectly = true;
6374     }
6375   }
6376 
6377   // We may be able to offer a FixItHint if it is a supported type.
6378   PrintfSpecifier fixedFS = FS;
6379   bool success =
6380       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6381 
6382   if (success) {
6383     // Get the fix string from the fixed format specifier
6384     SmallString<16> buf;
6385     llvm::raw_svector_ostream os(buf);
6386     fixedFS.toString(os);
6387 
6388     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6389 
6390     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6391       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6392       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6393         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6394       }
6395       // In this case, the specifier is wrong and should be changed to match
6396       // the argument.
6397       EmitFormatDiagnostic(S.PDiag(diag)
6398                                << AT.getRepresentativeTypeName(S.Context)
6399                                << IntendedTy << IsEnum << E->getSourceRange(),
6400                            E->getLocStart(),
6401                            /*IsStringLocation*/ false, SpecRange,
6402                            FixItHint::CreateReplacement(SpecRange, os.str()));
6403     } else {
6404       // The canonical type for formatting this value is different from the
6405       // actual type of the expression. (This occurs, for example, with Darwin's
6406       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6407       // should be printed as 'long' for 64-bit compatibility.)
6408       // Rather than emitting a normal format/argument mismatch, we want to
6409       // add a cast to the recommended type (and correct the format string
6410       // if necessary).
6411       SmallString<16> CastBuf;
6412       llvm::raw_svector_ostream CastFix(CastBuf);
6413       CastFix << "(";
6414       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6415       CastFix << ")";
6416 
6417       SmallVector<FixItHint,4> Hints;
6418       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6419         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6420 
6421       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6422         // If there's already a cast present, just replace it.
6423         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6424         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6425 
6426       } else if (!requiresParensToAddCast(E)) {
6427         // If the expression has high enough precedence,
6428         // just write the C-style cast.
6429         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6430                                                    CastFix.str()));
6431       } else {
6432         // Otherwise, add parens around the expression as well as the cast.
6433         CastFix << "(";
6434         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6435                                                    CastFix.str()));
6436 
6437         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6438         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6439       }
6440 
6441       if (ShouldNotPrintDirectly) {
6442         // The expression has a type that should not be printed directly.
6443         // We extract the name from the typedef because we don't want to show
6444         // the underlying type in the diagnostic.
6445         StringRef Name;
6446         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6447           Name = TypedefTy->getDecl()->getName();
6448         else
6449           Name = CastTyName;
6450         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6451                                << Name << IntendedTy << IsEnum
6452                                << E->getSourceRange(),
6453                              E->getLocStart(), /*IsStringLocation=*/false,
6454                              SpecRange, Hints);
6455       } else {
6456         // In this case, the expression could be printed using a different
6457         // specifier, but we've decided that the specifier is probably correct
6458         // and we should cast instead. Just use the normal warning message.
6459         EmitFormatDiagnostic(
6460           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6461             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6462             << E->getSourceRange(),
6463           E->getLocStart(), /*IsStringLocation*/false,
6464           SpecRange, Hints);
6465       }
6466     }
6467   } else {
6468     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6469                                                    SpecifierLen);
6470     // Since the warning for passing non-POD types to variadic functions
6471     // was deferred until now, we emit a warning for non-POD
6472     // arguments here.
6473     switch (S.isValidVarArgType(ExprTy)) {
6474     case Sema::VAK_Valid:
6475     case Sema::VAK_ValidInCXX11: {
6476       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6477       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6478         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6479       }
6480 
6481       EmitFormatDiagnostic(
6482           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6483                         << IsEnum << CSR << E->getSourceRange(),
6484           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6485       break;
6486     }
6487     case Sema::VAK_Undefined:
6488     case Sema::VAK_MSVCUndefined:
6489       EmitFormatDiagnostic(
6490         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6491           << S.getLangOpts().CPlusPlus11
6492           << ExprTy
6493           << CallType
6494           << AT.getRepresentativeTypeName(S.Context)
6495           << CSR
6496           << E->getSourceRange(),
6497         E->getLocStart(), /*IsStringLocation*/false, CSR);
6498       checkForCStrMembers(AT, E);
6499       break;
6500 
6501     case Sema::VAK_Invalid:
6502       if (ExprTy->isObjCObjectType())
6503         EmitFormatDiagnostic(
6504           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6505             << S.getLangOpts().CPlusPlus11
6506             << ExprTy
6507             << CallType
6508             << AT.getRepresentativeTypeName(S.Context)
6509             << CSR
6510             << E->getSourceRange(),
6511           E->getLocStart(), /*IsStringLocation*/false, CSR);
6512       else
6513         // FIXME: If this is an initializer list, suggest removing the braces
6514         // or inserting a cast to the target type.
6515         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6516           << isa<InitListExpr>(E) << ExprTy << CallType
6517           << AT.getRepresentativeTypeName(S.Context)
6518           << E->getSourceRange();
6519       break;
6520     }
6521 
6522     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6523            "format string specifier index out of range");
6524     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6525   }
6526 
6527   return true;
6528 }
6529 
6530 //===--- CHECK: Scanf format string checking ------------------------------===//
6531 
6532 namespace {
6533 
6534 class CheckScanfHandler : public CheckFormatHandler {
6535 public:
6536   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6537                     const Expr *origFormatExpr, Sema::FormatStringType type,
6538                     unsigned firstDataArg, unsigned numDataArgs,
6539                     const char *beg, bool hasVAListArg,
6540                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6541                     bool inFunctionCall, Sema::VariadicCallType CallType,
6542                     llvm::SmallBitVector &CheckedVarArgs,
6543                     UncoveredArgHandler &UncoveredArg)
6544       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6545                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6546                            inFunctionCall, CallType, CheckedVarArgs,
6547                            UncoveredArg) {}
6548 
6549   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6550                             const char *startSpecifier,
6551                             unsigned specifierLen) override;
6552 
6553   bool HandleInvalidScanfConversionSpecifier(
6554           const analyze_scanf::ScanfSpecifier &FS,
6555           const char *startSpecifier,
6556           unsigned specifierLen) override;
6557 
6558   void HandleIncompleteScanList(const char *start, const char *end) override;
6559 };
6560 
6561 } // namespace
6562 
6563 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6564                                                  const char *end) {
6565   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6566                        getLocationOfByte(end), /*IsStringLocation*/true,
6567                        getSpecifierRange(start, end - start));
6568 }
6569 
6570 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6571                                         const analyze_scanf::ScanfSpecifier &FS,
6572                                         const char *startSpecifier,
6573                                         unsigned specifierLen) {
6574   const analyze_scanf::ScanfConversionSpecifier &CS =
6575     FS.getConversionSpecifier();
6576 
6577   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6578                                           getLocationOfByte(CS.getStart()),
6579                                           startSpecifier, specifierLen,
6580                                           CS.getStart(), CS.getLength());
6581 }
6582 
6583 bool CheckScanfHandler::HandleScanfSpecifier(
6584                                        const analyze_scanf::ScanfSpecifier &FS,
6585                                        const char *startSpecifier,
6586                                        unsigned specifierLen) {
6587   using namespace analyze_scanf;
6588   using namespace analyze_format_string;
6589 
6590   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6591 
6592   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6593   // be used to decide if we are using positional arguments consistently.
6594   if (FS.consumesDataArgument()) {
6595     if (atFirstArg) {
6596       atFirstArg = false;
6597       usesPositionalArgs = FS.usesPositionalArg();
6598     }
6599     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6600       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6601                                         startSpecifier, specifierLen);
6602       return false;
6603     }
6604   }
6605 
6606   // Check if the field with is non-zero.
6607   const OptionalAmount &Amt = FS.getFieldWidth();
6608   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6609     if (Amt.getConstantAmount() == 0) {
6610       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6611                                                    Amt.getConstantLength());
6612       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6613                            getLocationOfByte(Amt.getStart()),
6614                            /*IsStringLocation*/true, R,
6615                            FixItHint::CreateRemoval(R));
6616     }
6617   }
6618 
6619   if (!FS.consumesDataArgument()) {
6620     // FIXME: Technically specifying a precision or field width here
6621     // makes no sense.  Worth issuing a warning at some point.
6622     return true;
6623   }
6624 
6625   // Consume the argument.
6626   unsigned argIndex = FS.getArgIndex();
6627   if (argIndex < NumDataArgs) {
6628       // The check to see if the argIndex is valid will come later.
6629       // We set the bit here because we may exit early from this
6630       // function if we encounter some other error.
6631     CoveredArgs.set(argIndex);
6632   }
6633 
6634   // Check the length modifier is valid with the given conversion specifier.
6635   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6636     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6637                                 diag::warn_format_nonsensical_length);
6638   else if (!FS.hasStandardLengthModifier())
6639     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6640   else if (!FS.hasStandardLengthConversionCombination())
6641     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6642                                 diag::warn_format_non_standard_conversion_spec);
6643 
6644   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6645     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6646 
6647   // The remaining checks depend on the data arguments.
6648   if (HasVAListArg)
6649     return true;
6650 
6651   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6652     return false;
6653 
6654   // Check that the argument type matches the format specifier.
6655   const Expr *Ex = getDataArg(argIndex);
6656   if (!Ex)
6657     return true;
6658 
6659   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6660 
6661   if (!AT.isValid()) {
6662     return true;
6663   }
6664 
6665   analyze_format_string::ArgType::MatchKind match =
6666       AT.matchesType(S.Context, Ex->getType());
6667   if (match == analyze_format_string::ArgType::Match) {
6668     return true;
6669   }
6670 
6671   ScanfSpecifier fixedFS = FS;
6672   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6673                                  S.getLangOpts(), S.Context);
6674 
6675   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6676   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6677     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6678   }
6679 
6680   if (success) {
6681     // Get the fix string from the fixed format specifier.
6682     SmallString<128> buf;
6683     llvm::raw_svector_ostream os(buf);
6684     fixedFS.toString(os);
6685 
6686     EmitFormatDiagnostic(
6687         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6688                       << Ex->getType() << false << Ex->getSourceRange(),
6689         Ex->getLocStart(),
6690         /*IsStringLocation*/ false,
6691         getSpecifierRange(startSpecifier, specifierLen),
6692         FixItHint::CreateReplacement(
6693             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6694   } else {
6695     EmitFormatDiagnostic(S.PDiag(diag)
6696                              << AT.getRepresentativeTypeName(S.Context)
6697                              << Ex->getType() << false << Ex->getSourceRange(),
6698                          Ex->getLocStart(),
6699                          /*IsStringLocation*/ false,
6700                          getSpecifierRange(startSpecifier, specifierLen));
6701   }
6702 
6703   return true;
6704 }
6705 
6706 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6707                               const Expr *OrigFormatExpr,
6708                               ArrayRef<const Expr *> Args,
6709                               bool HasVAListArg, unsigned format_idx,
6710                               unsigned firstDataArg,
6711                               Sema::FormatStringType Type,
6712                               bool inFunctionCall,
6713                               Sema::VariadicCallType CallType,
6714                               llvm::SmallBitVector &CheckedVarArgs,
6715                               UncoveredArgHandler &UncoveredArg) {
6716   // CHECK: is the format string a wide literal?
6717   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6718     CheckFormatHandler::EmitFormatDiagnostic(
6719       S, inFunctionCall, Args[format_idx],
6720       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6721       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6722     return;
6723   }
6724 
6725   // Str - The format string.  NOTE: this is NOT null-terminated!
6726   StringRef StrRef = FExpr->getString();
6727   const char *Str = StrRef.data();
6728   // Account for cases where the string literal is truncated in a declaration.
6729   const ConstantArrayType *T =
6730     S.Context.getAsConstantArrayType(FExpr->getType());
6731   assert(T && "String literal not of constant array type!");
6732   size_t TypeSize = T->getSize().getZExtValue();
6733   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6734   const unsigned numDataArgs = Args.size() - firstDataArg;
6735 
6736   // Emit a warning if the string literal is truncated and does not contain an
6737   // embedded null character.
6738   if (TypeSize <= StrRef.size() &&
6739       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6740     CheckFormatHandler::EmitFormatDiagnostic(
6741         S, inFunctionCall, Args[format_idx],
6742         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6743         FExpr->getLocStart(),
6744         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6745     return;
6746   }
6747 
6748   // CHECK: empty format string?
6749   if (StrLen == 0 && numDataArgs > 0) {
6750     CheckFormatHandler::EmitFormatDiagnostic(
6751       S, inFunctionCall, Args[format_idx],
6752       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6753       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6754     return;
6755   }
6756 
6757   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6758       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6759       Type == Sema::FST_OSTrace) {
6760     CheckPrintfHandler H(
6761         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6762         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6763         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6764         CheckedVarArgs, UncoveredArg);
6765 
6766     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6767                                                   S.getLangOpts(),
6768                                                   S.Context.getTargetInfo(),
6769                                             Type == Sema::FST_FreeBSDKPrintf))
6770       H.DoneProcessing();
6771   } else if (Type == Sema::FST_Scanf) {
6772     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6773                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6774                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6775 
6776     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6777                                                  S.getLangOpts(),
6778                                                  S.Context.getTargetInfo()))
6779       H.DoneProcessing();
6780   } // TODO: handle other formats
6781 }
6782 
6783 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6784   // Str - The format string.  NOTE: this is NOT null-terminated!
6785   StringRef StrRef = FExpr->getString();
6786   const char *Str = StrRef.data();
6787   // Account for cases where the string literal is truncated in a declaration.
6788   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6789   assert(T && "String literal not of constant array type!");
6790   size_t TypeSize = T->getSize().getZExtValue();
6791   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6792   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6793                                                          getLangOpts(),
6794                                                          Context.getTargetInfo());
6795 }
6796 
6797 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6798 
6799 // Returns the related absolute value function that is larger, of 0 if one
6800 // does not exist.
6801 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6802   switch (AbsFunction) {
6803   default:
6804     return 0;
6805 
6806   case Builtin::BI__builtin_abs:
6807     return Builtin::BI__builtin_labs;
6808   case Builtin::BI__builtin_labs:
6809     return Builtin::BI__builtin_llabs;
6810   case Builtin::BI__builtin_llabs:
6811     return 0;
6812 
6813   case Builtin::BI__builtin_fabsf:
6814     return Builtin::BI__builtin_fabs;
6815   case Builtin::BI__builtin_fabs:
6816     return Builtin::BI__builtin_fabsl;
6817   case Builtin::BI__builtin_fabsl:
6818     return 0;
6819 
6820   case Builtin::BI__builtin_cabsf:
6821     return Builtin::BI__builtin_cabs;
6822   case Builtin::BI__builtin_cabs:
6823     return Builtin::BI__builtin_cabsl;
6824   case Builtin::BI__builtin_cabsl:
6825     return 0;
6826 
6827   case Builtin::BIabs:
6828     return Builtin::BIlabs;
6829   case Builtin::BIlabs:
6830     return Builtin::BIllabs;
6831   case Builtin::BIllabs:
6832     return 0;
6833 
6834   case Builtin::BIfabsf:
6835     return Builtin::BIfabs;
6836   case Builtin::BIfabs:
6837     return Builtin::BIfabsl;
6838   case Builtin::BIfabsl:
6839     return 0;
6840 
6841   case Builtin::BIcabsf:
6842    return Builtin::BIcabs;
6843   case Builtin::BIcabs:
6844     return Builtin::BIcabsl;
6845   case Builtin::BIcabsl:
6846     return 0;
6847   }
6848 }
6849 
6850 // Returns the argument type of the absolute value function.
6851 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6852                                              unsigned AbsType) {
6853   if (AbsType == 0)
6854     return QualType();
6855 
6856   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6857   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6858   if (Error != ASTContext::GE_None)
6859     return QualType();
6860 
6861   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6862   if (!FT)
6863     return QualType();
6864 
6865   if (FT->getNumParams() != 1)
6866     return QualType();
6867 
6868   return FT->getParamType(0);
6869 }
6870 
6871 // Returns the best absolute value function, or zero, based on type and
6872 // current absolute value function.
6873 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6874                                    unsigned AbsFunctionKind) {
6875   unsigned BestKind = 0;
6876   uint64_t ArgSize = Context.getTypeSize(ArgType);
6877   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6878        Kind = getLargerAbsoluteValueFunction(Kind)) {
6879     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6880     if (Context.getTypeSize(ParamType) >= ArgSize) {
6881       if (BestKind == 0)
6882         BestKind = Kind;
6883       else if (Context.hasSameType(ParamType, ArgType)) {
6884         BestKind = Kind;
6885         break;
6886       }
6887     }
6888   }
6889   return BestKind;
6890 }
6891 
6892 enum AbsoluteValueKind {
6893   AVK_Integer,
6894   AVK_Floating,
6895   AVK_Complex
6896 };
6897 
6898 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6899   if (T->isIntegralOrEnumerationType())
6900     return AVK_Integer;
6901   if (T->isRealFloatingType())
6902     return AVK_Floating;
6903   if (T->isAnyComplexType())
6904     return AVK_Complex;
6905 
6906   llvm_unreachable("Type not integer, floating, or complex");
6907 }
6908 
6909 // Changes the absolute value function to a different type.  Preserves whether
6910 // the function is a builtin.
6911 static unsigned changeAbsFunction(unsigned AbsKind,
6912                                   AbsoluteValueKind ValueKind) {
6913   switch (ValueKind) {
6914   case AVK_Integer:
6915     switch (AbsKind) {
6916     default:
6917       return 0;
6918     case Builtin::BI__builtin_fabsf:
6919     case Builtin::BI__builtin_fabs:
6920     case Builtin::BI__builtin_fabsl:
6921     case Builtin::BI__builtin_cabsf:
6922     case Builtin::BI__builtin_cabs:
6923     case Builtin::BI__builtin_cabsl:
6924       return Builtin::BI__builtin_abs;
6925     case Builtin::BIfabsf:
6926     case Builtin::BIfabs:
6927     case Builtin::BIfabsl:
6928     case Builtin::BIcabsf:
6929     case Builtin::BIcabs:
6930     case Builtin::BIcabsl:
6931       return Builtin::BIabs;
6932     }
6933   case AVK_Floating:
6934     switch (AbsKind) {
6935     default:
6936       return 0;
6937     case Builtin::BI__builtin_abs:
6938     case Builtin::BI__builtin_labs:
6939     case Builtin::BI__builtin_llabs:
6940     case Builtin::BI__builtin_cabsf:
6941     case Builtin::BI__builtin_cabs:
6942     case Builtin::BI__builtin_cabsl:
6943       return Builtin::BI__builtin_fabsf;
6944     case Builtin::BIabs:
6945     case Builtin::BIlabs:
6946     case Builtin::BIllabs:
6947     case Builtin::BIcabsf:
6948     case Builtin::BIcabs:
6949     case Builtin::BIcabsl:
6950       return Builtin::BIfabsf;
6951     }
6952   case AVK_Complex:
6953     switch (AbsKind) {
6954     default:
6955       return 0;
6956     case Builtin::BI__builtin_abs:
6957     case Builtin::BI__builtin_labs:
6958     case Builtin::BI__builtin_llabs:
6959     case Builtin::BI__builtin_fabsf:
6960     case Builtin::BI__builtin_fabs:
6961     case Builtin::BI__builtin_fabsl:
6962       return Builtin::BI__builtin_cabsf;
6963     case Builtin::BIabs:
6964     case Builtin::BIlabs:
6965     case Builtin::BIllabs:
6966     case Builtin::BIfabsf:
6967     case Builtin::BIfabs:
6968     case Builtin::BIfabsl:
6969       return Builtin::BIcabsf;
6970     }
6971   }
6972   llvm_unreachable("Unable to convert function");
6973 }
6974 
6975 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6976   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6977   if (!FnInfo)
6978     return 0;
6979 
6980   switch (FDecl->getBuiltinID()) {
6981   default:
6982     return 0;
6983   case Builtin::BI__builtin_abs:
6984   case Builtin::BI__builtin_fabs:
6985   case Builtin::BI__builtin_fabsf:
6986   case Builtin::BI__builtin_fabsl:
6987   case Builtin::BI__builtin_labs:
6988   case Builtin::BI__builtin_llabs:
6989   case Builtin::BI__builtin_cabs:
6990   case Builtin::BI__builtin_cabsf:
6991   case Builtin::BI__builtin_cabsl:
6992   case Builtin::BIabs:
6993   case Builtin::BIlabs:
6994   case Builtin::BIllabs:
6995   case Builtin::BIfabs:
6996   case Builtin::BIfabsf:
6997   case Builtin::BIfabsl:
6998   case Builtin::BIcabs:
6999   case Builtin::BIcabsf:
7000   case Builtin::BIcabsl:
7001     return FDecl->getBuiltinID();
7002   }
7003   llvm_unreachable("Unknown Builtin type");
7004 }
7005 
7006 // If the replacement is valid, emit a note with replacement function.
7007 // Additionally, suggest including the proper header if not already included.
7008 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
7009                             unsigned AbsKind, QualType ArgType) {
7010   bool EmitHeaderHint = true;
7011   const char *HeaderName = nullptr;
7012   const char *FunctionName = nullptr;
7013   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
7014     FunctionName = "std::abs";
7015     if (ArgType->isIntegralOrEnumerationType()) {
7016       HeaderName = "cstdlib";
7017     } else if (ArgType->isRealFloatingType()) {
7018       HeaderName = "cmath";
7019     } else {
7020       llvm_unreachable("Invalid Type");
7021     }
7022 
7023     // Lookup all std::abs
7024     if (NamespaceDecl *Std = S.getStdNamespace()) {
7025       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
7026       R.suppressDiagnostics();
7027       S.LookupQualifiedName(R, Std);
7028 
7029       for (const auto *I : R) {
7030         const FunctionDecl *FDecl = nullptr;
7031         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
7032           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
7033         } else {
7034           FDecl = dyn_cast<FunctionDecl>(I);
7035         }
7036         if (!FDecl)
7037           continue;
7038 
7039         // Found std::abs(), check that they are the right ones.
7040         if (FDecl->getNumParams() != 1)
7041           continue;
7042 
7043         // Check that the parameter type can handle the argument.
7044         QualType ParamType = FDecl->getParamDecl(0)->getType();
7045         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
7046             S.Context.getTypeSize(ArgType) <=
7047                 S.Context.getTypeSize(ParamType)) {
7048           // Found a function, don't need the header hint.
7049           EmitHeaderHint = false;
7050           break;
7051         }
7052       }
7053     }
7054   } else {
7055     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7056     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7057 
7058     if (HeaderName) {
7059       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7060       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7061       R.suppressDiagnostics();
7062       S.LookupName(R, S.getCurScope());
7063 
7064       if (R.isSingleResult()) {
7065         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7066         if (FD && FD->getBuiltinID() == AbsKind) {
7067           EmitHeaderHint = false;
7068         } else {
7069           return;
7070         }
7071       } else if (!R.empty()) {
7072         return;
7073       }
7074     }
7075   }
7076 
7077   S.Diag(Loc, diag::note_replace_abs_function)
7078       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7079 
7080   if (!HeaderName)
7081     return;
7082 
7083   if (!EmitHeaderHint)
7084     return;
7085 
7086   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7087                                                     << FunctionName;
7088 }
7089 
7090 template <std::size_t StrLen>
7091 static bool IsStdFunction(const FunctionDecl *FDecl,
7092                           const char (&Str)[StrLen]) {
7093   if (!FDecl)
7094     return false;
7095   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7096     return false;
7097   if (!FDecl->isInStdNamespace())
7098     return false;
7099 
7100   return true;
7101 }
7102 
7103 // Warn when using the wrong abs() function.
7104 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7105                                       const FunctionDecl *FDecl) {
7106   if (Call->getNumArgs() != 1)
7107     return;
7108 
7109   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7110   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7111   if (AbsKind == 0 && !IsStdAbs)
7112     return;
7113 
7114   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7115   QualType ParamType = Call->getArg(0)->getType();
7116 
7117   // Unsigned types cannot be negative.  Suggest removing the absolute value
7118   // function call.
7119   if (ArgType->isUnsignedIntegerType()) {
7120     const char *FunctionName =
7121         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7122     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7123     Diag(Call->getExprLoc(), diag::note_remove_abs)
7124         << FunctionName
7125         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7126     return;
7127   }
7128 
7129   // Taking the absolute value of a pointer is very suspicious, they probably
7130   // wanted to index into an array, dereference a pointer, call a function, etc.
7131   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7132     unsigned DiagType = 0;
7133     if (ArgType->isFunctionType())
7134       DiagType = 1;
7135     else if (ArgType->isArrayType())
7136       DiagType = 2;
7137 
7138     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7139     return;
7140   }
7141 
7142   // std::abs has overloads which prevent most of the absolute value problems
7143   // from occurring.
7144   if (IsStdAbs)
7145     return;
7146 
7147   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7148   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7149 
7150   // The argument and parameter are the same kind.  Check if they are the right
7151   // size.
7152   if (ArgValueKind == ParamValueKind) {
7153     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7154       return;
7155 
7156     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7157     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7158         << FDecl << ArgType << ParamType;
7159 
7160     if (NewAbsKind == 0)
7161       return;
7162 
7163     emitReplacement(*this, Call->getExprLoc(),
7164                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7165     return;
7166   }
7167 
7168   // ArgValueKind != ParamValueKind
7169   // The wrong type of absolute value function was used.  Attempt to find the
7170   // proper one.
7171   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7172   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7173   if (NewAbsKind == 0)
7174     return;
7175 
7176   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7177       << FDecl << ParamValueKind << ArgValueKind;
7178 
7179   emitReplacement(*this, Call->getExprLoc(),
7180                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7181 }
7182 
7183 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7184 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7185                                 const FunctionDecl *FDecl) {
7186   if (!Call || !FDecl) return;
7187 
7188   // Ignore template specializations and macros.
7189   if (inTemplateInstantiation()) return;
7190   if (Call->getExprLoc().isMacroID()) return;
7191 
7192   // Only care about the one template argument, two function parameter std::max
7193   if (Call->getNumArgs() != 2) return;
7194   if (!IsStdFunction(FDecl, "max")) return;
7195   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7196   if (!ArgList) return;
7197   if (ArgList->size() != 1) return;
7198 
7199   // Check that template type argument is unsigned integer.
7200   const auto& TA = ArgList->get(0);
7201   if (TA.getKind() != TemplateArgument::Type) return;
7202   QualType ArgType = TA.getAsType();
7203   if (!ArgType->isUnsignedIntegerType()) return;
7204 
7205   // See if either argument is a literal zero.
7206   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7207     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7208     if (!MTE) return false;
7209     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7210     if (!Num) return false;
7211     if (Num->getValue() != 0) return false;
7212     return true;
7213   };
7214 
7215   const Expr *FirstArg = Call->getArg(0);
7216   const Expr *SecondArg = Call->getArg(1);
7217   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7218   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7219 
7220   // Only warn when exactly one argument is zero.
7221   if (IsFirstArgZero == IsSecondArgZero) return;
7222 
7223   SourceRange FirstRange = FirstArg->getSourceRange();
7224   SourceRange SecondRange = SecondArg->getSourceRange();
7225 
7226   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7227 
7228   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7229       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7230 
7231   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7232   SourceRange RemovalRange;
7233   if (IsFirstArgZero) {
7234     RemovalRange = SourceRange(FirstRange.getBegin(),
7235                                SecondRange.getBegin().getLocWithOffset(-1));
7236   } else {
7237     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7238                                SecondRange.getEnd());
7239   }
7240 
7241   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7242         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7243         << FixItHint::CreateRemoval(RemovalRange);
7244 }
7245 
7246 //===--- CHECK: Standard memory functions ---------------------------------===//
7247 
7248 /// \brief Takes the expression passed to the size_t parameter of functions
7249 /// such as memcmp, strncat, etc and warns if it's a comparison.
7250 ///
7251 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7252 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7253                                            IdentifierInfo *FnName,
7254                                            SourceLocation FnLoc,
7255                                            SourceLocation RParenLoc) {
7256   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7257   if (!Size)
7258     return false;
7259 
7260   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
7261   if (!Size->isComparisonOp() && !Size->isLogicalOp())
7262     return false;
7263 
7264   SourceRange SizeRange = Size->getSourceRange();
7265   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7266       << SizeRange << FnName;
7267   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7268       << FnName << FixItHint::CreateInsertion(
7269                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7270       << FixItHint::CreateRemoval(RParenLoc);
7271   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7272       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7273       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7274                                     ")");
7275 
7276   return true;
7277 }
7278 
7279 /// \brief Determine whether the given type is or contains a dynamic class type
7280 /// (e.g., whether it has a vtable).
7281 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7282                                                      bool &IsContained) {
7283   // Look through array types while ignoring qualifiers.
7284   const Type *Ty = T->getBaseElementTypeUnsafe();
7285   IsContained = false;
7286 
7287   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7288   RD = RD ? RD->getDefinition() : nullptr;
7289   if (!RD || RD->isInvalidDecl())
7290     return nullptr;
7291 
7292   if (RD->isDynamicClass())
7293     return RD;
7294 
7295   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7296   // It's impossible for a class to transitively contain itself by value, so
7297   // infinite recursion is impossible.
7298   for (auto *FD : RD->fields()) {
7299     bool SubContained;
7300     if (const CXXRecordDecl *ContainedRD =
7301             getContainedDynamicClass(FD->getType(), SubContained)) {
7302       IsContained = true;
7303       return ContainedRD;
7304     }
7305   }
7306 
7307   return nullptr;
7308 }
7309 
7310 /// \brief If E is a sizeof expression, returns its argument expression,
7311 /// otherwise returns NULL.
7312 static const Expr *getSizeOfExprArg(const Expr *E) {
7313   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7314       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7315     if (SizeOf->getKind() == UETT_SizeOf && !SizeOf->isArgumentType())
7316       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7317 
7318   return nullptr;
7319 }
7320 
7321 /// \brief If E is a sizeof expression, returns its argument type.
7322 static QualType getSizeOfArgType(const Expr *E) {
7323   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7324       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7325     if (SizeOf->getKind() == UETT_SizeOf)
7326       return SizeOf->getTypeOfArgument();
7327 
7328   return QualType();
7329 }
7330 
7331 /// \brief Check for dangerous or invalid arguments to memset().
7332 ///
7333 /// This issues warnings on known problematic, dangerous or unspecified
7334 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7335 /// function calls.
7336 ///
7337 /// \param Call The call expression to diagnose.
7338 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7339                                    unsigned BId,
7340                                    IdentifierInfo *FnName) {
7341   assert(BId != 0);
7342 
7343   // It is possible to have a non-standard definition of memset.  Validate
7344   // we have enough arguments, and if not, abort further checking.
7345   unsigned ExpectedNumArgs =
7346       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7347   if (Call->getNumArgs() < ExpectedNumArgs)
7348     return;
7349 
7350   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7351                       BId == Builtin::BIstrndup ? 1 : 2);
7352   unsigned LenArg =
7353       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7354   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7355 
7356   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7357                                      Call->getLocStart(), Call->getRParenLoc()))
7358     return;
7359 
7360   // We have special checking when the length is a sizeof expression.
7361   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7362   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7363   llvm::FoldingSetNodeID SizeOfArgID;
7364 
7365   // Although widely used, 'bzero' is not a standard function. Be more strict
7366   // with the argument types before allowing diagnostics and only allow the
7367   // form bzero(ptr, sizeof(...)).
7368   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7369   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7370     return;
7371 
7372   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7373     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7374     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7375 
7376     QualType DestTy = Dest->getType();
7377     QualType PointeeTy;
7378     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7379       PointeeTy = DestPtrTy->getPointeeType();
7380 
7381       // Never warn about void type pointers. This can be used to suppress
7382       // false positives.
7383       if (PointeeTy->isVoidType())
7384         continue;
7385 
7386       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7387       // actually comparing the expressions for equality. Because computing the
7388       // expression IDs can be expensive, we only do this if the diagnostic is
7389       // enabled.
7390       if (SizeOfArg &&
7391           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7392                            SizeOfArg->getExprLoc())) {
7393         // We only compute IDs for expressions if the warning is enabled, and
7394         // cache the sizeof arg's ID.
7395         if (SizeOfArgID == llvm::FoldingSetNodeID())
7396           SizeOfArg->Profile(SizeOfArgID, Context, true);
7397         llvm::FoldingSetNodeID DestID;
7398         Dest->Profile(DestID, Context, true);
7399         if (DestID == SizeOfArgID) {
7400           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7401           //       over sizeof(src) as well.
7402           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7403           StringRef ReadableName = FnName->getName();
7404 
7405           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7406             if (UnaryOp->getOpcode() == UO_AddrOf)
7407               ActionIdx = 1; // If its an address-of operator, just remove it.
7408           if (!PointeeTy->isIncompleteType() &&
7409               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7410             ActionIdx = 2; // If the pointee's size is sizeof(char),
7411                            // suggest an explicit length.
7412 
7413           // If the function is defined as a builtin macro, do not show macro
7414           // expansion.
7415           SourceLocation SL = SizeOfArg->getExprLoc();
7416           SourceRange DSR = Dest->getSourceRange();
7417           SourceRange SSR = SizeOfArg->getSourceRange();
7418           SourceManager &SM = getSourceManager();
7419 
7420           if (SM.isMacroArgExpansion(SL)) {
7421             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7422             SL = SM.getSpellingLoc(SL);
7423             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7424                              SM.getSpellingLoc(DSR.getEnd()));
7425             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7426                              SM.getSpellingLoc(SSR.getEnd()));
7427           }
7428 
7429           DiagRuntimeBehavior(SL, SizeOfArg,
7430                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7431                                 << ReadableName
7432                                 << PointeeTy
7433                                 << DestTy
7434                                 << DSR
7435                                 << SSR);
7436           DiagRuntimeBehavior(SL, SizeOfArg,
7437                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7438                                 << ActionIdx
7439                                 << SSR);
7440 
7441           break;
7442         }
7443       }
7444 
7445       // Also check for cases where the sizeof argument is the exact same
7446       // type as the memory argument, and where it points to a user-defined
7447       // record type.
7448       if (SizeOfArgTy != QualType()) {
7449         if (PointeeTy->isRecordType() &&
7450             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7451           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7452                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7453                                 << FnName << SizeOfArgTy << ArgIdx
7454                                 << PointeeTy << Dest->getSourceRange()
7455                                 << LenExpr->getSourceRange());
7456           break;
7457         }
7458       }
7459     } else if (DestTy->isArrayType()) {
7460       PointeeTy = DestTy;
7461     }
7462 
7463     if (PointeeTy == QualType())
7464       continue;
7465 
7466     // Always complain about dynamic classes.
7467     bool IsContained;
7468     if (const CXXRecordDecl *ContainedRD =
7469             getContainedDynamicClass(PointeeTy, IsContained)) {
7470 
7471       unsigned OperationType = 0;
7472       // "overwritten" if we're warning about the destination for any call
7473       // but memcmp; otherwise a verb appropriate to the call.
7474       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7475         if (BId == Builtin::BImemcpy)
7476           OperationType = 1;
7477         else if(BId == Builtin::BImemmove)
7478           OperationType = 2;
7479         else if (BId == Builtin::BImemcmp)
7480           OperationType = 3;
7481       }
7482 
7483       DiagRuntimeBehavior(
7484         Dest->getExprLoc(), Dest,
7485         PDiag(diag::warn_dyn_class_memaccess)
7486           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7487           << FnName << IsContained << ContainedRD << OperationType
7488           << Call->getCallee()->getSourceRange());
7489     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7490              BId != Builtin::BImemset)
7491       DiagRuntimeBehavior(
7492         Dest->getExprLoc(), Dest,
7493         PDiag(diag::warn_arc_object_memaccess)
7494           << ArgIdx << FnName << PointeeTy
7495           << Call->getCallee()->getSourceRange());
7496     else
7497       continue;
7498 
7499     DiagRuntimeBehavior(
7500       Dest->getExprLoc(), Dest,
7501       PDiag(diag::note_bad_memaccess_silence)
7502         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7503     break;
7504   }
7505 }
7506 
7507 // A little helper routine: ignore addition and subtraction of integer literals.
7508 // This intentionally does not ignore all integer constant expressions because
7509 // we don't want to remove sizeof().
7510 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7511   Ex = Ex->IgnoreParenCasts();
7512 
7513   while (true) {
7514     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7515     if (!BO || !BO->isAdditiveOp())
7516       break;
7517 
7518     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7519     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7520 
7521     if (isa<IntegerLiteral>(RHS))
7522       Ex = LHS;
7523     else if (isa<IntegerLiteral>(LHS))
7524       Ex = RHS;
7525     else
7526       break;
7527   }
7528 
7529   return Ex;
7530 }
7531 
7532 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7533                                                       ASTContext &Context) {
7534   // Only handle constant-sized or VLAs, but not flexible members.
7535   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7536     // Only issue the FIXIT for arrays of size > 1.
7537     if (CAT->getSize().getSExtValue() <= 1)
7538       return false;
7539   } else if (!Ty->isVariableArrayType()) {
7540     return false;
7541   }
7542   return true;
7543 }
7544 
7545 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7546 // be the size of the source, instead of the destination.
7547 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7548                                     IdentifierInfo *FnName) {
7549 
7550   // Don't crash if the user has the wrong number of arguments
7551   unsigned NumArgs = Call->getNumArgs();
7552   if ((NumArgs != 3) && (NumArgs != 4))
7553     return;
7554 
7555   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7556   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7557   const Expr *CompareWithSrc = nullptr;
7558 
7559   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7560                                      Call->getLocStart(), Call->getRParenLoc()))
7561     return;
7562 
7563   // Look for 'strlcpy(dst, x, sizeof(x))'
7564   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7565     CompareWithSrc = Ex;
7566   else {
7567     // Look for 'strlcpy(dst, x, strlen(x))'
7568     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7569       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7570           SizeCall->getNumArgs() == 1)
7571         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7572     }
7573   }
7574 
7575   if (!CompareWithSrc)
7576     return;
7577 
7578   // Determine if the argument to sizeof/strlen is equal to the source
7579   // argument.  In principle there's all kinds of things you could do
7580   // here, for instance creating an == expression and evaluating it with
7581   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7582   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7583   if (!SrcArgDRE)
7584     return;
7585 
7586   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7587   if (!CompareWithSrcDRE ||
7588       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7589     return;
7590 
7591   const Expr *OriginalSizeArg = Call->getArg(2);
7592   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7593     << OriginalSizeArg->getSourceRange() << FnName;
7594 
7595   // Output a FIXIT hint if the destination is an array (rather than a
7596   // pointer to an array).  This could be enhanced to handle some
7597   // pointers if we know the actual size, like if DstArg is 'array+2'
7598   // we could say 'sizeof(array)-2'.
7599   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7600   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7601     return;
7602 
7603   SmallString<128> sizeString;
7604   llvm::raw_svector_ostream OS(sizeString);
7605   OS << "sizeof(";
7606   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7607   OS << ")";
7608 
7609   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7610     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7611                                     OS.str());
7612 }
7613 
7614 /// Check if two expressions refer to the same declaration.
7615 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7616   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7617     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7618       return D1->getDecl() == D2->getDecl();
7619   return false;
7620 }
7621 
7622 static const Expr *getStrlenExprArg(const Expr *E) {
7623   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7624     const FunctionDecl *FD = CE->getDirectCallee();
7625     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7626       return nullptr;
7627     return CE->getArg(0)->IgnoreParenCasts();
7628   }
7629   return nullptr;
7630 }
7631 
7632 // Warn on anti-patterns as the 'size' argument to strncat.
7633 // The correct size argument should look like following:
7634 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7635 void Sema::CheckStrncatArguments(const CallExpr *CE,
7636                                  IdentifierInfo *FnName) {
7637   // Don't crash if the user has the wrong number of arguments.
7638   if (CE->getNumArgs() < 3)
7639     return;
7640   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7641   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7642   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7643 
7644   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7645                                      CE->getRParenLoc()))
7646     return;
7647 
7648   // Identify common expressions, which are wrongly used as the size argument
7649   // to strncat and may lead to buffer overflows.
7650   unsigned PatternType = 0;
7651   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7652     // - sizeof(dst)
7653     if (referToTheSameDecl(SizeOfArg, DstArg))
7654       PatternType = 1;
7655     // - sizeof(src)
7656     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7657       PatternType = 2;
7658   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7659     if (BE->getOpcode() == BO_Sub) {
7660       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7661       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7662       // - sizeof(dst) - strlen(dst)
7663       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7664           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7665         PatternType = 1;
7666       // - sizeof(src) - (anything)
7667       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7668         PatternType = 2;
7669     }
7670   }
7671 
7672   if (PatternType == 0)
7673     return;
7674 
7675   // Generate the diagnostic.
7676   SourceLocation SL = LenArg->getLocStart();
7677   SourceRange SR = LenArg->getSourceRange();
7678   SourceManager &SM = getSourceManager();
7679 
7680   // If the function is defined as a builtin macro, do not show macro expansion.
7681   if (SM.isMacroArgExpansion(SL)) {
7682     SL = SM.getSpellingLoc(SL);
7683     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7684                      SM.getSpellingLoc(SR.getEnd()));
7685   }
7686 
7687   // Check if the destination is an array (rather than a pointer to an array).
7688   QualType DstTy = DstArg->getType();
7689   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7690                                                                     Context);
7691   if (!isKnownSizeArray) {
7692     if (PatternType == 1)
7693       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7694     else
7695       Diag(SL, diag::warn_strncat_src_size) << SR;
7696     return;
7697   }
7698 
7699   if (PatternType == 1)
7700     Diag(SL, diag::warn_strncat_large_size) << SR;
7701   else
7702     Diag(SL, diag::warn_strncat_src_size) << SR;
7703 
7704   SmallString<128> sizeString;
7705   llvm::raw_svector_ostream OS(sizeString);
7706   OS << "sizeof(";
7707   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7708   OS << ") - ";
7709   OS << "strlen(";
7710   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7711   OS << ") - 1";
7712 
7713   Diag(SL, diag::note_strncat_wrong_size)
7714     << FixItHint::CreateReplacement(SR, OS.str());
7715 }
7716 
7717 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7718 
7719 static const Expr *EvalVal(const Expr *E,
7720                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7721                            const Decl *ParentDecl);
7722 static const Expr *EvalAddr(const Expr *E,
7723                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7724                             const Decl *ParentDecl);
7725 
7726 /// CheckReturnStackAddr - Check if a return statement returns the address
7727 ///   of a stack variable.
7728 static void
7729 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7730                      SourceLocation ReturnLoc) {
7731   const Expr *stackE = nullptr;
7732   SmallVector<const DeclRefExpr *, 8> refVars;
7733 
7734   // Perform checking for returned stack addresses, local blocks,
7735   // label addresses or references to temporaries.
7736   if (lhsType->isPointerType() ||
7737       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7738     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7739   } else if (lhsType->isReferenceType()) {
7740     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7741   }
7742 
7743   if (!stackE)
7744     return; // Nothing suspicious was found.
7745 
7746   // Parameters are initialized in the calling scope, so taking the address
7747   // of a parameter reference doesn't need a warning.
7748   for (auto *DRE : refVars)
7749     if (isa<ParmVarDecl>(DRE->getDecl()))
7750       return;
7751 
7752   SourceLocation diagLoc;
7753   SourceRange diagRange;
7754   if (refVars.empty()) {
7755     diagLoc = stackE->getLocStart();
7756     diagRange = stackE->getSourceRange();
7757   } else {
7758     // We followed through a reference variable. 'stackE' contains the
7759     // problematic expression but we will warn at the return statement pointing
7760     // at the reference variable. We will later display the "trail" of
7761     // reference variables using notes.
7762     diagLoc = refVars[0]->getLocStart();
7763     diagRange = refVars[0]->getSourceRange();
7764   }
7765 
7766   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7767     // address of local var
7768     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7769      << DR->getDecl()->getDeclName() << diagRange;
7770   } else if (isa<BlockExpr>(stackE)) { // local block.
7771     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7772   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7773     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7774   } else { // local temporary.
7775     // If there is an LValue->RValue conversion, then the value of the
7776     // reference type is used, not the reference.
7777     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7778       if (ICE->getCastKind() == CK_LValueToRValue) {
7779         return;
7780       }
7781     }
7782     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7783      << lhsType->isReferenceType() << diagRange;
7784   }
7785 
7786   // Display the "trail" of reference variables that we followed until we
7787   // found the problematic expression using notes.
7788   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7789     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7790     // If this var binds to another reference var, show the range of the next
7791     // var, otherwise the var binds to the problematic expression, in which case
7792     // show the range of the expression.
7793     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7794                                     : stackE->getSourceRange();
7795     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7796         << VD->getDeclName() << range;
7797   }
7798 }
7799 
7800 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7801 ///  check if the expression in a return statement evaluates to an address
7802 ///  to a location on the stack, a local block, an address of a label, or a
7803 ///  reference to local temporary. The recursion is used to traverse the
7804 ///  AST of the return expression, with recursion backtracking when we
7805 ///  encounter a subexpression that (1) clearly does not lead to one of the
7806 ///  above problematic expressions (2) is something we cannot determine leads to
7807 ///  a problematic expression based on such local checking.
7808 ///
7809 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7810 ///  the expression that they point to. Such variables are added to the
7811 ///  'refVars' vector so that we know what the reference variable "trail" was.
7812 ///
7813 ///  EvalAddr processes expressions that are pointers that are used as
7814 ///  references (and not L-values).  EvalVal handles all other values.
7815 ///  At the base case of the recursion is a check for the above problematic
7816 ///  expressions.
7817 ///
7818 ///  This implementation handles:
7819 ///
7820 ///   * pointer-to-pointer casts
7821 ///   * implicit conversions from array references to pointers
7822 ///   * taking the address of fields
7823 ///   * arbitrary interplay between "&" and "*" operators
7824 ///   * pointer arithmetic from an address of a stack variable
7825 ///   * taking the address of an array element where the array is on the stack
7826 static const Expr *EvalAddr(const Expr *E,
7827                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7828                             const Decl *ParentDecl) {
7829   if (E->isTypeDependent())
7830     return nullptr;
7831 
7832   // We should only be called for evaluating pointer expressions.
7833   assert((E->getType()->isAnyPointerType() ||
7834           E->getType()->isBlockPointerType() ||
7835           E->getType()->isObjCQualifiedIdType()) &&
7836          "EvalAddr only works on pointers");
7837 
7838   E = E->IgnoreParens();
7839 
7840   // Our "symbolic interpreter" is just a dispatch off the currently
7841   // viewed AST node.  We then recursively traverse the AST by calling
7842   // EvalAddr and EvalVal appropriately.
7843   switch (E->getStmtClass()) {
7844   case Stmt::DeclRefExprClass: {
7845     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7846 
7847     // If we leave the immediate function, the lifetime isn't about to end.
7848     if (DR->refersToEnclosingVariableOrCapture())
7849       return nullptr;
7850 
7851     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7852       // If this is a reference variable, follow through to the expression that
7853       // it points to.
7854       if (V->hasLocalStorage() &&
7855           V->getType()->isReferenceType() && V->hasInit()) {
7856         // Add the reference variable to the "trail".
7857         refVars.push_back(DR);
7858         return EvalAddr(V->getInit(), refVars, ParentDecl);
7859       }
7860 
7861     return nullptr;
7862   }
7863 
7864   case Stmt::UnaryOperatorClass: {
7865     // The only unary operator that make sense to handle here
7866     // is AddrOf.  All others don't make sense as pointers.
7867     const UnaryOperator *U = cast<UnaryOperator>(E);
7868 
7869     if (U->getOpcode() == UO_AddrOf)
7870       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7871     return nullptr;
7872   }
7873 
7874   case Stmt::BinaryOperatorClass: {
7875     // Handle pointer arithmetic.  All other binary operators are not valid
7876     // in this context.
7877     const BinaryOperator *B = cast<BinaryOperator>(E);
7878     BinaryOperatorKind op = B->getOpcode();
7879 
7880     if (op != BO_Add && op != BO_Sub)
7881       return nullptr;
7882 
7883     const Expr *Base = B->getLHS();
7884 
7885     // Determine which argument is the real pointer base.  It could be
7886     // the RHS argument instead of the LHS.
7887     if (!Base->getType()->isPointerType())
7888       Base = B->getRHS();
7889 
7890     assert(Base->getType()->isPointerType());
7891     return EvalAddr(Base, refVars, ParentDecl);
7892   }
7893 
7894   // For conditional operators we need to see if either the LHS or RHS are
7895   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7896   case Stmt::ConditionalOperatorClass: {
7897     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7898 
7899     // Handle the GNU extension for missing LHS.
7900     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7901     if (const Expr *LHSExpr = C->getLHS()) {
7902       // In C++, we can have a throw-expression, which has 'void' type.
7903       if (!LHSExpr->getType()->isVoidType())
7904         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7905           return LHS;
7906     }
7907 
7908     // In C++, we can have a throw-expression, which has 'void' type.
7909     if (C->getRHS()->getType()->isVoidType())
7910       return nullptr;
7911 
7912     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7913   }
7914 
7915   case Stmt::BlockExprClass:
7916     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7917       return E; // local block.
7918     return nullptr;
7919 
7920   case Stmt::AddrLabelExprClass:
7921     return E; // address of label.
7922 
7923   case Stmt::ExprWithCleanupsClass:
7924     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7925                     ParentDecl);
7926 
7927   // For casts, we need to handle conversions from arrays to
7928   // pointer values, and pointer-to-pointer conversions.
7929   case Stmt::ImplicitCastExprClass:
7930   case Stmt::CStyleCastExprClass:
7931   case Stmt::CXXFunctionalCastExprClass:
7932   case Stmt::ObjCBridgedCastExprClass:
7933   case Stmt::CXXStaticCastExprClass:
7934   case Stmt::CXXDynamicCastExprClass:
7935   case Stmt::CXXConstCastExprClass:
7936   case Stmt::CXXReinterpretCastExprClass: {
7937     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7938     switch (cast<CastExpr>(E)->getCastKind()) {
7939     case CK_LValueToRValue:
7940     case CK_NoOp:
7941     case CK_BaseToDerived:
7942     case CK_DerivedToBase:
7943     case CK_UncheckedDerivedToBase:
7944     case CK_Dynamic:
7945     case CK_CPointerToObjCPointerCast:
7946     case CK_BlockPointerToObjCPointerCast:
7947     case CK_AnyPointerToBlockPointerCast:
7948       return EvalAddr(SubExpr, refVars, ParentDecl);
7949 
7950     case CK_ArrayToPointerDecay:
7951       return EvalVal(SubExpr, refVars, ParentDecl);
7952 
7953     case CK_BitCast:
7954       if (SubExpr->getType()->isAnyPointerType() ||
7955           SubExpr->getType()->isBlockPointerType() ||
7956           SubExpr->getType()->isObjCQualifiedIdType())
7957         return EvalAddr(SubExpr, refVars, ParentDecl);
7958       else
7959         return nullptr;
7960 
7961     default:
7962       return nullptr;
7963     }
7964   }
7965 
7966   case Stmt::MaterializeTemporaryExprClass:
7967     if (const Expr *Result =
7968             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7969                      refVars, ParentDecl))
7970       return Result;
7971     return E;
7972 
7973   // Everything else: we simply don't reason about them.
7974   default:
7975     return nullptr;
7976   }
7977 }
7978 
7979 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7980 ///   See the comments for EvalAddr for more details.
7981 static const Expr *EvalVal(const Expr *E,
7982                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7983                            const Decl *ParentDecl) {
7984   do {
7985     // We should only be called for evaluating non-pointer expressions, or
7986     // expressions with a pointer type that are not used as references but
7987     // instead
7988     // are l-values (e.g., DeclRefExpr with a pointer type).
7989 
7990     // Our "symbolic interpreter" is just a dispatch off the currently
7991     // viewed AST node.  We then recursively traverse the AST by calling
7992     // EvalAddr and EvalVal appropriately.
7993 
7994     E = E->IgnoreParens();
7995     switch (E->getStmtClass()) {
7996     case Stmt::ImplicitCastExprClass: {
7997       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7998       if (IE->getValueKind() == VK_LValue) {
7999         E = IE->getSubExpr();
8000         continue;
8001       }
8002       return nullptr;
8003     }
8004 
8005     case Stmt::ExprWithCleanupsClass:
8006       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
8007                      ParentDecl);
8008 
8009     case Stmt::DeclRefExprClass: {
8010       // When we hit a DeclRefExpr we are looking at code that refers to a
8011       // variable's name. If it's not a reference variable we check if it has
8012       // local storage within the function, and if so, return the expression.
8013       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
8014 
8015       // If we leave the immediate function, the lifetime isn't about to end.
8016       if (DR->refersToEnclosingVariableOrCapture())
8017         return nullptr;
8018 
8019       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
8020         // Check if it refers to itself, e.g. "int& i = i;".
8021         if (V == ParentDecl)
8022           return DR;
8023 
8024         if (V->hasLocalStorage()) {
8025           if (!V->getType()->isReferenceType())
8026             return DR;
8027 
8028           // Reference variable, follow through to the expression that
8029           // it points to.
8030           if (V->hasInit()) {
8031             // Add the reference variable to the "trail".
8032             refVars.push_back(DR);
8033             return EvalVal(V->getInit(), refVars, V);
8034           }
8035         }
8036       }
8037 
8038       return nullptr;
8039     }
8040 
8041     case Stmt::UnaryOperatorClass: {
8042       // The only unary operator that make sense to handle here
8043       // is Deref.  All others don't resolve to a "name."  This includes
8044       // handling all sorts of rvalues passed to a unary operator.
8045       const UnaryOperator *U = cast<UnaryOperator>(E);
8046 
8047       if (U->getOpcode() == UO_Deref)
8048         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
8049 
8050       return nullptr;
8051     }
8052 
8053     case Stmt::ArraySubscriptExprClass: {
8054       // Array subscripts are potential references to data on the stack.  We
8055       // retrieve the DeclRefExpr* for the array variable if it indeed
8056       // has local storage.
8057       const auto *ASE = cast<ArraySubscriptExpr>(E);
8058       if (ASE->isTypeDependent())
8059         return nullptr;
8060       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8061     }
8062 
8063     case Stmt::OMPArraySectionExprClass: {
8064       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8065                       ParentDecl);
8066     }
8067 
8068     case Stmt::ConditionalOperatorClass: {
8069       // For conditional operators we need to see if either the LHS or RHS are
8070       // non-NULL Expr's.  If one is non-NULL, we return it.
8071       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8072 
8073       // Handle the GNU extension for missing LHS.
8074       if (const Expr *LHSExpr = C->getLHS()) {
8075         // In C++, we can have a throw-expression, which has 'void' type.
8076         if (!LHSExpr->getType()->isVoidType())
8077           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8078             return LHS;
8079       }
8080 
8081       // In C++, we can have a throw-expression, which has 'void' type.
8082       if (C->getRHS()->getType()->isVoidType())
8083         return nullptr;
8084 
8085       return EvalVal(C->getRHS(), refVars, ParentDecl);
8086     }
8087 
8088     // Accesses to members are potential references to data on the stack.
8089     case Stmt::MemberExprClass: {
8090       const MemberExpr *M = cast<MemberExpr>(E);
8091 
8092       // Check for indirect access.  We only want direct field accesses.
8093       if (M->isArrow())
8094         return nullptr;
8095 
8096       // Check whether the member type is itself a reference, in which case
8097       // we're not going to refer to the member, but to what the member refers
8098       // to.
8099       if (M->getMemberDecl()->getType()->isReferenceType())
8100         return nullptr;
8101 
8102       return EvalVal(M->getBase(), refVars, ParentDecl);
8103     }
8104 
8105     case Stmt::MaterializeTemporaryExprClass:
8106       if (const Expr *Result =
8107               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8108                       refVars, ParentDecl))
8109         return Result;
8110       return E;
8111 
8112     default:
8113       // Check that we don't return or take the address of a reference to a
8114       // temporary. This is only useful in C++.
8115       if (!E->isTypeDependent() && E->isRValue())
8116         return E;
8117 
8118       // Everything else: we simply don't reason about them.
8119       return nullptr;
8120     }
8121   } while (true);
8122 }
8123 
8124 void
8125 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8126                          SourceLocation ReturnLoc,
8127                          bool isObjCMethod,
8128                          const AttrVec *Attrs,
8129                          const FunctionDecl *FD) {
8130   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8131 
8132   // Check if the return value is null but should not be.
8133   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8134        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8135       CheckNonNullExpr(*this, RetValExp))
8136     Diag(ReturnLoc, diag::warn_null_ret)
8137       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8138 
8139   // C++11 [basic.stc.dynamic.allocation]p4:
8140   //   If an allocation function declared with a non-throwing
8141   //   exception-specification fails to allocate storage, it shall return
8142   //   a null pointer. Any other allocation function that fails to allocate
8143   //   storage shall indicate failure only by throwing an exception [...]
8144   if (FD) {
8145     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8146     if (Op == OO_New || Op == OO_Array_New) {
8147       const FunctionProtoType *Proto
8148         = FD->getType()->castAs<FunctionProtoType>();
8149       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8150           CheckNonNullExpr(*this, RetValExp))
8151         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8152           << FD << getLangOpts().CPlusPlus11;
8153     }
8154   }
8155 }
8156 
8157 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8158 
8159 /// Check for comparisons of floating point operands using != and ==.
8160 /// Issue a warning if these are no self-comparisons, as they are not likely
8161 /// to do what the programmer intended.
8162 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8163   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8164   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8165 
8166   // Special case: check for x == x (which is OK).
8167   // Do not emit warnings for such cases.
8168   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8169     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8170       if (DRL->getDecl() == DRR->getDecl())
8171         return;
8172 
8173   // Special case: check for comparisons against literals that can be exactly
8174   //  represented by APFloat.  In such cases, do not emit a warning.  This
8175   //  is a heuristic: often comparison against such literals are used to
8176   //  detect if a value in a variable has not changed.  This clearly can
8177   //  lead to false negatives.
8178   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8179     if (FLL->isExact())
8180       return;
8181   } else
8182     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8183       if (FLR->isExact())
8184         return;
8185 
8186   // Check for comparisons with builtin types.
8187   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8188     if (CL->getBuiltinCallee())
8189       return;
8190 
8191   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8192     if (CR->getBuiltinCallee())
8193       return;
8194 
8195   // Emit the diagnostic.
8196   Diag(Loc, diag::warn_floatingpoint_eq)
8197     << LHS->getSourceRange() << RHS->getSourceRange();
8198 }
8199 
8200 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8201 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8202 
8203 namespace {
8204 
8205 /// Structure recording the 'active' range of an integer-valued
8206 /// expression.
8207 struct IntRange {
8208   /// The number of bits active in the int.
8209   unsigned Width;
8210 
8211   /// True if the int is known not to have negative values.
8212   bool NonNegative;
8213 
8214   IntRange(unsigned Width, bool NonNegative)
8215       : Width(Width), NonNegative(NonNegative) {}
8216 
8217   /// Returns the range of the bool type.
8218   static IntRange forBoolType() {
8219     return IntRange(1, true);
8220   }
8221 
8222   /// Returns the range of an opaque value of the given integral type.
8223   static IntRange forValueOfType(ASTContext &C, QualType T) {
8224     return forValueOfCanonicalType(C,
8225                           T->getCanonicalTypeInternal().getTypePtr());
8226   }
8227 
8228   /// Returns the range of an opaque value of a canonical integral type.
8229   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8230     assert(T->isCanonicalUnqualified());
8231 
8232     if (const VectorType *VT = dyn_cast<VectorType>(T))
8233       T = VT->getElementType().getTypePtr();
8234     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8235       T = CT->getElementType().getTypePtr();
8236     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8237       T = AT->getValueType().getTypePtr();
8238 
8239     if (!C.getLangOpts().CPlusPlus) {
8240       // For enum types in C code, use the underlying datatype.
8241       if (const EnumType *ET = dyn_cast<EnumType>(T))
8242         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8243     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8244       // For enum types in C++, use the known bit width of the enumerators.
8245       EnumDecl *Enum = ET->getDecl();
8246       // In C++11, enums can have a fixed underlying type. Use this type to
8247       // compute the range.
8248       if (Enum->isFixed()) {
8249         return IntRange(C.getIntWidth(QualType(T, 0)),
8250                         !ET->isSignedIntegerOrEnumerationType());
8251       }
8252 
8253       unsigned NumPositive = Enum->getNumPositiveBits();
8254       unsigned NumNegative = Enum->getNumNegativeBits();
8255 
8256       if (NumNegative == 0)
8257         return IntRange(NumPositive, true/*NonNegative*/);
8258       else
8259         return IntRange(std::max(NumPositive + 1, NumNegative),
8260                         false/*NonNegative*/);
8261     }
8262 
8263     const BuiltinType *BT = cast<BuiltinType>(T);
8264     assert(BT->isInteger());
8265 
8266     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8267   }
8268 
8269   /// Returns the "target" range of a canonical integral type, i.e.
8270   /// the range of values expressible in the type.
8271   ///
8272   /// This matches forValueOfCanonicalType except that enums have the
8273   /// full range of their type, not the range of their enumerators.
8274   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8275     assert(T->isCanonicalUnqualified());
8276 
8277     if (const VectorType *VT = dyn_cast<VectorType>(T))
8278       T = VT->getElementType().getTypePtr();
8279     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8280       T = CT->getElementType().getTypePtr();
8281     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8282       T = AT->getValueType().getTypePtr();
8283     if (const EnumType *ET = dyn_cast<EnumType>(T))
8284       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8285 
8286     const BuiltinType *BT = cast<BuiltinType>(T);
8287     assert(BT->isInteger());
8288 
8289     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8290   }
8291 
8292   /// Returns the supremum of two ranges: i.e. their conservative merge.
8293   static IntRange join(IntRange L, IntRange R) {
8294     return IntRange(std::max(L.Width, R.Width),
8295                     L.NonNegative && R.NonNegative);
8296   }
8297 
8298   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8299   static IntRange meet(IntRange L, IntRange R) {
8300     return IntRange(std::min(L.Width, R.Width),
8301                     L.NonNegative || R.NonNegative);
8302   }
8303 };
8304 
8305 } // namespace
8306 
8307 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
8308                               unsigned MaxWidth) {
8309   if (value.isSigned() && value.isNegative())
8310     return IntRange(value.getMinSignedBits(), false);
8311 
8312   if (value.getBitWidth() > MaxWidth)
8313     value = value.trunc(MaxWidth);
8314 
8315   // isNonNegative() just checks the sign bit without considering
8316   // signedness.
8317   return IntRange(value.getActiveBits(), true);
8318 }
8319 
8320 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8321                               unsigned MaxWidth) {
8322   if (result.isInt())
8323     return GetValueRange(C, result.getInt(), MaxWidth);
8324 
8325   if (result.isVector()) {
8326     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8327     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8328       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8329       R = IntRange::join(R, El);
8330     }
8331     return R;
8332   }
8333 
8334   if (result.isComplexInt()) {
8335     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8336     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8337     return IntRange::join(R, I);
8338   }
8339 
8340   // This can happen with lossless casts to intptr_t of "based" lvalues.
8341   // Assume it might use arbitrary bits.
8342   // FIXME: The only reason we need to pass the type in here is to get
8343   // the sign right on this one case.  It would be nice if APValue
8344   // preserved this.
8345   assert(result.isLValue() || result.isAddrLabelDiff());
8346   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8347 }
8348 
8349 static QualType GetExprType(const Expr *E) {
8350   QualType Ty = E->getType();
8351   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8352     Ty = AtomicRHS->getValueType();
8353   return Ty;
8354 }
8355 
8356 /// Pseudo-evaluate the given integer expression, estimating the
8357 /// range of values it might take.
8358 ///
8359 /// \param MaxWidth - the width to which the value will be truncated
8360 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8361   E = E->IgnoreParens();
8362 
8363   // Try a full evaluation first.
8364   Expr::EvalResult result;
8365   if (E->EvaluateAsRValue(result, C))
8366     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8367 
8368   // I think we only want to look through implicit casts here; if the
8369   // user has an explicit widening cast, we should treat the value as
8370   // being of the new, wider type.
8371   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8372     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8373       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8374 
8375     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8376 
8377     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8378                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8379 
8380     // Assume that non-integer casts can span the full range of the type.
8381     if (!isIntegerCast)
8382       return OutputTypeRange;
8383 
8384     IntRange SubRange
8385       = GetExprRange(C, CE->getSubExpr(),
8386                      std::min(MaxWidth, OutputTypeRange.Width));
8387 
8388     // Bail out if the subexpr's range is as wide as the cast type.
8389     if (SubRange.Width >= OutputTypeRange.Width)
8390       return OutputTypeRange;
8391 
8392     // Otherwise, we take the smaller width, and we're non-negative if
8393     // either the output type or the subexpr is.
8394     return IntRange(SubRange.Width,
8395                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8396   }
8397 
8398   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8399     // If we can fold the condition, just take that operand.
8400     bool CondResult;
8401     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8402       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8403                                         : CO->getFalseExpr(),
8404                           MaxWidth);
8405 
8406     // Otherwise, conservatively merge.
8407     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8408     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8409     return IntRange::join(L, R);
8410   }
8411 
8412   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8413     switch (BO->getOpcode()) {
8414     case BO_Cmp:
8415       llvm_unreachable("builtin <=> should have class type");
8416 
8417     // Boolean-valued operations are single-bit and positive.
8418     case BO_LAnd:
8419     case BO_LOr:
8420     case BO_LT:
8421     case BO_GT:
8422     case BO_LE:
8423     case BO_GE:
8424     case BO_EQ:
8425     case BO_NE:
8426       return IntRange::forBoolType();
8427 
8428     // The type of the assignments is the type of the LHS, so the RHS
8429     // is not necessarily the same type.
8430     case BO_MulAssign:
8431     case BO_DivAssign:
8432     case BO_RemAssign:
8433     case BO_AddAssign:
8434     case BO_SubAssign:
8435     case BO_XorAssign:
8436     case BO_OrAssign:
8437       // TODO: bitfields?
8438       return IntRange::forValueOfType(C, GetExprType(E));
8439 
8440     // Simple assignments just pass through the RHS, which will have
8441     // been coerced to the LHS type.
8442     case BO_Assign:
8443       // TODO: bitfields?
8444       return GetExprRange(C, BO->getRHS(), MaxWidth);
8445 
8446     // Operations with opaque sources are black-listed.
8447     case BO_PtrMemD:
8448     case BO_PtrMemI:
8449       return IntRange::forValueOfType(C, GetExprType(E));
8450 
8451     // Bitwise-and uses the *infinum* of the two source ranges.
8452     case BO_And:
8453     case BO_AndAssign:
8454       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8455                             GetExprRange(C, BO->getRHS(), MaxWidth));
8456 
8457     // Left shift gets black-listed based on a judgement call.
8458     case BO_Shl:
8459       // ...except that we want to treat '1 << (blah)' as logically
8460       // positive.  It's an important idiom.
8461       if (IntegerLiteral *I
8462             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8463         if (I->getValue() == 1) {
8464           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8465           return IntRange(R.Width, /*NonNegative*/ true);
8466         }
8467       }
8468       LLVM_FALLTHROUGH;
8469 
8470     case BO_ShlAssign:
8471       return IntRange::forValueOfType(C, GetExprType(E));
8472 
8473     // Right shift by a constant can narrow its left argument.
8474     case BO_Shr:
8475     case BO_ShrAssign: {
8476       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8477 
8478       // If the shift amount is a positive constant, drop the width by
8479       // that much.
8480       llvm::APSInt shift;
8481       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8482           shift.isNonNegative()) {
8483         unsigned zext = shift.getZExtValue();
8484         if (zext >= L.Width)
8485           L.Width = (L.NonNegative ? 0 : 1);
8486         else
8487           L.Width -= zext;
8488       }
8489 
8490       return L;
8491     }
8492 
8493     // Comma acts as its right operand.
8494     case BO_Comma:
8495       return GetExprRange(C, BO->getRHS(), MaxWidth);
8496 
8497     // Black-list pointer subtractions.
8498     case BO_Sub:
8499       if (BO->getLHS()->getType()->isPointerType())
8500         return IntRange::forValueOfType(C, GetExprType(E));
8501       break;
8502 
8503     // The width of a division result is mostly determined by the size
8504     // of the LHS.
8505     case BO_Div: {
8506       // Don't 'pre-truncate' the operands.
8507       unsigned opWidth = C.getIntWidth(GetExprType(E));
8508       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8509 
8510       // If the divisor is constant, use that.
8511       llvm::APSInt divisor;
8512       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8513         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8514         if (log2 >= L.Width)
8515           L.Width = (L.NonNegative ? 0 : 1);
8516         else
8517           L.Width = std::min(L.Width - log2, MaxWidth);
8518         return L;
8519       }
8520 
8521       // Otherwise, just use the LHS's width.
8522       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8523       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8524     }
8525 
8526     // The result of a remainder can't be larger than the result of
8527     // either side.
8528     case BO_Rem: {
8529       // Don't 'pre-truncate' the operands.
8530       unsigned opWidth = C.getIntWidth(GetExprType(E));
8531       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8532       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8533 
8534       IntRange meet = IntRange::meet(L, R);
8535       meet.Width = std::min(meet.Width, MaxWidth);
8536       return meet;
8537     }
8538 
8539     // The default behavior is okay for these.
8540     case BO_Mul:
8541     case BO_Add:
8542     case BO_Xor:
8543     case BO_Or:
8544       break;
8545     }
8546 
8547     // The default case is to treat the operation as if it were closed
8548     // on the narrowest type that encompasses both operands.
8549     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8550     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8551     return IntRange::join(L, R);
8552   }
8553 
8554   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8555     switch (UO->getOpcode()) {
8556     // Boolean-valued operations are white-listed.
8557     case UO_LNot:
8558       return IntRange::forBoolType();
8559 
8560     // Operations with opaque sources are black-listed.
8561     case UO_Deref:
8562     case UO_AddrOf: // should be impossible
8563       return IntRange::forValueOfType(C, GetExprType(E));
8564 
8565     default:
8566       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8567     }
8568   }
8569 
8570   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8571     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8572 
8573   if (const auto *BitField = E->getSourceBitField())
8574     return IntRange(BitField->getBitWidthValue(C),
8575                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8576 
8577   return IntRange::forValueOfType(C, GetExprType(E));
8578 }
8579 
8580 static IntRange GetExprRange(ASTContext &C, const Expr *E) {
8581   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8582 }
8583 
8584 /// Checks whether the given value, which currently has the given
8585 /// source semantics, has the same value when coerced through the
8586 /// target semantics.
8587 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
8588                                  const llvm::fltSemantics &Src,
8589                                  const llvm::fltSemantics &Tgt) {
8590   llvm::APFloat truncated = value;
8591 
8592   bool ignored;
8593   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8594   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8595 
8596   return truncated.bitwiseIsEqual(value);
8597 }
8598 
8599 /// Checks whether the given value, which currently has the given
8600 /// source semantics, has the same value when coerced through the
8601 /// target semantics.
8602 ///
8603 /// The value might be a vector of floats (or a complex number).
8604 static bool IsSameFloatAfterCast(const APValue &value,
8605                                  const llvm::fltSemantics &Src,
8606                                  const llvm::fltSemantics &Tgt) {
8607   if (value.isFloat())
8608     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8609 
8610   if (value.isVector()) {
8611     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8612       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8613         return false;
8614     return true;
8615   }
8616 
8617   assert(value.isComplexFloat());
8618   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8619           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8620 }
8621 
8622 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8623 
8624 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8625   // Suppress cases where we are comparing against an enum constant.
8626   if (const DeclRefExpr *DR =
8627       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8628     if (isa<EnumConstantDecl>(DR->getDecl()))
8629       return true;
8630 
8631   // Suppress cases where the '0' value is expanded from a macro.
8632   if (E->getLocStart().isMacroID())
8633     return true;
8634 
8635   return false;
8636 }
8637 
8638 static bool isKnownToHaveUnsignedValue(Expr *E) {
8639   return E->getType()->isIntegerType() &&
8640          (!E->getType()->isSignedIntegerType() ||
8641           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8642 }
8643 
8644 namespace {
8645 /// The promoted range of values of a type. In general this has the
8646 /// following structure:
8647 ///
8648 ///     |-----------| . . . |-----------|
8649 ///     ^           ^       ^           ^
8650 ///    Min       HoleMin  HoleMax      Max
8651 ///
8652 /// ... where there is only a hole if a signed type is promoted to unsigned
8653 /// (in which case Min and Max are the smallest and largest representable
8654 /// values).
8655 struct PromotedRange {
8656   // Min, or HoleMax if there is a hole.
8657   llvm::APSInt PromotedMin;
8658   // Max, or HoleMin if there is a hole.
8659   llvm::APSInt PromotedMax;
8660 
8661   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
8662     if (R.Width == 0)
8663       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
8664     else if (R.Width >= BitWidth && !Unsigned) {
8665       // Promotion made the type *narrower*. This happens when promoting
8666       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
8667       // Treat all values of 'signed int' as being in range for now.
8668       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
8669       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
8670     } else {
8671       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
8672                         .extOrTrunc(BitWidth);
8673       PromotedMin.setIsUnsigned(Unsigned);
8674 
8675       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
8676                         .extOrTrunc(BitWidth);
8677       PromotedMax.setIsUnsigned(Unsigned);
8678     }
8679   }
8680 
8681   // Determine whether this range is contiguous (has no hole).
8682   bool isContiguous() const { return PromotedMin <= PromotedMax; }
8683 
8684   // Where a constant value is within the range.
8685   enum ComparisonResult {
8686     LT = 0x1,
8687     LE = 0x2,
8688     GT = 0x4,
8689     GE = 0x8,
8690     EQ = 0x10,
8691     NE = 0x20,
8692     InRangeFlag = 0x40,
8693 
8694     Less = LE | LT | NE,
8695     Min = LE | InRangeFlag,
8696     InRange = InRangeFlag,
8697     Max = GE | InRangeFlag,
8698     Greater = GE | GT | NE,
8699 
8700     OnlyValue = LE | GE | EQ | InRangeFlag,
8701     InHole = NE
8702   };
8703 
8704   ComparisonResult compare(const llvm::APSInt &Value) const {
8705     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
8706            Value.isUnsigned() == PromotedMin.isUnsigned());
8707     if (!isContiguous()) {
8708       assert(Value.isUnsigned() && "discontiguous range for signed compare");
8709       if (Value.isMinValue()) return Min;
8710       if (Value.isMaxValue()) return Max;
8711       if (Value >= PromotedMin) return InRange;
8712       if (Value <= PromotedMax) return InRange;
8713       return InHole;
8714     }
8715 
8716     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
8717     case -1: return Less;
8718     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
8719     case 1:
8720       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
8721       case -1: return InRange;
8722       case 0: return Max;
8723       case 1: return Greater;
8724       }
8725     }
8726 
8727     llvm_unreachable("impossible compare result");
8728   }
8729 
8730   static llvm::Optional<StringRef>
8731   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
8732     if (Op == BO_Cmp) {
8733       ComparisonResult LTFlag = LT, GTFlag = GT;
8734       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
8735 
8736       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
8737       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
8738       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
8739       return llvm::None;
8740     }
8741 
8742     ComparisonResult TrueFlag, FalseFlag;
8743     if (Op == BO_EQ) {
8744       TrueFlag = EQ;
8745       FalseFlag = NE;
8746     } else if (Op == BO_NE) {
8747       TrueFlag = NE;
8748       FalseFlag = EQ;
8749     } else {
8750       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
8751         TrueFlag = LT;
8752         FalseFlag = GE;
8753       } else {
8754         TrueFlag = GT;
8755         FalseFlag = LE;
8756       }
8757       if (Op == BO_GE || Op == BO_LE)
8758         std::swap(TrueFlag, FalseFlag);
8759     }
8760     if (R & TrueFlag)
8761       return StringRef("true");
8762     if (R & FalseFlag)
8763       return StringRef("false");
8764     return llvm::None;
8765   }
8766 };
8767 }
8768 
8769 static bool HasEnumType(Expr *E) {
8770   // Strip off implicit integral promotions.
8771   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8772     if (ICE->getCastKind() != CK_IntegralCast &&
8773         ICE->getCastKind() != CK_NoOp)
8774       break;
8775     E = ICE->getSubExpr();
8776   }
8777 
8778   return E->getType()->isEnumeralType();
8779 }
8780 
8781 static int classifyConstantValue(Expr *Constant) {
8782   // The values of this enumeration are used in the diagnostics
8783   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
8784   enum ConstantValueKind {
8785     Miscellaneous = 0,
8786     LiteralTrue,
8787     LiteralFalse
8788   };
8789   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
8790     return BL->getValue() ? ConstantValueKind::LiteralTrue
8791                           : ConstantValueKind::LiteralFalse;
8792   return ConstantValueKind::Miscellaneous;
8793 }
8794 
8795 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
8796                                         Expr *Constant, Expr *Other,
8797                                         const llvm::APSInt &Value,
8798                                         bool RhsConstant) {
8799   if (S.inTemplateInstantiation())
8800     return false;
8801 
8802   Expr *OriginalOther = Other;
8803 
8804   Constant = Constant->IgnoreParenImpCasts();
8805   Other = Other->IgnoreParenImpCasts();
8806 
8807   // Suppress warnings on tautological comparisons between values of the same
8808   // enumeration type. There are only two ways we could warn on this:
8809   //  - If the constant is outside the range of representable values of
8810   //    the enumeration. In such a case, we should warn about the cast
8811   //    to enumeration type, not about the comparison.
8812   //  - If the constant is the maximum / minimum in-range value. For an
8813   //    enumeratin type, such comparisons can be meaningful and useful.
8814   if (Constant->getType()->isEnumeralType() &&
8815       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
8816     return false;
8817 
8818   // TODO: Investigate using GetExprRange() to get tighter bounds
8819   // on the bit ranges.
8820   QualType OtherT = Other->getType();
8821   if (const auto *AT = OtherT->getAs<AtomicType>())
8822     OtherT = AT->getValueType();
8823   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8824 
8825   // Whether we're treating Other as being a bool because of the form of
8826   // expression despite it having another type (typically 'int' in C).
8827   bool OtherIsBooleanDespiteType =
8828       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
8829   if (OtherIsBooleanDespiteType)
8830     OtherRange = IntRange::forBoolType();
8831 
8832   // Determine the promoted range of the other type and see if a comparison of
8833   // the constant against that range is tautological.
8834   PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(),
8835                                    Value.isUnsigned());
8836   auto Cmp = OtherPromotedRange.compare(Value);
8837   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
8838   if (!Result)
8839     return false;
8840 
8841   // Suppress the diagnostic for an in-range comparison if the constant comes
8842   // from a macro or enumerator. We don't want to diagnose
8843   //
8844   //   some_long_value <= INT_MAX
8845   //
8846   // when sizeof(int) == sizeof(long).
8847   bool InRange = Cmp & PromotedRange::InRangeFlag;
8848   if (InRange && IsEnumConstOrFromMacro(S, Constant))
8849     return false;
8850 
8851   // If this is a comparison to an enum constant, include that
8852   // constant in the diagnostic.
8853   const EnumConstantDecl *ED = nullptr;
8854   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8855     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8856 
8857   // Should be enough for uint128 (39 decimal digits)
8858   SmallString<64> PrettySourceValue;
8859   llvm::raw_svector_ostream OS(PrettySourceValue);
8860   if (ED)
8861     OS << '\'' << *ED << "' (" << Value << ")";
8862   else
8863     OS << Value;
8864 
8865   // FIXME: We use a somewhat different formatting for the in-range cases and
8866   // cases involving boolean values for historical reasons. We should pick a
8867   // consistent way of presenting these diagnostics.
8868   if (!InRange || Other->isKnownToHaveBooleanValue()) {
8869     S.DiagRuntimeBehavior(
8870       E->getOperatorLoc(), E,
8871       S.PDiag(!InRange ? diag::warn_out_of_range_compare
8872                        : diag::warn_tautological_bool_compare)
8873           << OS.str() << classifyConstantValue(Constant)
8874           << OtherT << OtherIsBooleanDespiteType << *Result
8875           << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8876   } else {
8877     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
8878                         ? (HasEnumType(OriginalOther)
8879                                ? diag::warn_unsigned_enum_always_true_comparison
8880                                : diag::warn_unsigned_always_true_comparison)
8881                         : diag::warn_tautological_constant_compare;
8882 
8883     S.Diag(E->getOperatorLoc(), Diag)
8884         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
8885         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8886   }
8887 
8888   return true;
8889 }
8890 
8891 /// Analyze the operands of the given comparison.  Implements the
8892 /// fallback case from AnalyzeComparison.
8893 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8894   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8895   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8896 }
8897 
8898 /// \brief Implements -Wsign-compare.
8899 ///
8900 /// \param E the binary operator to check for warnings
8901 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8902   // The type the comparison is being performed in.
8903   QualType T = E->getLHS()->getType();
8904 
8905   // Only analyze comparison operators where both sides have been converted to
8906   // the same type.
8907   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8908     return AnalyzeImpConvsInComparison(S, E);
8909 
8910   // Don't analyze value-dependent comparisons directly.
8911   if (E->isValueDependent())
8912     return AnalyzeImpConvsInComparison(S, E);
8913 
8914   Expr *LHS = E->getLHS();
8915   Expr *RHS = E->getRHS();
8916 
8917   if (T->isIntegralType(S.Context)) {
8918     llvm::APSInt RHSValue;
8919     llvm::APSInt LHSValue;
8920 
8921     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8922     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8923 
8924     // We don't care about expressions whose result is a constant.
8925     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8926       return AnalyzeImpConvsInComparison(S, E);
8927 
8928     // We only care about expressions where just one side is literal
8929     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8930       // Is the constant on the RHS or LHS?
8931       const bool RhsConstant = IsRHSIntegralLiteral;
8932       Expr *Const = RhsConstant ? RHS : LHS;
8933       Expr *Other = RhsConstant ? LHS : RHS;
8934       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8935 
8936       // Check whether an integer constant comparison results in a value
8937       // of 'true' or 'false'.
8938       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8939         return AnalyzeImpConvsInComparison(S, E);
8940     }
8941   }
8942 
8943   if (!T->hasUnsignedIntegerRepresentation()) {
8944     // We don't do anything special if this isn't an unsigned integral
8945     // comparison:  we're only interested in integral comparisons, and
8946     // signed comparisons only happen in cases we don't care to warn about.
8947     return AnalyzeImpConvsInComparison(S, E);
8948   }
8949 
8950   LHS = LHS->IgnoreParenImpCasts();
8951   RHS = RHS->IgnoreParenImpCasts();
8952 
8953   if (!S.getLangOpts().CPlusPlus) {
8954     // Avoid warning about comparison of integers with different signs when
8955     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
8956     // the type of `E`.
8957     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
8958       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8959     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
8960       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
8961   }
8962 
8963   // Check to see if one of the (unmodified) operands is of different
8964   // signedness.
8965   Expr *signedOperand, *unsignedOperand;
8966   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8967     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8968            "unsigned comparison between two signed integer expressions?");
8969     signedOperand = LHS;
8970     unsignedOperand = RHS;
8971   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8972     signedOperand = RHS;
8973     unsignedOperand = LHS;
8974   } else {
8975     return AnalyzeImpConvsInComparison(S, E);
8976   }
8977 
8978   // Otherwise, calculate the effective range of the signed operand.
8979   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8980 
8981   // Go ahead and analyze implicit conversions in the operands.  Note
8982   // that we skip the implicit conversions on both sides.
8983   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8984   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8985 
8986   // If the signed range is non-negative, -Wsign-compare won't fire.
8987   if (signedRange.NonNegative)
8988     return;
8989 
8990   // For (in)equality comparisons, if the unsigned operand is a
8991   // constant which cannot collide with a overflowed signed operand,
8992   // then reinterpreting the signed operand as unsigned will not
8993   // change the result of the comparison.
8994   if (E->isEqualityOp()) {
8995     unsigned comparisonWidth = S.Context.getIntWidth(T);
8996     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8997 
8998     // We should never be unable to prove that the unsigned operand is
8999     // non-negative.
9000     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9001 
9002     if (unsignedRange.Width < comparisonWidth)
9003       return;
9004   }
9005 
9006   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9007     S.PDiag(diag::warn_mixed_sign_comparison)
9008       << LHS->getType() << RHS->getType()
9009       << LHS->getSourceRange() << RHS->getSourceRange());
9010 }
9011 
9012 /// Analyzes an attempt to assign the given value to a bitfield.
9013 ///
9014 /// Returns true if there was something fishy about the attempt.
9015 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9016                                       SourceLocation InitLoc) {
9017   assert(Bitfield->isBitField());
9018   if (Bitfield->isInvalidDecl())
9019     return false;
9020 
9021   // White-list bool bitfields.
9022   QualType BitfieldType = Bitfield->getType();
9023   if (BitfieldType->isBooleanType())
9024      return false;
9025 
9026   if (BitfieldType->isEnumeralType()) {
9027     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9028     // If the underlying enum type was not explicitly specified as an unsigned
9029     // type and the enum contain only positive values, MSVC++ will cause an
9030     // inconsistency by storing this as a signed type.
9031     if (S.getLangOpts().CPlusPlus11 &&
9032         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9033         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9034         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9035       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9036         << BitfieldEnumDecl->getNameAsString();
9037     }
9038   }
9039 
9040   if (Bitfield->getType()->isBooleanType())
9041     return false;
9042 
9043   // Ignore value- or type-dependent expressions.
9044   if (Bitfield->getBitWidth()->isValueDependent() ||
9045       Bitfield->getBitWidth()->isTypeDependent() ||
9046       Init->isValueDependent() ||
9047       Init->isTypeDependent())
9048     return false;
9049 
9050   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9051   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9052 
9053   llvm::APSInt Value;
9054   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9055                                    Expr::SE_AllowSideEffects)) {
9056     // The RHS is not constant.  If the RHS has an enum type, make sure the
9057     // bitfield is wide enough to hold all the values of the enum without
9058     // truncation.
9059     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9060       EnumDecl *ED = EnumTy->getDecl();
9061       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9062 
9063       // Enum types are implicitly signed on Windows, so check if there are any
9064       // negative enumerators to see if the enum was intended to be signed or
9065       // not.
9066       bool SignedEnum = ED->getNumNegativeBits() > 0;
9067 
9068       // Check for surprising sign changes when assigning enum values to a
9069       // bitfield of different signedness.  If the bitfield is signed and we
9070       // have exactly the right number of bits to store this unsigned enum,
9071       // suggest changing the enum to an unsigned type. This typically happens
9072       // on Windows where unfixed enums always use an underlying type of 'int'.
9073       unsigned DiagID = 0;
9074       if (SignedEnum && !SignedBitfield) {
9075         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9076       } else if (SignedBitfield && !SignedEnum &&
9077                  ED->getNumPositiveBits() == FieldWidth) {
9078         DiagID = diag::warn_signed_bitfield_enum_conversion;
9079       }
9080 
9081       if (DiagID) {
9082         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9083         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9084         SourceRange TypeRange =
9085             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9086         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9087             << SignedEnum << TypeRange;
9088       }
9089 
9090       // Compute the required bitwidth. If the enum has negative values, we need
9091       // one more bit than the normal number of positive bits to represent the
9092       // sign bit.
9093       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9094                                                   ED->getNumNegativeBits())
9095                                        : ED->getNumPositiveBits();
9096 
9097       // Check the bitwidth.
9098       if (BitsNeeded > FieldWidth) {
9099         Expr *WidthExpr = Bitfield->getBitWidth();
9100         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9101             << Bitfield << ED;
9102         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9103             << BitsNeeded << ED << WidthExpr->getSourceRange();
9104       }
9105     }
9106 
9107     return false;
9108   }
9109 
9110   unsigned OriginalWidth = Value.getBitWidth();
9111 
9112   if (!Value.isSigned() || Value.isNegative())
9113     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9114       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9115         OriginalWidth = Value.getMinSignedBits();
9116 
9117   if (OriginalWidth <= FieldWidth)
9118     return false;
9119 
9120   // Compute the value which the bitfield will contain.
9121   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9122   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9123 
9124   // Check whether the stored value is equal to the original value.
9125   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9126   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9127     return false;
9128 
9129   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9130   // therefore don't strictly fit into a signed bitfield of width 1.
9131   if (FieldWidth == 1 && Value == 1)
9132     return false;
9133 
9134   std::string PrettyValue = Value.toString(10);
9135   std::string PrettyTrunc = TruncatedValue.toString(10);
9136 
9137   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9138     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9139     << Init->getSourceRange();
9140 
9141   return true;
9142 }
9143 
9144 /// Analyze the given simple or compound assignment for warning-worthy
9145 /// operations.
9146 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9147   // Just recurse on the LHS.
9148   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9149 
9150   // We want to recurse on the RHS as normal unless we're assigning to
9151   // a bitfield.
9152   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9153     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9154                                   E->getOperatorLoc())) {
9155       // Recurse, ignoring any implicit conversions on the RHS.
9156       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9157                                         E->getOperatorLoc());
9158     }
9159   }
9160 
9161   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9162 }
9163 
9164 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9165 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9166                             SourceLocation CContext, unsigned diag,
9167                             bool pruneControlFlow = false) {
9168   if (pruneControlFlow) {
9169     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9170                           S.PDiag(diag)
9171                             << SourceType << T << E->getSourceRange()
9172                             << SourceRange(CContext));
9173     return;
9174   }
9175   S.Diag(E->getExprLoc(), diag)
9176     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9177 }
9178 
9179 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9180 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
9181                             SourceLocation CContext,
9182                             unsigned diag, bool pruneControlFlow = false) {
9183   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9184 }
9185 
9186 
9187 /// Diagnose an implicit cast from a floating point value to an integer value.
9188 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9189                                     SourceLocation CContext) {
9190   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9191   const bool PruneWarnings = S.inTemplateInstantiation();
9192 
9193   Expr *InnerE = E->IgnoreParenImpCasts();
9194   // We also want to warn on, e.g., "int i = -1.234"
9195   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9196     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9197       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9198 
9199   const bool IsLiteral =
9200       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9201 
9202   llvm::APFloat Value(0.0);
9203   bool IsConstant =
9204     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9205   if (!IsConstant) {
9206     return DiagnoseImpCast(S, E, T, CContext,
9207                            diag::warn_impcast_float_integer, PruneWarnings);
9208   }
9209 
9210   bool isExact = false;
9211 
9212   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9213                             T->hasUnsignedIntegerRepresentation());
9214   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9215                              &isExact) == llvm::APFloat::opOK &&
9216       isExact) {
9217     if (IsLiteral) return;
9218     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9219                            PruneWarnings);
9220   }
9221 
9222   unsigned DiagID = 0;
9223   if (IsLiteral) {
9224     // Warn on floating point literal to integer.
9225     DiagID = diag::warn_impcast_literal_float_to_integer;
9226   } else if (IntegerValue == 0) {
9227     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9228       return DiagnoseImpCast(S, E, T, CContext,
9229                              diag::warn_impcast_float_integer, PruneWarnings);
9230     }
9231     // Warn on non-zero to zero conversion.
9232     DiagID = diag::warn_impcast_float_to_integer_zero;
9233   } else {
9234     if (IntegerValue.isUnsigned()) {
9235       if (!IntegerValue.isMaxValue()) {
9236         return DiagnoseImpCast(S, E, T, CContext,
9237                                diag::warn_impcast_float_integer, PruneWarnings);
9238       }
9239     } else {  // IntegerValue.isSigned()
9240       if (!IntegerValue.isMaxSignedValue() &&
9241           !IntegerValue.isMinSignedValue()) {
9242         return DiagnoseImpCast(S, E, T, CContext,
9243                                diag::warn_impcast_float_integer, PruneWarnings);
9244       }
9245     }
9246     // Warn on evaluatable floating point expression to integer conversion.
9247     DiagID = diag::warn_impcast_float_to_integer;
9248   }
9249 
9250   // FIXME: Force the precision of the source value down so we don't print
9251   // digits which are usually useless (we don't really care here if we
9252   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9253   // would automatically print the shortest representation, but it's a bit
9254   // tricky to implement.
9255   SmallString<16> PrettySourceValue;
9256   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9257   precision = (precision * 59 + 195) / 196;
9258   Value.toString(PrettySourceValue, precision);
9259 
9260   SmallString<16> PrettyTargetValue;
9261   if (IsBool)
9262     PrettyTargetValue = Value.isZero() ? "false" : "true";
9263   else
9264     IntegerValue.toString(PrettyTargetValue);
9265 
9266   if (PruneWarnings) {
9267     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9268                           S.PDiag(DiagID)
9269                               << E->getType() << T.getUnqualifiedType()
9270                               << PrettySourceValue << PrettyTargetValue
9271                               << E->getSourceRange() << SourceRange(CContext));
9272   } else {
9273     S.Diag(E->getExprLoc(), DiagID)
9274         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9275         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9276   }
9277 }
9278 
9279 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
9280                                       IntRange Range) {
9281   if (!Range.Width) return "0";
9282 
9283   llvm::APSInt ValueInRange = Value;
9284   ValueInRange.setIsSigned(!Range.NonNegative);
9285   ValueInRange = ValueInRange.trunc(Range.Width);
9286   return ValueInRange.toString(10);
9287 }
9288 
9289 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9290   if (!isa<ImplicitCastExpr>(Ex))
9291     return false;
9292 
9293   Expr *InnerE = Ex->IgnoreParenImpCasts();
9294   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9295   const Type *Source =
9296     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9297   if (Target->isDependentType())
9298     return false;
9299 
9300   const BuiltinType *FloatCandidateBT =
9301     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9302   const Type *BoolCandidateType = ToBool ? Target : Source;
9303 
9304   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9305           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9306 }
9307 
9308 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9309                                              SourceLocation CC) {
9310   unsigned NumArgs = TheCall->getNumArgs();
9311   for (unsigned i = 0; i < NumArgs; ++i) {
9312     Expr *CurrA = TheCall->getArg(i);
9313     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9314       continue;
9315 
9316     bool IsSwapped = ((i > 0) &&
9317         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9318     IsSwapped |= ((i < (NumArgs - 1)) &&
9319         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9320     if (IsSwapped) {
9321       // Warn on this floating-point to bool conversion.
9322       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9323                       CurrA->getType(), CC,
9324                       diag::warn_impcast_floating_point_to_bool);
9325     }
9326   }
9327 }
9328 
9329 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
9330                                    SourceLocation CC) {
9331   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9332                         E->getExprLoc()))
9333     return;
9334 
9335   // Don't warn on functions which have return type nullptr_t.
9336   if (isa<CallExpr>(E))
9337     return;
9338 
9339   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9340   const Expr::NullPointerConstantKind NullKind =
9341       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9342   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9343     return;
9344 
9345   // Return if target type is a safe conversion.
9346   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9347       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9348     return;
9349 
9350   SourceLocation Loc = E->getSourceRange().getBegin();
9351 
9352   // Venture through the macro stacks to get to the source of macro arguments.
9353   // The new location is a better location than the complete location that was
9354   // passed in.
9355   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
9356   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
9357 
9358   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9359   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9360     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9361         Loc, S.SourceMgr, S.getLangOpts());
9362     if (MacroName == "NULL")
9363       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9364   }
9365 
9366   // Only warn if the null and context location are in the same macro expansion.
9367   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9368     return;
9369 
9370   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9371       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
9372       << FixItHint::CreateReplacement(Loc,
9373                                       S.getFixItZeroLiteralForType(T, Loc));
9374 }
9375 
9376 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9377                                   ObjCArrayLiteral *ArrayLiteral);
9378 
9379 static void
9380 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9381                            ObjCDictionaryLiteral *DictionaryLiteral);
9382 
9383 /// Check a single element within a collection literal against the
9384 /// target element type.
9385 static void checkObjCCollectionLiteralElement(Sema &S,
9386                                               QualType TargetElementType,
9387                                               Expr *Element,
9388                                               unsigned ElementKind) {
9389   // Skip a bitcast to 'id' or qualified 'id'.
9390   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9391     if (ICE->getCastKind() == CK_BitCast &&
9392         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9393       Element = ICE->getSubExpr();
9394   }
9395 
9396   QualType ElementType = Element->getType();
9397   ExprResult ElementResult(Element);
9398   if (ElementType->getAs<ObjCObjectPointerType>() &&
9399       S.CheckSingleAssignmentConstraints(TargetElementType,
9400                                          ElementResult,
9401                                          false, false)
9402         != Sema::Compatible) {
9403     S.Diag(Element->getLocStart(),
9404            diag::warn_objc_collection_literal_element)
9405       << ElementType << ElementKind << TargetElementType
9406       << Element->getSourceRange();
9407   }
9408 
9409   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9410     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9411   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9412     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9413 }
9414 
9415 /// Check an Objective-C array literal being converted to the given
9416 /// target type.
9417 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9418                                   ObjCArrayLiteral *ArrayLiteral) {
9419   if (!S.NSArrayDecl)
9420     return;
9421 
9422   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9423   if (!TargetObjCPtr)
9424     return;
9425 
9426   if (TargetObjCPtr->isUnspecialized() ||
9427       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9428         != S.NSArrayDecl->getCanonicalDecl())
9429     return;
9430 
9431   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9432   if (TypeArgs.size() != 1)
9433     return;
9434 
9435   QualType TargetElementType = TypeArgs[0];
9436   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9437     checkObjCCollectionLiteralElement(S, TargetElementType,
9438                                       ArrayLiteral->getElement(I),
9439                                       0);
9440   }
9441 }
9442 
9443 /// Check an Objective-C dictionary literal being converted to the given
9444 /// target type.
9445 static void
9446 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9447                            ObjCDictionaryLiteral *DictionaryLiteral) {
9448   if (!S.NSDictionaryDecl)
9449     return;
9450 
9451   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9452   if (!TargetObjCPtr)
9453     return;
9454 
9455   if (TargetObjCPtr->isUnspecialized() ||
9456       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9457         != S.NSDictionaryDecl->getCanonicalDecl())
9458     return;
9459 
9460   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9461   if (TypeArgs.size() != 2)
9462     return;
9463 
9464   QualType TargetKeyType = TypeArgs[0];
9465   QualType TargetObjectType = TypeArgs[1];
9466   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9467     auto Element = DictionaryLiteral->getKeyValueElement(I);
9468     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9469     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9470   }
9471 }
9472 
9473 // Helper function to filter out cases for constant width constant conversion.
9474 // Don't warn on char array initialization or for non-decimal values.
9475 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9476                                           SourceLocation CC) {
9477   // If initializing from a constant, and the constant starts with '0',
9478   // then it is a binary, octal, or hexadecimal.  Allow these constants
9479   // to fill all the bits, even if there is a sign change.
9480   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9481     const char FirstLiteralCharacter =
9482         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9483     if (FirstLiteralCharacter == '0')
9484       return false;
9485   }
9486 
9487   // If the CC location points to a '{', and the type is char, then assume
9488   // assume it is an array initialization.
9489   if (CC.isValid() && T->isCharType()) {
9490     const char FirstContextCharacter =
9491         S.getSourceManager().getCharacterData(CC)[0];
9492     if (FirstContextCharacter == '{')
9493       return false;
9494   }
9495 
9496   return true;
9497 }
9498 
9499 static void
9500 CheckImplicitConversion(Sema &S, Expr *E, QualType T, SourceLocation CC,
9501                         bool *ICContext = nullptr) {
9502   if (E->isTypeDependent() || E->isValueDependent()) return;
9503 
9504   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9505   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9506   if (Source == Target) return;
9507   if (Target->isDependentType()) return;
9508 
9509   // If the conversion context location is invalid don't complain. We also
9510   // don't want to emit a warning if the issue occurs from the expansion of
9511   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9512   // delay this check as long as possible. Once we detect we are in that
9513   // scenario, we just return.
9514   if (CC.isInvalid())
9515     return;
9516 
9517   // Diagnose implicit casts to bool.
9518   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9519     if (isa<StringLiteral>(E))
9520       // Warn on string literal to bool.  Checks for string literals in logical
9521       // and expressions, for instance, assert(0 && "error here"), are
9522       // prevented by a check in AnalyzeImplicitConversions().
9523       return DiagnoseImpCast(S, E, T, CC,
9524                              diag::warn_impcast_string_literal_to_bool);
9525     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9526         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9527       // This covers the literal expressions that evaluate to Objective-C
9528       // objects.
9529       return DiagnoseImpCast(S, E, T, CC,
9530                              diag::warn_impcast_objective_c_literal_to_bool);
9531     }
9532     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9533       // Warn on pointer to bool conversion that is always true.
9534       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9535                                      SourceRange(CC));
9536     }
9537   }
9538 
9539   // Check implicit casts from Objective-C collection literals to specialized
9540   // collection types, e.g., NSArray<NSString *> *.
9541   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9542     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9543   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9544     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9545 
9546   // Strip vector types.
9547   if (isa<VectorType>(Source)) {
9548     if (!isa<VectorType>(Target)) {
9549       if (S.SourceMgr.isInSystemMacro(CC))
9550         return;
9551       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9552     }
9553 
9554     // If the vector cast is cast between two vectors of the same size, it is
9555     // a bitcast, not a conversion.
9556     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9557       return;
9558 
9559     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9560     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9561   }
9562   if (auto VecTy = dyn_cast<VectorType>(Target))
9563     Target = VecTy->getElementType().getTypePtr();
9564 
9565   // Strip complex types.
9566   if (isa<ComplexType>(Source)) {
9567     if (!isa<ComplexType>(Target)) {
9568       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9569         return;
9570 
9571       return DiagnoseImpCast(S, E, T, CC,
9572                              S.getLangOpts().CPlusPlus
9573                                  ? diag::err_impcast_complex_scalar
9574                                  : diag::warn_impcast_complex_scalar);
9575     }
9576 
9577     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9578     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9579   }
9580 
9581   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9582   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9583 
9584   // If the source is floating point...
9585   if (SourceBT && SourceBT->isFloatingPoint()) {
9586     // ...and the target is floating point...
9587     if (TargetBT && TargetBT->isFloatingPoint()) {
9588       // ...then warn if we're dropping FP rank.
9589 
9590       // Builtin FP kinds are ordered by increasing FP rank.
9591       if (SourceBT->getKind() > TargetBT->getKind()) {
9592         // Don't warn about float constants that are precisely
9593         // representable in the target type.
9594         Expr::EvalResult result;
9595         if (E->EvaluateAsRValue(result, S.Context)) {
9596           // Value might be a float, a float vector, or a float complex.
9597           if (IsSameFloatAfterCast(result.Val,
9598                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9599                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9600             return;
9601         }
9602 
9603         if (S.SourceMgr.isInSystemMacro(CC))
9604           return;
9605 
9606         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9607       }
9608       // ... or possibly if we're increasing rank, too
9609       else if (TargetBT->getKind() > SourceBT->getKind()) {
9610         if (S.SourceMgr.isInSystemMacro(CC))
9611           return;
9612 
9613         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9614       }
9615       return;
9616     }
9617 
9618     // If the target is integral, always warn.
9619     if (TargetBT && TargetBT->isInteger()) {
9620       if (S.SourceMgr.isInSystemMacro(CC))
9621         return;
9622 
9623       DiagnoseFloatingImpCast(S, E, T, CC);
9624     }
9625 
9626     // Detect the case where a call result is converted from floating-point to
9627     // to bool, and the final argument to the call is converted from bool, to
9628     // discover this typo:
9629     //
9630     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9631     //
9632     // FIXME: This is an incredibly special case; is there some more general
9633     // way to detect this class of misplaced-parentheses bug?
9634     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9635       // Check last argument of function call to see if it is an
9636       // implicit cast from a type matching the type the result
9637       // is being cast to.
9638       CallExpr *CEx = cast<CallExpr>(E);
9639       if (unsigned NumArgs = CEx->getNumArgs()) {
9640         Expr *LastA = CEx->getArg(NumArgs - 1);
9641         Expr *InnerE = LastA->IgnoreParenImpCasts();
9642         if (isa<ImplicitCastExpr>(LastA) &&
9643             InnerE->getType()->isBooleanType()) {
9644           // Warn on this floating-point to bool conversion
9645           DiagnoseImpCast(S, E, T, CC,
9646                           diag::warn_impcast_floating_point_to_bool);
9647         }
9648       }
9649     }
9650     return;
9651   }
9652 
9653   DiagnoseNullConversion(S, E, T, CC);
9654 
9655   S.DiscardMisalignedMemberAddress(Target, E);
9656 
9657   if (!Source->isIntegerType() || !Target->isIntegerType())
9658     return;
9659 
9660   // TODO: remove this early return once the false positives for constant->bool
9661   // in templates, macros, etc, are reduced or removed.
9662   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9663     return;
9664 
9665   IntRange SourceRange = GetExprRange(S.Context, E);
9666   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9667 
9668   if (SourceRange.Width > TargetRange.Width) {
9669     // If the source is a constant, use a default-on diagnostic.
9670     // TODO: this should happen for bitfield stores, too.
9671     llvm::APSInt Value(32);
9672     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9673       if (S.SourceMgr.isInSystemMacro(CC))
9674         return;
9675 
9676       std::string PrettySourceValue = Value.toString(10);
9677       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9678 
9679       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9680         S.PDiag(diag::warn_impcast_integer_precision_constant)
9681             << PrettySourceValue << PrettyTargetValue
9682             << E->getType() << T << E->getSourceRange()
9683             << clang::SourceRange(CC));
9684       return;
9685     }
9686 
9687     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9688     if (S.SourceMgr.isInSystemMacro(CC))
9689       return;
9690 
9691     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9692       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9693                              /* pruneControlFlow */ true);
9694     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9695   }
9696 
9697   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9698       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9699     // Warn when doing a signed to signed conversion, warn if the positive
9700     // source value is exactly the width of the target type, which will
9701     // cause a negative value to be stored.
9702 
9703     llvm::APSInt Value;
9704     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9705         !S.SourceMgr.isInSystemMacro(CC)) {
9706       if (isSameWidthConstantConversion(S, E, T, CC)) {
9707         std::string PrettySourceValue = Value.toString(10);
9708         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9709 
9710         S.DiagRuntimeBehavior(
9711             E->getExprLoc(), E,
9712             S.PDiag(diag::warn_impcast_integer_precision_constant)
9713                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9714                 << E->getSourceRange() << clang::SourceRange(CC));
9715         return;
9716       }
9717     }
9718 
9719     // Fall through for non-constants to give a sign conversion warning.
9720   }
9721 
9722   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9723       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9724        SourceRange.Width == TargetRange.Width)) {
9725     if (S.SourceMgr.isInSystemMacro(CC))
9726       return;
9727 
9728     unsigned DiagID = diag::warn_impcast_integer_sign;
9729 
9730     // Traditionally, gcc has warned about this under -Wsign-compare.
9731     // We also want to warn about it in -Wconversion.
9732     // So if -Wconversion is off, use a completely identical diagnostic
9733     // in the sign-compare group.
9734     // The conditional-checking code will
9735     if (ICContext) {
9736       DiagID = diag::warn_impcast_integer_sign_conditional;
9737       *ICContext = true;
9738     }
9739 
9740     return DiagnoseImpCast(S, E, T, CC, DiagID);
9741   }
9742 
9743   // Diagnose conversions between different enumeration types.
9744   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9745   // type, to give us better diagnostics.
9746   QualType SourceType = E->getType();
9747   if (!S.getLangOpts().CPlusPlus) {
9748     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9749       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9750         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9751         SourceType = S.Context.getTypeDeclType(Enum);
9752         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9753       }
9754   }
9755 
9756   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9757     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9758       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9759           TargetEnum->getDecl()->hasNameForLinkage() &&
9760           SourceEnum != TargetEnum) {
9761         if (S.SourceMgr.isInSystemMacro(CC))
9762           return;
9763 
9764         return DiagnoseImpCast(S, E, SourceType, T, CC,
9765                                diag::warn_impcast_different_enum_types);
9766       }
9767 }
9768 
9769 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9770                                      SourceLocation CC, QualType T);
9771 
9772 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9773                                     SourceLocation CC, bool &ICContext) {
9774   E = E->IgnoreParenImpCasts();
9775 
9776   if (isa<ConditionalOperator>(E))
9777     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9778 
9779   AnalyzeImplicitConversions(S, E, CC);
9780   if (E->getType() != T)
9781     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9782 }
9783 
9784 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9785                                      SourceLocation CC, QualType T) {
9786   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9787 
9788   bool Suspicious = false;
9789   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9790   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9791 
9792   // If -Wconversion would have warned about either of the candidates
9793   // for a signedness conversion to the context type...
9794   if (!Suspicious) return;
9795 
9796   // ...but it's currently ignored...
9797   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9798     return;
9799 
9800   // ...then check whether it would have warned about either of the
9801   // candidates for a signedness conversion to the condition type.
9802   if (E->getType() == T) return;
9803 
9804   Suspicious = false;
9805   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9806                           E->getType(), CC, &Suspicious);
9807   if (!Suspicious)
9808     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9809                             E->getType(), CC, &Suspicious);
9810 }
9811 
9812 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9813 /// Input argument E is a logical expression.
9814 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9815   if (S.getLangOpts().Bool)
9816     return;
9817   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9818 }
9819 
9820 /// AnalyzeImplicitConversions - Find and report any interesting
9821 /// implicit conversions in the given expression.  There are a couple
9822 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9823 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE,
9824                                        SourceLocation CC) {
9825   QualType T = OrigE->getType();
9826   Expr *E = OrigE->IgnoreParenImpCasts();
9827 
9828   if (E->isTypeDependent() || E->isValueDependent())
9829     return;
9830 
9831   // For conditional operators, we analyze the arguments as if they
9832   // were being fed directly into the output.
9833   if (isa<ConditionalOperator>(E)) {
9834     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9835     CheckConditionalOperator(S, CO, CC, T);
9836     return;
9837   }
9838 
9839   // Check implicit argument conversions for function calls.
9840   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9841     CheckImplicitArgumentConversions(S, Call, CC);
9842 
9843   // Go ahead and check any implicit conversions we might have skipped.
9844   // The non-canonical typecheck is just an optimization;
9845   // CheckImplicitConversion will filter out dead implicit conversions.
9846   if (E->getType() != T)
9847     CheckImplicitConversion(S, E, T, CC);
9848 
9849   // Now continue drilling into this expression.
9850 
9851   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9852     // The bound subexpressions in a PseudoObjectExpr are not reachable
9853     // as transitive children.
9854     // FIXME: Use a more uniform representation for this.
9855     for (auto *SE : POE->semantics())
9856       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9857         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9858   }
9859 
9860   // Skip past explicit casts.
9861   if (isa<ExplicitCastExpr>(E)) {
9862     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9863     return AnalyzeImplicitConversions(S, E, CC);
9864   }
9865 
9866   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9867     // Do a somewhat different check with comparison operators.
9868     if (BO->isComparisonOp())
9869       return AnalyzeComparison(S, BO);
9870 
9871     // And with simple assignments.
9872     if (BO->getOpcode() == BO_Assign)
9873       return AnalyzeAssignment(S, BO);
9874   }
9875 
9876   // These break the otherwise-useful invariant below.  Fortunately,
9877   // we don't really need to recurse into them, because any internal
9878   // expressions should have been analyzed already when they were
9879   // built into statements.
9880   if (isa<StmtExpr>(E)) return;
9881 
9882   // Don't descend into unevaluated contexts.
9883   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9884 
9885   // Now just recurse over the expression's children.
9886   CC = E->getExprLoc();
9887   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9888   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9889   for (Stmt *SubStmt : E->children()) {
9890     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9891     if (!ChildExpr)
9892       continue;
9893 
9894     if (IsLogicalAndOperator &&
9895         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9896       // Ignore checking string literals that are in logical and operators.
9897       // This is a common pattern for asserts.
9898       continue;
9899     AnalyzeImplicitConversions(S, ChildExpr, CC);
9900   }
9901 
9902   if (BO && BO->isLogicalOp()) {
9903     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9904     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9905       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9906 
9907     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9908     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9909       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9910   }
9911 
9912   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9913     if (U->getOpcode() == UO_LNot)
9914       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9915 }
9916 
9917 /// Diagnose integer type and any valid implicit convertion to it.
9918 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9919   // Taking into account implicit conversions,
9920   // allow any integer.
9921   if (!E->getType()->isIntegerType()) {
9922     S.Diag(E->getLocStart(),
9923            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9924     return true;
9925   }
9926   // Potentially emit standard warnings for implicit conversions if enabled
9927   // using -Wconversion.
9928   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9929   return false;
9930 }
9931 
9932 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9933 // Returns true when emitting a warning about taking the address of a reference.
9934 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9935                               const PartialDiagnostic &PD) {
9936   E = E->IgnoreParenImpCasts();
9937 
9938   const FunctionDecl *FD = nullptr;
9939 
9940   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9941     if (!DRE->getDecl()->getType()->isReferenceType())
9942       return false;
9943   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9944     if (!M->getMemberDecl()->getType()->isReferenceType())
9945       return false;
9946   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9947     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9948       return false;
9949     FD = Call->getDirectCallee();
9950   } else {
9951     return false;
9952   }
9953 
9954   SemaRef.Diag(E->getExprLoc(), PD);
9955 
9956   // If possible, point to location of function.
9957   if (FD) {
9958     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9959   }
9960 
9961   return true;
9962 }
9963 
9964 // Returns true if the SourceLocation is expanded from any macro body.
9965 // Returns false if the SourceLocation is invalid, is from not in a macro
9966 // expansion, or is from expanded from a top-level macro argument.
9967 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9968   if (Loc.isInvalid())
9969     return false;
9970 
9971   while (Loc.isMacroID()) {
9972     if (SM.isMacroBodyExpansion(Loc))
9973       return true;
9974     Loc = SM.getImmediateMacroCallerLoc(Loc);
9975   }
9976 
9977   return false;
9978 }
9979 
9980 /// \brief Diagnose pointers that are always non-null.
9981 /// \param E the expression containing the pointer
9982 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9983 /// compared to a null pointer
9984 /// \param IsEqual True when the comparison is equal to a null pointer
9985 /// \param Range Extra SourceRange to highlight in the diagnostic
9986 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9987                                         Expr::NullPointerConstantKind NullKind,
9988                                         bool IsEqual, SourceRange Range) {
9989   if (!E)
9990     return;
9991 
9992   // Don't warn inside macros.
9993   if (E->getExprLoc().isMacroID()) {
9994     const SourceManager &SM = getSourceManager();
9995     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9996         IsInAnyMacroBody(SM, Range.getBegin()))
9997       return;
9998   }
9999   E = E->IgnoreImpCasts();
10000 
10001   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10002 
10003   if (isa<CXXThisExpr>(E)) {
10004     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10005                                 : diag::warn_this_bool_conversion;
10006     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10007     return;
10008   }
10009 
10010   bool IsAddressOf = false;
10011 
10012   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10013     if (UO->getOpcode() != UO_AddrOf)
10014       return;
10015     IsAddressOf = true;
10016     E = UO->getSubExpr();
10017   }
10018 
10019   if (IsAddressOf) {
10020     unsigned DiagID = IsCompare
10021                           ? diag::warn_address_of_reference_null_compare
10022                           : diag::warn_address_of_reference_bool_conversion;
10023     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10024                                          << IsEqual;
10025     if (CheckForReference(*this, E, PD)) {
10026       return;
10027     }
10028   }
10029 
10030   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10031     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10032     std::string Str;
10033     llvm::raw_string_ostream S(Str);
10034     E->printPretty(S, nullptr, getPrintingPolicy());
10035     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10036                                 : diag::warn_cast_nonnull_to_bool;
10037     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10038       << E->getSourceRange() << Range << IsEqual;
10039     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10040   };
10041 
10042   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10043   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10044     if (auto *Callee = Call->getDirectCallee()) {
10045       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10046         ComplainAboutNonnullParamOrCall(A);
10047         return;
10048       }
10049     }
10050   }
10051 
10052   // Expect to find a single Decl.  Skip anything more complicated.
10053   ValueDecl *D = nullptr;
10054   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10055     D = R->getDecl();
10056   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10057     D = M->getMemberDecl();
10058   }
10059 
10060   // Weak Decls can be null.
10061   if (!D || D->isWeak())
10062     return;
10063 
10064   // Check for parameter decl with nonnull attribute
10065   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10066     if (getCurFunction() &&
10067         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10068       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10069         ComplainAboutNonnullParamOrCall(A);
10070         return;
10071       }
10072 
10073       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10074         auto ParamIter = llvm::find(FD->parameters(), PV);
10075         assert(ParamIter != FD->param_end());
10076         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10077 
10078         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10079           if (!NonNull->args_size()) {
10080               ComplainAboutNonnullParamOrCall(NonNull);
10081               return;
10082           }
10083 
10084           for (const ParamIdx &ArgNo : NonNull->args()) {
10085             if (ArgNo.getASTIndex() == ParamNo) {
10086               ComplainAboutNonnullParamOrCall(NonNull);
10087               return;
10088             }
10089           }
10090         }
10091       }
10092     }
10093   }
10094 
10095   QualType T = D->getType();
10096   const bool IsArray = T->isArrayType();
10097   const bool IsFunction = T->isFunctionType();
10098 
10099   // Address of function is used to silence the function warning.
10100   if (IsAddressOf && IsFunction) {
10101     return;
10102   }
10103 
10104   // Found nothing.
10105   if (!IsAddressOf && !IsFunction && !IsArray)
10106     return;
10107 
10108   // Pretty print the expression for the diagnostic.
10109   std::string Str;
10110   llvm::raw_string_ostream S(Str);
10111   E->printPretty(S, nullptr, getPrintingPolicy());
10112 
10113   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10114                               : diag::warn_impcast_pointer_to_bool;
10115   enum {
10116     AddressOf,
10117     FunctionPointer,
10118     ArrayPointer
10119   } DiagType;
10120   if (IsAddressOf)
10121     DiagType = AddressOf;
10122   else if (IsFunction)
10123     DiagType = FunctionPointer;
10124   else if (IsArray)
10125     DiagType = ArrayPointer;
10126   else
10127     llvm_unreachable("Could not determine diagnostic.");
10128   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10129                                 << Range << IsEqual;
10130 
10131   if (!IsFunction)
10132     return;
10133 
10134   // Suggest '&' to silence the function warning.
10135   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10136       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10137 
10138   // Check to see if '()' fixit should be emitted.
10139   QualType ReturnType;
10140   UnresolvedSet<4> NonTemplateOverloads;
10141   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10142   if (ReturnType.isNull())
10143     return;
10144 
10145   if (IsCompare) {
10146     // There are two cases here.  If there is null constant, the only suggest
10147     // for a pointer return type.  If the null is 0, then suggest if the return
10148     // type is a pointer or an integer type.
10149     if (!ReturnType->isPointerType()) {
10150       if (NullKind == Expr::NPCK_ZeroExpression ||
10151           NullKind == Expr::NPCK_ZeroLiteral) {
10152         if (!ReturnType->isIntegerType())
10153           return;
10154       } else {
10155         return;
10156       }
10157     }
10158   } else { // !IsCompare
10159     // For function to bool, only suggest if the function pointer has bool
10160     // return type.
10161     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10162       return;
10163   }
10164   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10165       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10166 }
10167 
10168 /// Diagnoses "dangerous" implicit conversions within the given
10169 /// expression (which is a full expression).  Implements -Wconversion
10170 /// and -Wsign-compare.
10171 ///
10172 /// \param CC the "context" location of the implicit conversion, i.e.
10173 ///   the most location of the syntactic entity requiring the implicit
10174 ///   conversion
10175 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10176   // Don't diagnose in unevaluated contexts.
10177   if (isUnevaluatedContext())
10178     return;
10179 
10180   // Don't diagnose for value- or type-dependent expressions.
10181   if (E->isTypeDependent() || E->isValueDependent())
10182     return;
10183 
10184   // Check for array bounds violations in cases where the check isn't triggered
10185   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10186   // ArraySubscriptExpr is on the RHS of a variable initialization.
10187   CheckArrayAccess(E);
10188 
10189   // This is not the right CC for (e.g.) a variable initialization.
10190   AnalyzeImplicitConversions(*this, E, CC);
10191 }
10192 
10193 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10194 /// Input argument E is a logical expression.
10195 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10196   ::CheckBoolLikeConversion(*this, E, CC);
10197 }
10198 
10199 /// Diagnose when expression is an integer constant expression and its evaluation
10200 /// results in integer overflow
10201 void Sema::CheckForIntOverflow (Expr *E) {
10202   // Use a work list to deal with nested struct initializers.
10203   SmallVector<Expr *, 2> Exprs(1, E);
10204 
10205   do {
10206     Expr *E = Exprs.pop_back_val();
10207 
10208     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10209       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10210       continue;
10211     }
10212 
10213     if (auto InitList = dyn_cast<InitListExpr>(E))
10214       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10215 
10216     if (isa<ObjCBoxedExpr>(E))
10217       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10218   } while (!Exprs.empty());
10219 }
10220 
10221 namespace {
10222 
10223 /// \brief Visitor for expressions which looks for unsequenced operations on the
10224 /// same object.
10225 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10226   using Base = EvaluatedExprVisitor<SequenceChecker>;
10227 
10228   /// \brief A tree of sequenced regions within an expression. Two regions are
10229   /// unsequenced if one is an ancestor or a descendent of the other. When we
10230   /// finish processing an expression with sequencing, such as a comma
10231   /// expression, we fold its tree nodes into its parent, since they are
10232   /// unsequenced with respect to nodes we will visit later.
10233   class SequenceTree {
10234     struct Value {
10235       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10236       unsigned Parent : 31;
10237       unsigned Merged : 1;
10238     };
10239     SmallVector<Value, 8> Values;
10240 
10241   public:
10242     /// \brief A region within an expression which may be sequenced with respect
10243     /// to some other region.
10244     class Seq {
10245       friend class SequenceTree;
10246 
10247       unsigned Index = 0;
10248 
10249       explicit Seq(unsigned N) : Index(N) {}
10250 
10251     public:
10252       Seq() = default;
10253     };
10254 
10255     SequenceTree() { Values.push_back(Value(0)); }
10256     Seq root() const { return Seq(0); }
10257 
10258     /// \brief Create a new sequence of operations, which is an unsequenced
10259     /// subset of \p Parent. This sequence of operations is sequenced with
10260     /// respect to other children of \p Parent.
10261     Seq allocate(Seq Parent) {
10262       Values.push_back(Value(Parent.Index));
10263       return Seq(Values.size() - 1);
10264     }
10265 
10266     /// \brief Merge a sequence of operations into its parent.
10267     void merge(Seq S) {
10268       Values[S.Index].Merged = true;
10269     }
10270 
10271     /// \brief Determine whether two operations are unsequenced. This operation
10272     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10273     /// should have been merged into its parent as appropriate.
10274     bool isUnsequenced(Seq Cur, Seq Old) {
10275       unsigned C = representative(Cur.Index);
10276       unsigned Target = representative(Old.Index);
10277       while (C >= Target) {
10278         if (C == Target)
10279           return true;
10280         C = Values[C].Parent;
10281       }
10282       return false;
10283     }
10284 
10285   private:
10286     /// \brief Pick a representative for a sequence.
10287     unsigned representative(unsigned K) {
10288       if (Values[K].Merged)
10289         // Perform path compression as we go.
10290         return Values[K].Parent = representative(Values[K].Parent);
10291       return K;
10292     }
10293   };
10294 
10295   /// An object for which we can track unsequenced uses.
10296   using Object = NamedDecl *;
10297 
10298   /// Different flavors of object usage which we track. We only track the
10299   /// least-sequenced usage of each kind.
10300   enum UsageKind {
10301     /// A read of an object. Multiple unsequenced reads are OK.
10302     UK_Use,
10303 
10304     /// A modification of an object which is sequenced before the value
10305     /// computation of the expression, such as ++n in C++.
10306     UK_ModAsValue,
10307 
10308     /// A modification of an object which is not sequenced before the value
10309     /// computation of the expression, such as n++.
10310     UK_ModAsSideEffect,
10311 
10312     UK_Count = UK_ModAsSideEffect + 1
10313   };
10314 
10315   struct Usage {
10316     Expr *Use = nullptr;
10317     SequenceTree::Seq Seq;
10318 
10319     Usage() = default;
10320   };
10321 
10322   struct UsageInfo {
10323     Usage Uses[UK_Count];
10324 
10325     /// Have we issued a diagnostic for this variable already?
10326     bool Diagnosed = false;
10327 
10328     UsageInfo() = default;
10329   };
10330   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
10331 
10332   Sema &SemaRef;
10333 
10334   /// Sequenced regions within the expression.
10335   SequenceTree Tree;
10336 
10337   /// Declaration modifications and references which we have seen.
10338   UsageInfoMap UsageMap;
10339 
10340   /// The region we are currently within.
10341   SequenceTree::Seq Region;
10342 
10343   /// Filled in with declarations which were modified as a side-effect
10344   /// (that is, post-increment operations).
10345   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
10346 
10347   /// Expressions to check later. We defer checking these to reduce
10348   /// stack usage.
10349   SmallVectorImpl<Expr *> &WorkList;
10350 
10351   /// RAII object wrapping the visitation of a sequenced subexpression of an
10352   /// expression. At the end of this process, the side-effects of the evaluation
10353   /// become sequenced with respect to the value computation of the result, so
10354   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10355   /// UK_ModAsValue.
10356   struct SequencedSubexpression {
10357     SequencedSubexpression(SequenceChecker &Self)
10358       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10359       Self.ModAsSideEffect = &ModAsSideEffect;
10360     }
10361 
10362     ~SequencedSubexpression() {
10363       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10364         UsageInfo &U = Self.UsageMap[M.first];
10365         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10366         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10367         SideEffectUsage = M.second;
10368       }
10369       Self.ModAsSideEffect = OldModAsSideEffect;
10370     }
10371 
10372     SequenceChecker &Self;
10373     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10374     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
10375   };
10376 
10377   /// RAII object wrapping the visitation of a subexpression which we might
10378   /// choose to evaluate as a constant. If any subexpression is evaluated and
10379   /// found to be non-constant, this allows us to suppress the evaluation of
10380   /// the outer expression.
10381   class EvaluationTracker {
10382   public:
10383     EvaluationTracker(SequenceChecker &Self)
10384         : Self(Self), Prev(Self.EvalTracker) {
10385       Self.EvalTracker = this;
10386     }
10387 
10388     ~EvaluationTracker() {
10389       Self.EvalTracker = Prev;
10390       if (Prev)
10391         Prev->EvalOK &= EvalOK;
10392     }
10393 
10394     bool evaluate(const Expr *E, bool &Result) {
10395       if (!EvalOK || E->isValueDependent())
10396         return false;
10397       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10398       return EvalOK;
10399     }
10400 
10401   private:
10402     SequenceChecker &Self;
10403     EvaluationTracker *Prev;
10404     bool EvalOK = true;
10405   } *EvalTracker = nullptr;
10406 
10407   /// \brief Find the object which is produced by the specified expression,
10408   /// if any.
10409   Object getObject(Expr *E, bool Mod) const {
10410     E = E->IgnoreParenCasts();
10411     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10412       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10413         return getObject(UO->getSubExpr(), Mod);
10414     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10415       if (BO->getOpcode() == BO_Comma)
10416         return getObject(BO->getRHS(), Mod);
10417       if (Mod && BO->isAssignmentOp())
10418         return getObject(BO->getLHS(), Mod);
10419     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10420       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10421       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10422         return ME->getMemberDecl();
10423     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10424       // FIXME: If this is a reference, map through to its value.
10425       return DRE->getDecl();
10426     return nullptr;
10427   }
10428 
10429   /// \brief Note that an object was modified or used by an expression.
10430   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10431     Usage &U = UI.Uses[UK];
10432     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10433       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10434         ModAsSideEffect->push_back(std::make_pair(O, U));
10435       U.Use = Ref;
10436       U.Seq = Region;
10437     }
10438   }
10439 
10440   /// \brief Check whether a modification or use conflicts with a prior usage.
10441   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10442                   bool IsModMod) {
10443     if (UI.Diagnosed)
10444       return;
10445 
10446     const Usage &U = UI.Uses[OtherKind];
10447     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10448       return;
10449 
10450     Expr *Mod = U.Use;
10451     Expr *ModOrUse = Ref;
10452     if (OtherKind == UK_Use)
10453       std::swap(Mod, ModOrUse);
10454 
10455     SemaRef.Diag(Mod->getExprLoc(),
10456                  IsModMod ? diag::warn_unsequenced_mod_mod
10457                           : diag::warn_unsequenced_mod_use)
10458       << O << SourceRange(ModOrUse->getExprLoc());
10459     UI.Diagnosed = true;
10460   }
10461 
10462   void notePreUse(Object O, Expr *Use) {
10463     UsageInfo &U = UsageMap[O];
10464     // Uses conflict with other modifications.
10465     checkUsage(O, U, Use, UK_ModAsValue, false);
10466   }
10467 
10468   void notePostUse(Object O, Expr *Use) {
10469     UsageInfo &U = UsageMap[O];
10470     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10471     addUsage(U, O, Use, UK_Use);
10472   }
10473 
10474   void notePreMod(Object O, Expr *Mod) {
10475     UsageInfo &U = UsageMap[O];
10476     // Modifications conflict with other modifications and with uses.
10477     checkUsage(O, U, Mod, UK_ModAsValue, true);
10478     checkUsage(O, U, Mod, UK_Use, false);
10479   }
10480 
10481   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10482     UsageInfo &U = UsageMap[O];
10483     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10484     addUsage(U, O, Use, UK);
10485   }
10486 
10487 public:
10488   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10489       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
10490     Visit(E);
10491   }
10492 
10493   void VisitStmt(Stmt *S) {
10494     // Skip all statements which aren't expressions for now.
10495   }
10496 
10497   void VisitExpr(Expr *E) {
10498     // By default, just recurse to evaluated subexpressions.
10499     Base::VisitStmt(E);
10500   }
10501 
10502   void VisitCastExpr(CastExpr *E) {
10503     Object O = Object();
10504     if (E->getCastKind() == CK_LValueToRValue)
10505       O = getObject(E->getSubExpr(), false);
10506 
10507     if (O)
10508       notePreUse(O, E);
10509     VisitExpr(E);
10510     if (O)
10511       notePostUse(O, E);
10512   }
10513 
10514   void VisitBinComma(BinaryOperator *BO) {
10515     // C++11 [expr.comma]p1:
10516     //   Every value computation and side effect associated with the left
10517     //   expression is sequenced before every value computation and side
10518     //   effect associated with the right expression.
10519     SequenceTree::Seq LHS = Tree.allocate(Region);
10520     SequenceTree::Seq RHS = Tree.allocate(Region);
10521     SequenceTree::Seq OldRegion = Region;
10522 
10523     {
10524       SequencedSubexpression SeqLHS(*this);
10525       Region = LHS;
10526       Visit(BO->getLHS());
10527     }
10528 
10529     Region = RHS;
10530     Visit(BO->getRHS());
10531 
10532     Region = OldRegion;
10533 
10534     // Forget that LHS and RHS are sequenced. They are both unsequenced
10535     // with respect to other stuff.
10536     Tree.merge(LHS);
10537     Tree.merge(RHS);
10538   }
10539 
10540   void VisitBinAssign(BinaryOperator *BO) {
10541     // The modification is sequenced after the value computation of the LHS
10542     // and RHS, so check it before inspecting the operands and update the
10543     // map afterwards.
10544     Object O = getObject(BO->getLHS(), true);
10545     if (!O)
10546       return VisitExpr(BO);
10547 
10548     notePreMod(O, BO);
10549 
10550     // C++11 [expr.ass]p7:
10551     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10552     //   only once.
10553     //
10554     // Therefore, for a compound assignment operator, O is considered used
10555     // everywhere except within the evaluation of E1 itself.
10556     if (isa<CompoundAssignOperator>(BO))
10557       notePreUse(O, BO);
10558 
10559     Visit(BO->getLHS());
10560 
10561     if (isa<CompoundAssignOperator>(BO))
10562       notePostUse(O, BO);
10563 
10564     Visit(BO->getRHS());
10565 
10566     // C++11 [expr.ass]p1:
10567     //   the assignment is sequenced [...] before the value computation of the
10568     //   assignment expression.
10569     // C11 6.5.16/3 has no such rule.
10570     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10571                                                        : UK_ModAsSideEffect);
10572   }
10573 
10574   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10575     VisitBinAssign(CAO);
10576   }
10577 
10578   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10579   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10580   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10581     Object O = getObject(UO->getSubExpr(), true);
10582     if (!O)
10583       return VisitExpr(UO);
10584 
10585     notePreMod(O, UO);
10586     Visit(UO->getSubExpr());
10587     // C++11 [expr.pre.incr]p1:
10588     //   the expression ++x is equivalent to x+=1
10589     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10590                                                        : UK_ModAsSideEffect);
10591   }
10592 
10593   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10594   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10595   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10596     Object O = getObject(UO->getSubExpr(), true);
10597     if (!O)
10598       return VisitExpr(UO);
10599 
10600     notePreMod(O, UO);
10601     Visit(UO->getSubExpr());
10602     notePostMod(O, UO, UK_ModAsSideEffect);
10603   }
10604 
10605   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10606   void VisitBinLOr(BinaryOperator *BO) {
10607     // The side-effects of the LHS of an '&&' are sequenced before the
10608     // value computation of the RHS, and hence before the value computation
10609     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10610     // as if they were unconditionally sequenced.
10611     EvaluationTracker Eval(*this);
10612     {
10613       SequencedSubexpression Sequenced(*this);
10614       Visit(BO->getLHS());
10615     }
10616 
10617     bool Result;
10618     if (Eval.evaluate(BO->getLHS(), Result)) {
10619       if (!Result)
10620         Visit(BO->getRHS());
10621     } else {
10622       // Check for unsequenced operations in the RHS, treating it as an
10623       // entirely separate evaluation.
10624       //
10625       // FIXME: If there are operations in the RHS which are unsequenced
10626       // with respect to operations outside the RHS, and those operations
10627       // are unconditionally evaluated, diagnose them.
10628       WorkList.push_back(BO->getRHS());
10629     }
10630   }
10631   void VisitBinLAnd(BinaryOperator *BO) {
10632     EvaluationTracker Eval(*this);
10633     {
10634       SequencedSubexpression Sequenced(*this);
10635       Visit(BO->getLHS());
10636     }
10637 
10638     bool Result;
10639     if (Eval.evaluate(BO->getLHS(), Result)) {
10640       if (Result)
10641         Visit(BO->getRHS());
10642     } else {
10643       WorkList.push_back(BO->getRHS());
10644     }
10645   }
10646 
10647   // Only visit the condition, unless we can be sure which subexpression will
10648   // be chosen.
10649   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10650     EvaluationTracker Eval(*this);
10651     {
10652       SequencedSubexpression Sequenced(*this);
10653       Visit(CO->getCond());
10654     }
10655 
10656     bool Result;
10657     if (Eval.evaluate(CO->getCond(), Result))
10658       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10659     else {
10660       WorkList.push_back(CO->getTrueExpr());
10661       WorkList.push_back(CO->getFalseExpr());
10662     }
10663   }
10664 
10665   void VisitCallExpr(CallExpr *CE) {
10666     // C++11 [intro.execution]p15:
10667     //   When calling a function [...], every value computation and side effect
10668     //   associated with any argument expression, or with the postfix expression
10669     //   designating the called function, is sequenced before execution of every
10670     //   expression or statement in the body of the function [and thus before
10671     //   the value computation of its result].
10672     SequencedSubexpression Sequenced(*this);
10673     Base::VisitCallExpr(CE);
10674 
10675     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10676   }
10677 
10678   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10679     // This is a call, so all subexpressions are sequenced before the result.
10680     SequencedSubexpression Sequenced(*this);
10681 
10682     if (!CCE->isListInitialization())
10683       return VisitExpr(CCE);
10684 
10685     // In C++11, list initializations are sequenced.
10686     SmallVector<SequenceTree::Seq, 32> Elts;
10687     SequenceTree::Seq Parent = Region;
10688     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10689                                         E = CCE->arg_end();
10690          I != E; ++I) {
10691       Region = Tree.allocate(Parent);
10692       Elts.push_back(Region);
10693       Visit(*I);
10694     }
10695 
10696     // Forget that the initializers are sequenced.
10697     Region = Parent;
10698     for (unsigned I = 0; I < Elts.size(); ++I)
10699       Tree.merge(Elts[I]);
10700   }
10701 
10702   void VisitInitListExpr(InitListExpr *ILE) {
10703     if (!SemaRef.getLangOpts().CPlusPlus11)
10704       return VisitExpr(ILE);
10705 
10706     // In C++11, list initializations are sequenced.
10707     SmallVector<SequenceTree::Seq, 32> Elts;
10708     SequenceTree::Seq Parent = Region;
10709     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10710       Expr *E = ILE->getInit(I);
10711       if (!E) continue;
10712       Region = Tree.allocate(Parent);
10713       Elts.push_back(Region);
10714       Visit(E);
10715     }
10716 
10717     // Forget that the initializers are sequenced.
10718     Region = Parent;
10719     for (unsigned I = 0; I < Elts.size(); ++I)
10720       Tree.merge(Elts[I]);
10721   }
10722 };
10723 
10724 } // namespace
10725 
10726 void Sema::CheckUnsequencedOperations(Expr *E) {
10727   SmallVector<Expr *, 8> WorkList;
10728   WorkList.push_back(E);
10729   while (!WorkList.empty()) {
10730     Expr *Item = WorkList.pop_back_val();
10731     SequenceChecker(*this, Item, WorkList);
10732   }
10733 }
10734 
10735 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10736                               bool IsConstexpr) {
10737   CheckImplicitConversions(E, CheckLoc);
10738   if (!E->isInstantiationDependent())
10739     CheckUnsequencedOperations(E);
10740   if (!IsConstexpr && !E->isValueDependent())
10741     CheckForIntOverflow(E);
10742   DiagnoseMisalignedMembers();
10743 }
10744 
10745 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10746                                        FieldDecl *BitField,
10747                                        Expr *Init) {
10748   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10749 }
10750 
10751 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10752                                          SourceLocation Loc) {
10753   if (!PType->isVariablyModifiedType())
10754     return;
10755   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10756     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10757     return;
10758   }
10759   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10760     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10761     return;
10762   }
10763   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10764     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10765     return;
10766   }
10767 
10768   const ArrayType *AT = S.Context.getAsArrayType(PType);
10769   if (!AT)
10770     return;
10771 
10772   if (AT->getSizeModifier() != ArrayType::Star) {
10773     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10774     return;
10775   }
10776 
10777   S.Diag(Loc, diag::err_array_star_in_function_definition);
10778 }
10779 
10780 /// CheckParmsForFunctionDef - Check that the parameters of the given
10781 /// function are appropriate for the definition of a function. This
10782 /// takes care of any checks that cannot be performed on the
10783 /// declaration itself, e.g., that the types of each of the function
10784 /// parameters are complete.
10785 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10786                                     bool CheckParameterNames) {
10787   bool HasInvalidParm = false;
10788   for (ParmVarDecl *Param : Parameters) {
10789     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10790     // function declarator that is part of a function definition of
10791     // that function shall not have incomplete type.
10792     //
10793     // This is also C++ [dcl.fct]p6.
10794     if (!Param->isInvalidDecl() &&
10795         RequireCompleteType(Param->getLocation(), Param->getType(),
10796                             diag::err_typecheck_decl_incomplete_type)) {
10797       Param->setInvalidDecl();
10798       HasInvalidParm = true;
10799     }
10800 
10801     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10802     // declaration of each parameter shall include an identifier.
10803     if (CheckParameterNames &&
10804         Param->getIdentifier() == nullptr &&
10805         !Param->isImplicit() &&
10806         !getLangOpts().CPlusPlus)
10807       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10808 
10809     // C99 6.7.5.3p12:
10810     //   If the function declarator is not part of a definition of that
10811     //   function, parameters may have incomplete type and may use the [*]
10812     //   notation in their sequences of declarator specifiers to specify
10813     //   variable length array types.
10814     QualType PType = Param->getOriginalType();
10815     // FIXME: This diagnostic should point the '[*]' if source-location
10816     // information is added for it.
10817     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10818 
10819     // If the parameter is a c++ class type and it has to be destructed in the
10820     // callee function, declare the destructor so that it can be called by the
10821     // callee function. Do not perfom any direct access check on the dtor here.
10822     if (!Param->isInvalidDecl()) {
10823       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
10824         if (!ClassDecl->isInvalidDecl() &&
10825             !ClassDecl->hasIrrelevantDestructor() &&
10826             !ClassDecl->isDependentContext() &&
10827             Context.isParamDestroyedInCallee(Param->getType())) {
10828           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10829           MarkFunctionReferenced(Param->getLocation(), Destructor);
10830           DiagnoseUseOfDecl(Destructor, Param->getLocation());
10831         }
10832       }
10833     }
10834 
10835     // Parameters with the pass_object_size attribute only need to be marked
10836     // constant at function definitions. Because we lack information about
10837     // whether we're on a declaration or definition when we're instantiating the
10838     // attribute, we need to check for constness here.
10839     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10840       if (!Param->getType().isConstQualified())
10841         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10842             << Attr->getSpelling() << 1;
10843   }
10844 
10845   return HasInvalidParm;
10846 }
10847 
10848 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10849 /// or MemberExpr.
10850 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10851                               ASTContext &Context) {
10852   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10853     return Context.getDeclAlign(DRE->getDecl());
10854 
10855   if (const auto *ME = dyn_cast<MemberExpr>(E))
10856     return Context.getDeclAlign(ME->getMemberDecl());
10857 
10858   return TypeAlign;
10859 }
10860 
10861 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10862 /// pointer cast increases the alignment requirements.
10863 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10864   // This is actually a lot of work to potentially be doing on every
10865   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10866   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10867     return;
10868 
10869   // Ignore dependent types.
10870   if (T->isDependentType() || Op->getType()->isDependentType())
10871     return;
10872 
10873   // Require that the destination be a pointer type.
10874   const PointerType *DestPtr = T->getAs<PointerType>();
10875   if (!DestPtr) return;
10876 
10877   // If the destination has alignment 1, we're done.
10878   QualType DestPointee = DestPtr->getPointeeType();
10879   if (DestPointee->isIncompleteType()) return;
10880   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10881   if (DestAlign.isOne()) return;
10882 
10883   // Require that the source be a pointer type.
10884   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10885   if (!SrcPtr) return;
10886   QualType SrcPointee = SrcPtr->getPointeeType();
10887 
10888   // Whitelist casts from cv void*.  We already implicitly
10889   // whitelisted casts to cv void*, since they have alignment 1.
10890   // Also whitelist casts involving incomplete types, which implicitly
10891   // includes 'void'.
10892   if (SrcPointee->isIncompleteType()) return;
10893 
10894   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10895 
10896   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10897     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10898       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10899   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10900     if (UO->getOpcode() == UO_AddrOf)
10901       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10902   }
10903 
10904   if (SrcAlign >= DestAlign) return;
10905 
10906   Diag(TRange.getBegin(), diag::warn_cast_align)
10907     << Op->getType() << T
10908     << static_cast<unsigned>(SrcAlign.getQuantity())
10909     << static_cast<unsigned>(DestAlign.getQuantity())
10910     << TRange << Op->getSourceRange();
10911 }
10912 
10913 /// \brief Check whether this array fits the idiom of a size-one tail padded
10914 /// array member of a struct.
10915 ///
10916 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10917 /// commonly used to emulate flexible arrays in C89 code.
10918 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10919                                     const NamedDecl *ND) {
10920   if (Size != 1 || !ND) return false;
10921 
10922   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10923   if (!FD) return false;
10924 
10925   // Don't consider sizes resulting from macro expansions or template argument
10926   // substitution to form C89 tail-padded arrays.
10927 
10928   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10929   while (TInfo) {
10930     TypeLoc TL = TInfo->getTypeLoc();
10931     // Look through typedefs.
10932     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10933       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10934       TInfo = TDL->getTypeSourceInfo();
10935       continue;
10936     }
10937     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10938       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10939       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10940         return false;
10941     }
10942     break;
10943   }
10944 
10945   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10946   if (!RD) return false;
10947   if (RD->isUnion()) return false;
10948   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10949     if (!CRD->isStandardLayout()) return false;
10950   }
10951 
10952   // See if this is the last field decl in the record.
10953   const Decl *D = FD;
10954   while ((D = D->getNextDeclInContext()))
10955     if (isa<FieldDecl>(D))
10956       return false;
10957   return true;
10958 }
10959 
10960 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10961                             const ArraySubscriptExpr *ASE,
10962                             bool AllowOnePastEnd, bool IndexNegated) {
10963   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10964   if (IndexExpr->isValueDependent())
10965     return;
10966 
10967   const Type *EffectiveType =
10968       BaseExpr->getType()->getPointeeOrArrayElementType();
10969   BaseExpr = BaseExpr->IgnoreParenCasts();
10970   const ConstantArrayType *ArrayTy =
10971     Context.getAsConstantArrayType(BaseExpr->getType());
10972   if (!ArrayTy)
10973     return;
10974 
10975   llvm::APSInt index;
10976   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10977     return;
10978   if (IndexNegated)
10979     index = -index;
10980 
10981   const NamedDecl *ND = nullptr;
10982   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10983     ND = DRE->getDecl();
10984   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10985     ND = ME->getMemberDecl();
10986 
10987   if (index.isUnsigned() || !index.isNegative()) {
10988     llvm::APInt size = ArrayTy->getSize();
10989     if (!size.isStrictlyPositive())
10990       return;
10991 
10992     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10993     if (BaseType != EffectiveType) {
10994       // Make sure we're comparing apples to apples when comparing index to size
10995       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10996       uint64_t array_typesize = Context.getTypeSize(BaseType);
10997       // Handle ptrarith_typesize being zero, such as when casting to void*
10998       if (!ptrarith_typesize) ptrarith_typesize = 1;
10999       if (ptrarith_typesize != array_typesize) {
11000         // There's a cast to a different size type involved
11001         uint64_t ratio = array_typesize / ptrarith_typesize;
11002         // TODO: Be smarter about handling cases where array_typesize is not a
11003         // multiple of ptrarith_typesize
11004         if (ptrarith_typesize * ratio == array_typesize)
11005           size *= llvm::APInt(size.getBitWidth(), ratio);
11006       }
11007     }
11008 
11009     if (size.getBitWidth() > index.getBitWidth())
11010       index = index.zext(size.getBitWidth());
11011     else if (size.getBitWidth() < index.getBitWidth())
11012       size = size.zext(index.getBitWidth());
11013 
11014     // For array subscripting the index must be less than size, but for pointer
11015     // arithmetic also allow the index (offset) to be equal to size since
11016     // computing the next address after the end of the array is legal and
11017     // commonly done e.g. in C++ iterators and range-based for loops.
11018     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11019       return;
11020 
11021     // Also don't warn for arrays of size 1 which are members of some
11022     // structure. These are often used to approximate flexible arrays in C89
11023     // code.
11024     if (IsTailPaddedMemberArray(*this, size, ND))
11025       return;
11026 
11027     // Suppress the warning if the subscript expression (as identified by the
11028     // ']' location) and the index expression are both from macro expansions
11029     // within a system header.
11030     if (ASE) {
11031       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11032           ASE->getRBracketLoc());
11033       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11034         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11035             IndexExpr->getLocStart());
11036         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11037           return;
11038       }
11039     }
11040 
11041     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11042     if (ASE)
11043       DiagID = diag::warn_array_index_exceeds_bounds;
11044 
11045     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11046                         PDiag(DiagID) << index.toString(10, true)
11047                           << size.toString(10, true)
11048                           << (unsigned)size.getLimitedValue(~0U)
11049                           << IndexExpr->getSourceRange());
11050   } else {
11051     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11052     if (!ASE) {
11053       DiagID = diag::warn_ptr_arith_precedes_bounds;
11054       if (index.isNegative()) index = -index;
11055     }
11056 
11057     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11058                         PDiag(DiagID) << index.toString(10, true)
11059                           << IndexExpr->getSourceRange());
11060   }
11061 
11062   if (!ND) {
11063     // Try harder to find a NamedDecl to point at in the note.
11064     while (const ArraySubscriptExpr *ASE =
11065            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11066       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11067     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11068       ND = DRE->getDecl();
11069     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11070       ND = ME->getMemberDecl();
11071   }
11072 
11073   if (ND)
11074     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11075                         PDiag(diag::note_array_index_out_of_bounds)
11076                           << ND->getDeclName());
11077 }
11078 
11079 void Sema::CheckArrayAccess(const Expr *expr) {
11080   int AllowOnePastEnd = 0;
11081   while (expr) {
11082     expr = expr->IgnoreParenImpCasts();
11083     switch (expr->getStmtClass()) {
11084       case Stmt::ArraySubscriptExprClass: {
11085         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11086         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11087                          AllowOnePastEnd > 0);
11088         return;
11089       }
11090       case Stmt::OMPArraySectionExprClass: {
11091         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11092         if (ASE->getLowerBound())
11093           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11094                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11095         return;
11096       }
11097       case Stmt::UnaryOperatorClass: {
11098         // Only unwrap the * and & unary operators
11099         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11100         expr = UO->getSubExpr();
11101         switch (UO->getOpcode()) {
11102           case UO_AddrOf:
11103             AllowOnePastEnd++;
11104             break;
11105           case UO_Deref:
11106             AllowOnePastEnd--;
11107             break;
11108           default:
11109             return;
11110         }
11111         break;
11112       }
11113       case Stmt::ConditionalOperatorClass: {
11114         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11115         if (const Expr *lhs = cond->getLHS())
11116           CheckArrayAccess(lhs);
11117         if (const Expr *rhs = cond->getRHS())
11118           CheckArrayAccess(rhs);
11119         return;
11120       }
11121       case Stmt::CXXOperatorCallExprClass: {
11122         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11123         for (const auto *Arg : OCE->arguments())
11124           CheckArrayAccess(Arg);
11125         return;
11126       }
11127       default:
11128         return;
11129     }
11130   }
11131 }
11132 
11133 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11134 
11135 namespace {
11136 
11137 struct RetainCycleOwner {
11138   VarDecl *Variable = nullptr;
11139   SourceRange Range;
11140   SourceLocation Loc;
11141   bool Indirect = false;
11142 
11143   RetainCycleOwner() = default;
11144 
11145   void setLocsFrom(Expr *e) {
11146     Loc = e->getExprLoc();
11147     Range = e->getSourceRange();
11148   }
11149 };
11150 
11151 } // namespace
11152 
11153 /// Consider whether capturing the given variable can possibly lead to
11154 /// a retain cycle.
11155 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11156   // In ARC, it's captured strongly iff the variable has __strong
11157   // lifetime.  In MRR, it's captured strongly if the variable is
11158   // __block and has an appropriate type.
11159   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11160     return false;
11161 
11162   owner.Variable = var;
11163   if (ref)
11164     owner.setLocsFrom(ref);
11165   return true;
11166 }
11167 
11168 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11169   while (true) {
11170     e = e->IgnoreParens();
11171     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11172       switch (cast->getCastKind()) {
11173       case CK_BitCast:
11174       case CK_LValueBitCast:
11175       case CK_LValueToRValue:
11176       case CK_ARCReclaimReturnedObject:
11177         e = cast->getSubExpr();
11178         continue;
11179 
11180       default:
11181         return false;
11182       }
11183     }
11184 
11185     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11186       ObjCIvarDecl *ivar = ref->getDecl();
11187       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11188         return false;
11189 
11190       // Try to find a retain cycle in the base.
11191       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11192         return false;
11193 
11194       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11195       owner.Indirect = true;
11196       return true;
11197     }
11198 
11199     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11200       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11201       if (!var) return false;
11202       return considerVariable(var, ref, owner);
11203     }
11204 
11205     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11206       if (member->isArrow()) return false;
11207 
11208       // Don't count this as an indirect ownership.
11209       e = member->getBase();
11210       continue;
11211     }
11212 
11213     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11214       // Only pay attention to pseudo-objects on property references.
11215       ObjCPropertyRefExpr *pre
11216         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11217                                               ->IgnoreParens());
11218       if (!pre) return false;
11219       if (pre->isImplicitProperty()) return false;
11220       ObjCPropertyDecl *property = pre->getExplicitProperty();
11221       if (!property->isRetaining() &&
11222           !(property->getPropertyIvarDecl() &&
11223             property->getPropertyIvarDecl()->getType()
11224               .getObjCLifetime() == Qualifiers::OCL_Strong))
11225           return false;
11226 
11227       owner.Indirect = true;
11228       if (pre->isSuperReceiver()) {
11229         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11230         if (!owner.Variable)
11231           return false;
11232         owner.Loc = pre->getLocation();
11233         owner.Range = pre->getSourceRange();
11234         return true;
11235       }
11236       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11237                               ->getSourceExpr());
11238       continue;
11239     }
11240 
11241     // Array ivars?
11242 
11243     return false;
11244   }
11245 }
11246 
11247 namespace {
11248 
11249   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11250     ASTContext &Context;
11251     VarDecl *Variable;
11252     Expr *Capturer = nullptr;
11253     bool VarWillBeReased = false;
11254 
11255     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11256         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11257           Context(Context), Variable(variable) {}
11258 
11259     void VisitDeclRefExpr(DeclRefExpr *ref) {
11260       if (ref->getDecl() == Variable && !Capturer)
11261         Capturer = ref;
11262     }
11263 
11264     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11265       if (Capturer) return;
11266       Visit(ref->getBase());
11267       if (Capturer && ref->isFreeIvar())
11268         Capturer = ref;
11269     }
11270 
11271     void VisitBlockExpr(BlockExpr *block) {
11272       // Look inside nested blocks
11273       if (block->getBlockDecl()->capturesVariable(Variable))
11274         Visit(block->getBlockDecl()->getBody());
11275     }
11276 
11277     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11278       if (Capturer) return;
11279       if (OVE->getSourceExpr())
11280         Visit(OVE->getSourceExpr());
11281     }
11282 
11283     void VisitBinaryOperator(BinaryOperator *BinOp) {
11284       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11285         return;
11286       Expr *LHS = BinOp->getLHS();
11287       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11288         if (DRE->getDecl() != Variable)
11289           return;
11290         if (Expr *RHS = BinOp->getRHS()) {
11291           RHS = RHS->IgnoreParenCasts();
11292           llvm::APSInt Value;
11293           VarWillBeReased =
11294             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11295         }
11296       }
11297     }
11298   };
11299 
11300 } // namespace
11301 
11302 /// Check whether the given argument is a block which captures a
11303 /// variable.
11304 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11305   assert(owner.Variable && owner.Loc.isValid());
11306 
11307   e = e->IgnoreParenCasts();
11308 
11309   // Look through [^{...} copy] and Block_copy(^{...}).
11310   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11311     Selector Cmd = ME->getSelector();
11312     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11313       e = ME->getInstanceReceiver();
11314       if (!e)
11315         return nullptr;
11316       e = e->IgnoreParenCasts();
11317     }
11318   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11319     if (CE->getNumArgs() == 1) {
11320       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11321       if (Fn) {
11322         const IdentifierInfo *FnI = Fn->getIdentifier();
11323         if (FnI && FnI->isStr("_Block_copy")) {
11324           e = CE->getArg(0)->IgnoreParenCasts();
11325         }
11326       }
11327     }
11328   }
11329 
11330   BlockExpr *block = dyn_cast<BlockExpr>(e);
11331   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11332     return nullptr;
11333 
11334   FindCaptureVisitor visitor(S.Context, owner.Variable);
11335   visitor.Visit(block->getBlockDecl()->getBody());
11336   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11337 }
11338 
11339 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11340                                 RetainCycleOwner &owner) {
11341   assert(capturer);
11342   assert(owner.Variable && owner.Loc.isValid());
11343 
11344   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11345     << owner.Variable << capturer->getSourceRange();
11346   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11347     << owner.Indirect << owner.Range;
11348 }
11349 
11350 /// Check for a keyword selector that starts with the word 'add' or
11351 /// 'set'.
11352 static bool isSetterLikeSelector(Selector sel) {
11353   if (sel.isUnarySelector()) return false;
11354 
11355   StringRef str = sel.getNameForSlot(0);
11356   while (!str.empty() && str.front() == '_') str = str.substr(1);
11357   if (str.startswith("set"))
11358     str = str.substr(3);
11359   else if (str.startswith("add")) {
11360     // Specially whitelist 'addOperationWithBlock:'.
11361     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11362       return false;
11363     str = str.substr(3);
11364   }
11365   else
11366     return false;
11367 
11368   if (str.empty()) return true;
11369   return !isLowercase(str.front());
11370 }
11371 
11372 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11373                                                     ObjCMessageExpr *Message) {
11374   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11375                                                 Message->getReceiverInterface(),
11376                                                 NSAPI::ClassId_NSMutableArray);
11377   if (!IsMutableArray) {
11378     return None;
11379   }
11380 
11381   Selector Sel = Message->getSelector();
11382 
11383   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11384     S.NSAPIObj->getNSArrayMethodKind(Sel);
11385   if (!MKOpt) {
11386     return None;
11387   }
11388 
11389   NSAPI::NSArrayMethodKind MK = *MKOpt;
11390 
11391   switch (MK) {
11392     case NSAPI::NSMutableArr_addObject:
11393     case NSAPI::NSMutableArr_insertObjectAtIndex:
11394     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11395       return 0;
11396     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11397       return 1;
11398 
11399     default:
11400       return None;
11401   }
11402 
11403   return None;
11404 }
11405 
11406 static
11407 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11408                                                   ObjCMessageExpr *Message) {
11409   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11410                                             Message->getReceiverInterface(),
11411                                             NSAPI::ClassId_NSMutableDictionary);
11412   if (!IsMutableDictionary) {
11413     return None;
11414   }
11415 
11416   Selector Sel = Message->getSelector();
11417 
11418   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11419     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11420   if (!MKOpt) {
11421     return None;
11422   }
11423 
11424   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11425 
11426   switch (MK) {
11427     case NSAPI::NSMutableDict_setObjectForKey:
11428     case NSAPI::NSMutableDict_setValueForKey:
11429     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11430       return 0;
11431 
11432     default:
11433       return None;
11434   }
11435 
11436   return None;
11437 }
11438 
11439 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11440   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11441                                                 Message->getReceiverInterface(),
11442                                                 NSAPI::ClassId_NSMutableSet);
11443 
11444   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11445                                             Message->getReceiverInterface(),
11446                                             NSAPI::ClassId_NSMutableOrderedSet);
11447   if (!IsMutableSet && !IsMutableOrderedSet) {
11448     return None;
11449   }
11450 
11451   Selector Sel = Message->getSelector();
11452 
11453   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11454   if (!MKOpt) {
11455     return None;
11456   }
11457 
11458   NSAPI::NSSetMethodKind MK = *MKOpt;
11459 
11460   switch (MK) {
11461     case NSAPI::NSMutableSet_addObject:
11462     case NSAPI::NSOrderedSet_setObjectAtIndex:
11463     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11464     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11465       return 0;
11466     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11467       return 1;
11468   }
11469 
11470   return None;
11471 }
11472 
11473 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11474   if (!Message->isInstanceMessage()) {
11475     return;
11476   }
11477 
11478   Optional<int> ArgOpt;
11479 
11480   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11481       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11482       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11483     return;
11484   }
11485 
11486   int ArgIndex = *ArgOpt;
11487 
11488   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11489   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11490     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11491   }
11492 
11493   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11494     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11495       if (ArgRE->isObjCSelfExpr()) {
11496         Diag(Message->getSourceRange().getBegin(),
11497              diag::warn_objc_circular_container)
11498           << ArgRE->getDecl()->getName() << StringRef("super");
11499       }
11500     }
11501   } else {
11502     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11503 
11504     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11505       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11506     }
11507 
11508     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11509       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11510         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11511           ValueDecl *Decl = ReceiverRE->getDecl();
11512           Diag(Message->getSourceRange().getBegin(),
11513                diag::warn_objc_circular_container)
11514             << Decl->getName() << Decl->getName();
11515           if (!ArgRE->isObjCSelfExpr()) {
11516             Diag(Decl->getLocation(),
11517                  diag::note_objc_circular_container_declared_here)
11518               << Decl->getName();
11519           }
11520         }
11521       }
11522     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11523       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11524         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11525           ObjCIvarDecl *Decl = IvarRE->getDecl();
11526           Diag(Message->getSourceRange().getBegin(),
11527                diag::warn_objc_circular_container)
11528             << Decl->getName() << Decl->getName();
11529           Diag(Decl->getLocation(),
11530                diag::note_objc_circular_container_declared_here)
11531             << Decl->getName();
11532         }
11533       }
11534     }
11535   }
11536 }
11537 
11538 /// Check a message send to see if it's likely to cause a retain cycle.
11539 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11540   // Only check instance methods whose selector looks like a setter.
11541   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11542     return;
11543 
11544   // Try to find a variable that the receiver is strongly owned by.
11545   RetainCycleOwner owner;
11546   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11547     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11548       return;
11549   } else {
11550     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11551     owner.Variable = getCurMethodDecl()->getSelfDecl();
11552     owner.Loc = msg->getSuperLoc();
11553     owner.Range = msg->getSuperLoc();
11554   }
11555 
11556   // Check whether the receiver is captured by any of the arguments.
11557   const ObjCMethodDecl *MD = msg->getMethodDecl();
11558   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
11559     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
11560       // noescape blocks should not be retained by the method.
11561       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
11562         continue;
11563       return diagnoseRetainCycle(*this, capturer, owner);
11564     }
11565   }
11566 }
11567 
11568 /// Check a property assign to see if it's likely to cause a retain cycle.
11569 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11570   RetainCycleOwner owner;
11571   if (!findRetainCycleOwner(*this, receiver, owner))
11572     return;
11573 
11574   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11575     diagnoseRetainCycle(*this, capturer, owner);
11576 }
11577 
11578 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11579   RetainCycleOwner Owner;
11580   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11581     return;
11582 
11583   // Because we don't have an expression for the variable, we have to set the
11584   // location explicitly here.
11585   Owner.Loc = Var->getLocation();
11586   Owner.Range = Var->getSourceRange();
11587 
11588   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11589     diagnoseRetainCycle(*this, Capturer, Owner);
11590 }
11591 
11592 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11593                                      Expr *RHS, bool isProperty) {
11594   // Check if RHS is an Objective-C object literal, which also can get
11595   // immediately zapped in a weak reference.  Note that we explicitly
11596   // allow ObjCStringLiterals, since those are designed to never really die.
11597   RHS = RHS->IgnoreParenImpCasts();
11598 
11599   // This enum needs to match with the 'select' in
11600   // warn_objc_arc_literal_assign (off-by-1).
11601   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11602   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11603     return false;
11604 
11605   S.Diag(Loc, diag::warn_arc_literal_assign)
11606     << (unsigned) Kind
11607     << (isProperty ? 0 : 1)
11608     << RHS->getSourceRange();
11609 
11610   return true;
11611 }
11612 
11613 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11614                                     Qualifiers::ObjCLifetime LT,
11615                                     Expr *RHS, bool isProperty) {
11616   // Strip off any implicit cast added to get to the one ARC-specific.
11617   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11618     if (cast->getCastKind() == CK_ARCConsumeObject) {
11619       S.Diag(Loc, diag::warn_arc_retained_assign)
11620         << (LT == Qualifiers::OCL_ExplicitNone)
11621         << (isProperty ? 0 : 1)
11622         << RHS->getSourceRange();
11623       return true;
11624     }
11625     RHS = cast->getSubExpr();
11626   }
11627 
11628   if (LT == Qualifiers::OCL_Weak &&
11629       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11630     return true;
11631 
11632   return false;
11633 }
11634 
11635 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11636                               QualType LHS, Expr *RHS) {
11637   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11638 
11639   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11640     return false;
11641 
11642   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11643     return true;
11644 
11645   return false;
11646 }
11647 
11648 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11649                               Expr *LHS, Expr *RHS) {
11650   QualType LHSType;
11651   // PropertyRef on LHS type need be directly obtained from
11652   // its declaration as it has a PseudoType.
11653   ObjCPropertyRefExpr *PRE
11654     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11655   if (PRE && !PRE->isImplicitProperty()) {
11656     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11657     if (PD)
11658       LHSType = PD->getType();
11659   }
11660 
11661   if (LHSType.isNull())
11662     LHSType = LHS->getType();
11663 
11664   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11665 
11666   if (LT == Qualifiers::OCL_Weak) {
11667     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11668       getCurFunction()->markSafeWeakUse(LHS);
11669   }
11670 
11671   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11672     return;
11673 
11674   // FIXME. Check for other life times.
11675   if (LT != Qualifiers::OCL_None)
11676     return;
11677 
11678   if (PRE) {
11679     if (PRE->isImplicitProperty())
11680       return;
11681     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11682     if (!PD)
11683       return;
11684 
11685     unsigned Attributes = PD->getPropertyAttributes();
11686     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11687       // when 'assign' attribute was not explicitly specified
11688       // by user, ignore it and rely on property type itself
11689       // for lifetime info.
11690       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11691       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11692           LHSType->isObjCRetainableType())
11693         return;
11694 
11695       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11696         if (cast->getCastKind() == CK_ARCConsumeObject) {
11697           Diag(Loc, diag::warn_arc_retained_property_assign)
11698           << RHS->getSourceRange();
11699           return;
11700         }
11701         RHS = cast->getSubExpr();
11702       }
11703     }
11704     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11705       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11706         return;
11707     }
11708   }
11709 }
11710 
11711 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11712 
11713 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11714                                         SourceLocation StmtLoc,
11715                                         const NullStmt *Body) {
11716   // Do not warn if the body is a macro that expands to nothing, e.g:
11717   //
11718   // #define CALL(x)
11719   // if (condition)
11720   //   CALL(0);
11721   if (Body->hasLeadingEmptyMacro())
11722     return false;
11723 
11724   // Get line numbers of statement and body.
11725   bool StmtLineInvalid;
11726   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11727                                                       &StmtLineInvalid);
11728   if (StmtLineInvalid)
11729     return false;
11730 
11731   bool BodyLineInvalid;
11732   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11733                                                       &BodyLineInvalid);
11734   if (BodyLineInvalid)
11735     return false;
11736 
11737   // Warn if null statement and body are on the same line.
11738   if (StmtLine != BodyLine)
11739     return false;
11740 
11741   return true;
11742 }
11743 
11744 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11745                                  const Stmt *Body,
11746                                  unsigned DiagID) {
11747   // Since this is a syntactic check, don't emit diagnostic for template
11748   // instantiations, this just adds noise.
11749   if (CurrentInstantiationScope)
11750     return;
11751 
11752   // The body should be a null statement.
11753   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11754   if (!NBody)
11755     return;
11756 
11757   // Do the usual checks.
11758   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11759     return;
11760 
11761   Diag(NBody->getSemiLoc(), DiagID);
11762   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11763 }
11764 
11765 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11766                                  const Stmt *PossibleBody) {
11767   assert(!CurrentInstantiationScope); // Ensured by caller
11768 
11769   SourceLocation StmtLoc;
11770   const Stmt *Body;
11771   unsigned DiagID;
11772   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11773     StmtLoc = FS->getRParenLoc();
11774     Body = FS->getBody();
11775     DiagID = diag::warn_empty_for_body;
11776   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11777     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11778     Body = WS->getBody();
11779     DiagID = diag::warn_empty_while_body;
11780   } else
11781     return; // Neither `for' nor `while'.
11782 
11783   // The body should be a null statement.
11784   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11785   if (!NBody)
11786     return;
11787 
11788   // Skip expensive checks if diagnostic is disabled.
11789   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11790     return;
11791 
11792   // Do the usual checks.
11793   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11794     return;
11795 
11796   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11797   // noise level low, emit diagnostics only if for/while is followed by a
11798   // CompoundStmt, e.g.:
11799   //    for (int i = 0; i < n; i++);
11800   //    {
11801   //      a(i);
11802   //    }
11803   // or if for/while is followed by a statement with more indentation
11804   // than for/while itself:
11805   //    for (int i = 0; i < n; i++);
11806   //      a(i);
11807   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11808   if (!ProbableTypo) {
11809     bool BodyColInvalid;
11810     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11811                              PossibleBody->getLocStart(),
11812                              &BodyColInvalid);
11813     if (BodyColInvalid)
11814       return;
11815 
11816     bool StmtColInvalid;
11817     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11818                              S->getLocStart(),
11819                              &StmtColInvalid);
11820     if (StmtColInvalid)
11821       return;
11822 
11823     if (BodyCol > StmtCol)
11824       ProbableTypo = true;
11825   }
11826 
11827   if (ProbableTypo) {
11828     Diag(NBody->getSemiLoc(), DiagID);
11829     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11830   }
11831 }
11832 
11833 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11834 
11835 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11836 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11837                              SourceLocation OpLoc) {
11838   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11839     return;
11840 
11841   if (inTemplateInstantiation())
11842     return;
11843 
11844   // Strip parens and casts away.
11845   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11846   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11847 
11848   // Check for a call expression
11849   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11850   if (!CE || CE->getNumArgs() != 1)
11851     return;
11852 
11853   // Check for a call to std::move
11854   if (!CE->isCallToStdMove())
11855     return;
11856 
11857   // Get argument from std::move
11858   RHSExpr = CE->getArg(0);
11859 
11860   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11861   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11862 
11863   // Two DeclRefExpr's, check that the decls are the same.
11864   if (LHSDeclRef && RHSDeclRef) {
11865     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11866       return;
11867     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11868         RHSDeclRef->getDecl()->getCanonicalDecl())
11869       return;
11870 
11871     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11872                                         << LHSExpr->getSourceRange()
11873                                         << RHSExpr->getSourceRange();
11874     return;
11875   }
11876 
11877   // Member variables require a different approach to check for self moves.
11878   // MemberExpr's are the same if every nested MemberExpr refers to the same
11879   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11880   // the base Expr's are CXXThisExpr's.
11881   const Expr *LHSBase = LHSExpr;
11882   const Expr *RHSBase = RHSExpr;
11883   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11884   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11885   if (!LHSME || !RHSME)
11886     return;
11887 
11888   while (LHSME && RHSME) {
11889     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11890         RHSME->getMemberDecl()->getCanonicalDecl())
11891       return;
11892 
11893     LHSBase = LHSME->getBase();
11894     RHSBase = RHSME->getBase();
11895     LHSME = dyn_cast<MemberExpr>(LHSBase);
11896     RHSME = dyn_cast<MemberExpr>(RHSBase);
11897   }
11898 
11899   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11900   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11901   if (LHSDeclRef && RHSDeclRef) {
11902     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11903       return;
11904     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11905         RHSDeclRef->getDecl()->getCanonicalDecl())
11906       return;
11907 
11908     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11909                                         << LHSExpr->getSourceRange()
11910                                         << RHSExpr->getSourceRange();
11911     return;
11912   }
11913 
11914   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11915     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11916                                         << LHSExpr->getSourceRange()
11917                                         << RHSExpr->getSourceRange();
11918 }
11919 
11920 //===--- Layout compatibility ----------------------------------------------//
11921 
11922 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11923 
11924 /// \brief Check if two enumeration types are layout-compatible.
11925 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11926   // C++11 [dcl.enum] p8:
11927   // Two enumeration types are layout-compatible if they have the same
11928   // underlying type.
11929   return ED1->isComplete() && ED2->isComplete() &&
11930          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11931 }
11932 
11933 /// \brief Check if two fields are layout-compatible.
11934 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
11935                                FieldDecl *Field2) {
11936   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11937     return false;
11938 
11939   if (Field1->isBitField() != Field2->isBitField())
11940     return false;
11941 
11942   if (Field1->isBitField()) {
11943     // Make sure that the bit-fields are the same length.
11944     unsigned Bits1 = Field1->getBitWidthValue(C);
11945     unsigned Bits2 = Field2->getBitWidthValue(C);
11946 
11947     if (Bits1 != Bits2)
11948       return false;
11949   }
11950 
11951   return true;
11952 }
11953 
11954 /// \brief Check if two standard-layout structs are layout-compatible.
11955 /// (C++11 [class.mem] p17)
11956 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
11957                                      RecordDecl *RD2) {
11958   // If both records are C++ classes, check that base classes match.
11959   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11960     // If one of records is a CXXRecordDecl we are in C++ mode,
11961     // thus the other one is a CXXRecordDecl, too.
11962     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11963     // Check number of base classes.
11964     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11965       return false;
11966 
11967     // Check the base classes.
11968     for (CXXRecordDecl::base_class_const_iterator
11969                Base1 = D1CXX->bases_begin(),
11970            BaseEnd1 = D1CXX->bases_end(),
11971               Base2 = D2CXX->bases_begin();
11972          Base1 != BaseEnd1;
11973          ++Base1, ++Base2) {
11974       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11975         return false;
11976     }
11977   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11978     // If only RD2 is a C++ class, it should have zero base classes.
11979     if (D2CXX->getNumBases() > 0)
11980       return false;
11981   }
11982 
11983   // Check the fields.
11984   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11985                              Field2End = RD2->field_end(),
11986                              Field1 = RD1->field_begin(),
11987                              Field1End = RD1->field_end();
11988   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11989     if (!isLayoutCompatible(C, *Field1, *Field2))
11990       return false;
11991   }
11992   if (Field1 != Field1End || Field2 != Field2End)
11993     return false;
11994 
11995   return true;
11996 }
11997 
11998 /// \brief Check if two standard-layout unions are layout-compatible.
11999 /// (C++11 [class.mem] p18)
12000 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
12001                                     RecordDecl *RD2) {
12002   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
12003   for (auto *Field2 : RD2->fields())
12004     UnmatchedFields.insert(Field2);
12005 
12006   for (auto *Field1 : RD1->fields()) {
12007     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
12008         I = UnmatchedFields.begin(),
12009         E = UnmatchedFields.end();
12010 
12011     for ( ; I != E; ++I) {
12012       if (isLayoutCompatible(C, Field1, *I)) {
12013         bool Result = UnmatchedFields.erase(*I);
12014         (void) Result;
12015         assert(Result);
12016         break;
12017       }
12018     }
12019     if (I == E)
12020       return false;
12021   }
12022 
12023   return UnmatchedFields.empty();
12024 }
12025 
12026 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
12027                                RecordDecl *RD2) {
12028   if (RD1->isUnion() != RD2->isUnion())
12029     return false;
12030 
12031   if (RD1->isUnion())
12032     return isLayoutCompatibleUnion(C, RD1, RD2);
12033   else
12034     return isLayoutCompatibleStruct(C, RD1, RD2);
12035 }
12036 
12037 /// \brief Check if two types are layout-compatible in C++11 sense.
12038 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12039   if (T1.isNull() || T2.isNull())
12040     return false;
12041 
12042   // C++11 [basic.types] p11:
12043   // If two types T1 and T2 are the same type, then T1 and T2 are
12044   // layout-compatible types.
12045   if (C.hasSameType(T1, T2))
12046     return true;
12047 
12048   T1 = T1.getCanonicalType().getUnqualifiedType();
12049   T2 = T2.getCanonicalType().getUnqualifiedType();
12050 
12051   const Type::TypeClass TC1 = T1->getTypeClass();
12052   const Type::TypeClass TC2 = T2->getTypeClass();
12053 
12054   if (TC1 != TC2)
12055     return false;
12056 
12057   if (TC1 == Type::Enum) {
12058     return isLayoutCompatible(C,
12059                               cast<EnumType>(T1)->getDecl(),
12060                               cast<EnumType>(T2)->getDecl());
12061   } else if (TC1 == Type::Record) {
12062     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12063       return false;
12064 
12065     return isLayoutCompatible(C,
12066                               cast<RecordType>(T1)->getDecl(),
12067                               cast<RecordType>(T2)->getDecl());
12068   }
12069 
12070   return false;
12071 }
12072 
12073 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12074 
12075 /// \brief Given a type tag expression find the type tag itself.
12076 ///
12077 /// \param TypeExpr Type tag expression, as it appears in user's code.
12078 ///
12079 /// \param VD Declaration of an identifier that appears in a type tag.
12080 ///
12081 /// \param MagicValue Type tag magic value.
12082 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12083                             const ValueDecl **VD, uint64_t *MagicValue) {
12084   while(true) {
12085     if (!TypeExpr)
12086       return false;
12087 
12088     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12089 
12090     switch (TypeExpr->getStmtClass()) {
12091     case Stmt::UnaryOperatorClass: {
12092       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12093       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12094         TypeExpr = UO->getSubExpr();
12095         continue;
12096       }
12097       return false;
12098     }
12099 
12100     case Stmt::DeclRefExprClass: {
12101       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12102       *VD = DRE->getDecl();
12103       return true;
12104     }
12105 
12106     case Stmt::IntegerLiteralClass: {
12107       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12108       llvm::APInt MagicValueAPInt = IL->getValue();
12109       if (MagicValueAPInt.getActiveBits() <= 64) {
12110         *MagicValue = MagicValueAPInt.getZExtValue();
12111         return true;
12112       } else
12113         return false;
12114     }
12115 
12116     case Stmt::BinaryConditionalOperatorClass:
12117     case Stmt::ConditionalOperatorClass: {
12118       const AbstractConditionalOperator *ACO =
12119           cast<AbstractConditionalOperator>(TypeExpr);
12120       bool Result;
12121       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12122         if (Result)
12123           TypeExpr = ACO->getTrueExpr();
12124         else
12125           TypeExpr = ACO->getFalseExpr();
12126         continue;
12127       }
12128       return false;
12129     }
12130 
12131     case Stmt::BinaryOperatorClass: {
12132       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12133       if (BO->getOpcode() == BO_Comma) {
12134         TypeExpr = BO->getRHS();
12135         continue;
12136       }
12137       return false;
12138     }
12139 
12140     default:
12141       return false;
12142     }
12143   }
12144 }
12145 
12146 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12147 ///
12148 /// \param TypeExpr Expression that specifies a type tag.
12149 ///
12150 /// \param MagicValues Registered magic values.
12151 ///
12152 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12153 ///        kind.
12154 ///
12155 /// \param TypeInfo Information about the corresponding C type.
12156 ///
12157 /// \returns true if the corresponding C type was found.
12158 static bool GetMatchingCType(
12159         const IdentifierInfo *ArgumentKind,
12160         const Expr *TypeExpr, const ASTContext &Ctx,
12161         const llvm::DenseMap<Sema::TypeTagMagicValue,
12162                              Sema::TypeTagData> *MagicValues,
12163         bool &FoundWrongKind,
12164         Sema::TypeTagData &TypeInfo) {
12165   FoundWrongKind = false;
12166 
12167   // Variable declaration that has type_tag_for_datatype attribute.
12168   const ValueDecl *VD = nullptr;
12169 
12170   uint64_t MagicValue;
12171 
12172   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12173     return false;
12174 
12175   if (VD) {
12176     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12177       if (I->getArgumentKind() != ArgumentKind) {
12178         FoundWrongKind = true;
12179         return false;
12180       }
12181       TypeInfo.Type = I->getMatchingCType();
12182       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12183       TypeInfo.MustBeNull = I->getMustBeNull();
12184       return true;
12185     }
12186     return false;
12187   }
12188 
12189   if (!MagicValues)
12190     return false;
12191 
12192   llvm::DenseMap<Sema::TypeTagMagicValue,
12193                  Sema::TypeTagData>::const_iterator I =
12194       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12195   if (I == MagicValues->end())
12196     return false;
12197 
12198   TypeInfo = I->second;
12199   return true;
12200 }
12201 
12202 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12203                                       uint64_t MagicValue, QualType Type,
12204                                       bool LayoutCompatible,
12205                                       bool MustBeNull) {
12206   if (!TypeTagForDatatypeMagicValues)
12207     TypeTagForDatatypeMagicValues.reset(
12208         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12209 
12210   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12211   (*TypeTagForDatatypeMagicValues)[Magic] =
12212       TypeTagData(Type, LayoutCompatible, MustBeNull);
12213 }
12214 
12215 static bool IsSameCharType(QualType T1, QualType T2) {
12216   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12217   if (!BT1)
12218     return false;
12219 
12220   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12221   if (!BT2)
12222     return false;
12223 
12224   BuiltinType::Kind T1Kind = BT1->getKind();
12225   BuiltinType::Kind T2Kind = BT2->getKind();
12226 
12227   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12228          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12229          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12230          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12231 }
12232 
12233 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12234                                     const ArrayRef<const Expr *> ExprArgs,
12235                                     SourceLocation CallSiteLoc) {
12236   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12237   bool IsPointerAttr = Attr->getIsPointer();
12238 
12239   // Retrieve the argument representing the 'type_tag'.
12240   unsigned TypeTagIdxAST = Attr->typeTagIdx().getASTIndex();
12241   if (TypeTagIdxAST >= ExprArgs.size()) {
12242     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12243         << 0 << Attr->typeTagIdx().getSourceIndex();
12244     return;
12245   }
12246   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
12247   bool FoundWrongKind;
12248   TypeTagData TypeInfo;
12249   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12250                         TypeTagForDatatypeMagicValues.get(),
12251                         FoundWrongKind, TypeInfo)) {
12252     if (FoundWrongKind)
12253       Diag(TypeTagExpr->getExprLoc(),
12254            diag::warn_type_tag_for_datatype_wrong_kind)
12255         << TypeTagExpr->getSourceRange();
12256     return;
12257   }
12258 
12259   // Retrieve the argument representing the 'arg_idx'.
12260   unsigned ArgumentIdxAST = Attr->argumentIdx().getASTIndex();
12261   if (ArgumentIdxAST >= ExprArgs.size()) {
12262     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
12263         << 1 << Attr->argumentIdx().getSourceIndex();
12264     return;
12265   }
12266   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
12267   if (IsPointerAttr) {
12268     // Skip implicit cast of pointer to `void *' (as a function argument).
12269     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12270       if (ICE->getType()->isVoidPointerType() &&
12271           ICE->getCastKind() == CK_BitCast)
12272         ArgumentExpr = ICE->getSubExpr();
12273   }
12274   QualType ArgumentType = ArgumentExpr->getType();
12275 
12276   // Passing a `void*' pointer shouldn't trigger a warning.
12277   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12278     return;
12279 
12280   if (TypeInfo.MustBeNull) {
12281     // Type tag with matching void type requires a null pointer.
12282     if (!ArgumentExpr->isNullPointerConstant(Context,
12283                                              Expr::NPC_ValueDependentIsNotNull)) {
12284       Diag(ArgumentExpr->getExprLoc(),
12285            diag::warn_type_safety_null_pointer_required)
12286           << ArgumentKind->getName()
12287           << ArgumentExpr->getSourceRange()
12288           << TypeTagExpr->getSourceRange();
12289     }
12290     return;
12291   }
12292 
12293   QualType RequiredType = TypeInfo.Type;
12294   if (IsPointerAttr)
12295     RequiredType = Context.getPointerType(RequiredType);
12296 
12297   bool mismatch = false;
12298   if (!TypeInfo.LayoutCompatible) {
12299     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12300 
12301     // C++11 [basic.fundamental] p1:
12302     // Plain char, signed char, and unsigned char are three distinct types.
12303     //
12304     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12305     // char' depending on the current char signedness mode.
12306     if (mismatch)
12307       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12308                                            RequiredType->getPointeeType())) ||
12309           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12310         mismatch = false;
12311   } else
12312     if (IsPointerAttr)
12313       mismatch = !isLayoutCompatible(Context,
12314                                      ArgumentType->getPointeeType(),
12315                                      RequiredType->getPointeeType());
12316     else
12317       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12318 
12319   if (mismatch)
12320     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12321         << ArgumentType << ArgumentKind
12322         << TypeInfo.LayoutCompatible << RequiredType
12323         << ArgumentExpr->getSourceRange()
12324         << TypeTagExpr->getSourceRange();
12325 }
12326 
12327 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12328                                          CharUnits Alignment) {
12329   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12330 }
12331 
12332 void Sema::DiagnoseMisalignedMembers() {
12333   for (MisalignedMember &m : MisalignedMembers) {
12334     const NamedDecl *ND = m.RD;
12335     if (ND->getName().empty()) {
12336       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12337         ND = TD;
12338     }
12339     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12340         << m.MD << ND << m.E->getSourceRange();
12341   }
12342   MisalignedMembers.clear();
12343 }
12344 
12345 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12346   E = E->IgnoreParens();
12347   if (!T->isPointerType() && !T->isIntegerType())
12348     return;
12349   if (isa<UnaryOperator>(E) &&
12350       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12351     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12352     if (isa<MemberExpr>(Op)) {
12353       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12354                           MisalignedMember(Op));
12355       if (MA != MisalignedMembers.end() &&
12356           (T->isIntegerType() ||
12357            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
12358                                    Context.getTypeAlignInChars(
12359                                        T->getPointeeType()) <= MA->Alignment))))
12360         MisalignedMembers.erase(MA);
12361     }
12362   }
12363 }
12364 
12365 void Sema::RefersToMemberWithReducedAlignment(
12366     Expr *E,
12367     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12368         Action) {
12369   const auto *ME = dyn_cast<MemberExpr>(E);
12370   if (!ME)
12371     return;
12372 
12373   // No need to check expressions with an __unaligned-qualified type.
12374   if (E->getType().getQualifiers().hasUnaligned())
12375     return;
12376 
12377   // For a chain of MemberExpr like "a.b.c.d" this list
12378   // will keep FieldDecl's like [d, c, b].
12379   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12380   const MemberExpr *TopME = nullptr;
12381   bool AnyIsPacked = false;
12382   do {
12383     QualType BaseType = ME->getBase()->getType();
12384     if (ME->isArrow())
12385       BaseType = BaseType->getPointeeType();
12386     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12387     if (RD->isInvalidDecl())
12388       return;
12389 
12390     ValueDecl *MD = ME->getMemberDecl();
12391     auto *FD = dyn_cast<FieldDecl>(MD);
12392     // We do not care about non-data members.
12393     if (!FD || FD->isInvalidDecl())
12394       return;
12395 
12396     AnyIsPacked =
12397         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12398     ReverseMemberChain.push_back(FD);
12399 
12400     TopME = ME;
12401     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12402   } while (ME);
12403   assert(TopME && "We did not compute a topmost MemberExpr!");
12404 
12405   // Not the scope of this diagnostic.
12406   if (!AnyIsPacked)
12407     return;
12408 
12409   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12410   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12411   // TODO: The innermost base of the member expression may be too complicated.
12412   // For now, just disregard these cases. This is left for future
12413   // improvement.
12414   if (!DRE && !isa<CXXThisExpr>(TopBase))
12415       return;
12416 
12417   // Alignment expected by the whole expression.
12418   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12419 
12420   // No need to do anything else with this case.
12421   if (ExpectedAlignment.isOne())
12422     return;
12423 
12424   // Synthesize offset of the whole access.
12425   CharUnits Offset;
12426   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12427        I++) {
12428     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12429   }
12430 
12431   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12432   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12433       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12434 
12435   // The base expression of the innermost MemberExpr may give
12436   // stronger guarantees than the class containing the member.
12437   if (DRE && !TopME->isArrow()) {
12438     const ValueDecl *VD = DRE->getDecl();
12439     if (!VD->getType()->isReferenceType())
12440       CompleteObjectAlignment =
12441           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12442   }
12443 
12444   // Check if the synthesized offset fulfills the alignment.
12445   if (Offset % ExpectedAlignment != 0 ||
12446       // It may fulfill the offset it but the effective alignment may still be
12447       // lower than the expected expression alignment.
12448       CompleteObjectAlignment < ExpectedAlignment) {
12449     // If this happens, we want to determine a sensible culprit of this.
12450     // Intuitively, watching the chain of member expressions from right to
12451     // left, we start with the required alignment (as required by the field
12452     // type) but some packed attribute in that chain has reduced the alignment.
12453     // It may happen that another packed structure increases it again. But if
12454     // we are here such increase has not been enough. So pointing the first
12455     // FieldDecl that either is packed or else its RecordDecl is,
12456     // seems reasonable.
12457     FieldDecl *FD = nullptr;
12458     CharUnits Alignment;
12459     for (FieldDecl *FDI : ReverseMemberChain) {
12460       if (FDI->hasAttr<PackedAttr>() ||
12461           FDI->getParent()->hasAttr<PackedAttr>()) {
12462         FD = FDI;
12463         Alignment = std::min(
12464             Context.getTypeAlignInChars(FD->getType()),
12465             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12466         break;
12467       }
12468     }
12469     assert(FD && "We did not find a packed FieldDecl!");
12470     Action(E, FD->getParent(), FD, Alignment);
12471   }
12472 }
12473 
12474 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12475   using namespace std::placeholders;
12476 
12477   RefersToMemberWithReducedAlignment(
12478       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12479                      _2, _3, _4));
12480 }
12481