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/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/SyncScope.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallBitVector.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/Support/ConvertUTF.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/Locale.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace clang;
46 using namespace sema;
47 
48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49                                                     unsigned ByteNo) const {
50   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51                                Context.getTargetInfo());
52 }
53 
54 /// Checks that a call expression's argument count is the desired number.
55 /// This is useful when doing custom type-checking.  Returns true on error.
56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57   unsigned argCount = call->getNumArgs();
58   if (argCount == desiredArgCount) return false;
59 
60   if (argCount < desiredArgCount)
61     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62         << 0 /*function call*/ << desiredArgCount << argCount
63         << call->getSourceRange();
64 
65   // Highlight all the excess arguments.
66   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67                     call->getArg(argCount - 1)->getLocEnd());
68 
69   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70     << 0 /*function call*/ << desiredArgCount << argCount
71     << call->getArg(1)->getSourceRange();
72 }
73 
74 /// Check that the first argument to __builtin_annotation is an integer
75 /// and the second argument is a non-wide string literal.
76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77   if (checkArgCount(S, TheCall, 2))
78     return true;
79 
80   // First argument should be an integer.
81   Expr *ValArg = TheCall->getArg(0);
82   QualType Ty = ValArg->getType();
83   if (!Ty->isIntegerType()) {
84     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85       << ValArg->getSourceRange();
86     return true;
87   }
88 
89   // Second argument should be a constant string.
90   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92   if (!Literal || !Literal->isAscii()) {
93     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94       << StrArg->getSourceRange();
95     return true;
96   }
97 
98   TheCall->setType(Ty);
99   return false;
100 }
101 
102 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103   // We need at least one argument.
104   if (TheCall->getNumArgs() < 1) {
105     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106         << 0 << 1 << TheCall->getNumArgs()
107         << TheCall->getCallee()->getSourceRange();
108     return true;
109   }
110 
111   // All arguments should be wide string literals.
112   for (Expr *Arg : TheCall->arguments()) {
113     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114     if (!Literal || !Literal->isWide()) {
115       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116           << Arg->getSourceRange();
117       return true;
118     }
119   }
120 
121   return false;
122 }
123 
124 /// Check that the argument to __builtin_addressof is a glvalue, and set the
125 /// result type to the corresponding pointer type.
126 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127   if (checkArgCount(S, TheCall, 1))
128     return true;
129 
130   ExprResult Arg(TheCall->getArg(0));
131   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132   if (ResultType.isNull())
133     return true;
134 
135   TheCall->setArg(0, Arg.get());
136   TheCall->setType(ResultType);
137   return false;
138 }
139 
140 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141   if (checkArgCount(S, TheCall, 3))
142     return true;
143 
144   // First two arguments should be integers.
145   for (unsigned I = 0; I < 2; ++I) {
146     Expr *Arg = TheCall->getArg(I);
147     QualType Ty = Arg->getType();
148     if (!Ty->isIntegerType()) {
149       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150           << Ty << Arg->getSourceRange();
151       return true;
152     }
153   }
154 
155   // Third argument should be a pointer to a non-const integer.
156   // IRGen correctly handles volatile, restrict, and address spaces, and
157   // the other qualifiers aren't possible.
158   {
159     Expr *Arg = TheCall->getArg(2);
160     QualType Ty = Arg->getType();
161     const auto *PtrTy = Ty->getAs<PointerType>();
162     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163           !PtrTy->getPointeeType().isConstQualified())) {
164       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165           << Ty << Arg->getSourceRange();
166       return true;
167     }
168   }
169 
170   return false;
171 }
172 
173 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 		                  CallExpr *TheCall, unsigned SizeIdx,
175                                   unsigned DstSizeIdx) {
176   if (TheCall->getNumArgs() <= SizeIdx ||
177       TheCall->getNumArgs() <= DstSizeIdx)
178     return;
179 
180   const Expr *SizeArg = TheCall->getArg(SizeIdx);
181   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182 
183   llvm::APSInt Size, DstSize;
184 
185   // find out if both sizes are known at compile time
186   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188     return;
189 
190   if (Size.ule(DstSize))
191     return;
192 
193   // confirmed overflow so generate the diagnostic.
194   IdentifierInfo *FnName = FDecl->getIdentifier();
195   SourceLocation SL = TheCall->getLocStart();
196   SourceRange SR = TheCall->getSourceRange();
197 
198   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199 }
200 
201 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202   if (checkArgCount(S, BuiltinCall, 2))
203     return true;
204 
205   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207   Expr *Call = BuiltinCall->getArg(0);
208   Expr *Chain = BuiltinCall->getArg(1);
209 
210   if (Call->getStmtClass() != Stmt::CallExprClass) {
211     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212         << Call->getSourceRange();
213     return true;
214   }
215 
216   auto CE = cast<CallExpr>(Call);
217   if (CE->getCallee()->getType()->isBlockPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219         << Call->getSourceRange();
220     return true;
221   }
222 
223   const Decl *TargetDecl = CE->getCalleeDecl();
224   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225     if (FD->getBuiltinID()) {
226       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227           << Call->getSourceRange();
228       return true;
229     }
230 
231   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233         << Call->getSourceRange();
234     return true;
235   }
236 
237   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238   if (ChainResult.isInvalid())
239     return true;
240   if (!ChainResult.get()->getType()->isPointerType()) {
241     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242         << Chain->getSourceRange();
243     return true;
244   }
245 
246   QualType ReturnTy = CE->getCallReturnType(S.Context);
247   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248   QualType BuiltinTy = S.Context.getFunctionType(
249       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251 
252   Builtin =
253       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254 
255   BuiltinCall->setType(CE->getType());
256   BuiltinCall->setValueKind(CE->getValueKind());
257   BuiltinCall->setObjectKind(CE->getObjectKind());
258   BuiltinCall->setCallee(Builtin);
259   BuiltinCall->setArg(1, ChainResult.get());
260 
261   return false;
262 }
263 
264 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265                                      Scope::ScopeFlags NeededScopeFlags,
266                                      unsigned DiagID) {
267   // Scopes aren't available during instantiation. Fortunately, builtin
268   // functions cannot be template args so they cannot be formed through template
269   // instantiation. Therefore checking once during the parse is sufficient.
270   if (SemaRef.inTemplateInstantiation())
271     return false;
272 
273   Scope *S = SemaRef.getCurScope();
274   while (S && !S->isSEHExceptScope())
275     S = S->getParent();
276   if (!S || !(S->getFlags() & NeededScopeFlags)) {
277     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279         << DRE->getDecl()->getIdentifier();
280     return true;
281   }
282 
283   return false;
284 }
285 
286 static inline bool isBlockPointer(Expr *Arg) {
287   return Arg->getType()->isBlockPointerType();
288 }
289 
290 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291 /// void*, which is a requirement of device side enqueue.
292 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293   const BlockPointerType *BPT =
294       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295   ArrayRef<QualType> Params =
296       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297   unsigned ArgCounter = 0;
298   bool IllegalParams = false;
299   // Iterate through the block parameters until either one is found that is not
300   // a local void*, or the block is valid.
301   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302        I != E; ++I, ++ArgCounter) {
303     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305             LangAS::opencl_local) {
306       // Get the location of the error. If a block literal has been passed
307       // (BlockExpr) then we can point straight to the offending argument,
308       // else we just point to the variable reference.
309       SourceLocation ErrorLoc;
310       if (isa<BlockExpr>(BlockArg)) {
311         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313       } else if (isa<DeclRefExpr>(BlockArg)) {
314         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315       }
316       S.Diag(ErrorLoc,
317              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318       IllegalParams = true;
319     }
320   }
321 
322   return IllegalParams;
323 }
324 
325 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329     return true;
330   }
331   return false;
332 }
333 
334 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335   if (checkArgCount(S, TheCall, 2))
336     return true;
337 
338   if (checkOpenCLSubgroupExt(S, TheCall))
339     return true;
340 
341   // First argument is an ndrange_t type.
342   Expr *NDRangeArg = TheCall->getArg(0);
343   if (NDRangeArg->getType().getAsString() != "ndrange_t") {
344     S.Diag(NDRangeArg->getLocStart(),
345            diag::err_opencl_builtin_expected_type)
346         << TheCall->getDirectCallee() << "'ndrange_t'";
347     return true;
348   }
349 
350   Expr *BlockArg = TheCall->getArg(1);
351   if (!isBlockPointer(BlockArg)) {
352     S.Diag(BlockArg->getLocStart(),
353            diag::err_opencl_builtin_expected_type)
354         << TheCall->getDirectCallee() << "block";
355     return true;
356   }
357   return checkOpenCLBlockArgs(S, BlockArg);
358 }
359 
360 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361 /// get_kernel_work_group_size
362 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
363 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364   if (checkArgCount(S, TheCall, 1))
365     return true;
366 
367   Expr *BlockArg = TheCall->getArg(0);
368   if (!isBlockPointer(BlockArg)) {
369     S.Diag(BlockArg->getLocStart(),
370            diag::err_opencl_builtin_expected_type)
371         << TheCall->getDirectCallee() << "block";
372     return true;
373   }
374   return checkOpenCLBlockArgs(S, BlockArg);
375 }
376 
377 /// Diagnose integer type and any valid implicit conversion to it.
378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379                                       const QualType &IntType);
380 
381 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
382                                             unsigned Start, unsigned End) {
383   bool IllegalParams = false;
384   for (unsigned I = Start; I <= End; ++I)
385     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386                                               S.Context.getSizeType());
387   return IllegalParams;
388 }
389 
390 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391 /// 'local void*' parameter of passed block.
392 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393                                            Expr *BlockArg,
394                                            unsigned NumNonVarArgs) {
395   const BlockPointerType *BPT =
396       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397   unsigned NumBlockParams =
398       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399   unsigned TotalNumArgs = TheCall->getNumArgs();
400 
401   // For each argument passed to the block, a corresponding uint needs to
402   // be passed to describe the size of the local memory.
403   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404     S.Diag(TheCall->getLocStart(),
405            diag::err_opencl_enqueue_kernel_local_size_args);
406     return true;
407   }
408 
409   // Check that the sizes of the local memory are specified by integers.
410   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411                                          TotalNumArgs - 1);
412 }
413 
414 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415 /// overload formats specified in Table 6.13.17.1.
416 /// int enqueue_kernel(queue_t queue,
417 ///                    kernel_enqueue_flags_t flags,
418 ///                    const ndrange_t ndrange,
419 ///                    void (^block)(void))
420 /// int enqueue_kernel(queue_t queue,
421 ///                    kernel_enqueue_flags_t flags,
422 ///                    const ndrange_t ndrange,
423 ///                    uint num_events_in_wait_list,
424 ///                    clk_event_t *event_wait_list,
425 ///                    clk_event_t *event_ret,
426 ///                    void (^block)(void))
427 /// int enqueue_kernel(queue_t queue,
428 ///                    kernel_enqueue_flags_t flags,
429 ///                    const ndrange_t ndrange,
430 ///                    void (^block)(local void*, ...),
431 ///                    uint size0, ...)
432 /// int enqueue_kernel(queue_t queue,
433 ///                    kernel_enqueue_flags_t flags,
434 ///                    const ndrange_t ndrange,
435 ///                    uint num_events_in_wait_list,
436 ///                    clk_event_t *event_wait_list,
437 ///                    clk_event_t *event_ret,
438 ///                    void (^block)(local void*, ...),
439 ///                    uint size0, ...)
440 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441   unsigned NumArgs = TheCall->getNumArgs();
442 
443   if (NumArgs < 4) {
444     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445     return true;
446   }
447 
448   Expr *Arg0 = TheCall->getArg(0);
449   Expr *Arg1 = TheCall->getArg(1);
450   Expr *Arg2 = TheCall->getArg(2);
451   Expr *Arg3 = TheCall->getArg(3);
452 
453   // First argument always needs to be a queue_t type.
454   if (!Arg0->getType()->isQueueT()) {
455     S.Diag(TheCall->getArg(0)->getLocStart(),
456            diag::err_opencl_builtin_expected_type)
457         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
458     return true;
459   }
460 
461   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462   if (!Arg1->getType()->isIntegerType()) {
463     S.Diag(TheCall->getArg(1)->getLocStart(),
464            diag::err_opencl_builtin_expected_type)
465         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
466     return true;
467   }
468 
469   // Third argument is always an ndrange_t type.
470   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
471     S.Diag(TheCall->getArg(2)->getLocStart(),
472            diag::err_opencl_builtin_expected_type)
473         << TheCall->getDirectCallee() << "'ndrange_t'";
474     return true;
475   }
476 
477   // With four arguments, there is only one form that the function could be
478   // called in: no events and no variable arguments.
479   if (NumArgs == 4) {
480     // check that the last argument is the right block type.
481     if (!isBlockPointer(Arg3)) {
482       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483           << TheCall->getDirectCallee() << "block";
484       return true;
485     }
486     // we have a block type, check the prototype
487     const BlockPointerType *BPT =
488         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490       S.Diag(Arg3->getLocStart(),
491              diag::err_opencl_enqueue_kernel_blocks_no_args);
492       return true;
493     }
494     return false;
495   }
496   // we can have block + varargs.
497   if (isBlockPointer(Arg3))
498     return (checkOpenCLBlockArgs(S, Arg3) ||
499             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500   // last two cases with either exactly 7 args or 7 args and varargs.
501   if (NumArgs >= 7) {
502     // check common block argument.
503     Expr *Arg6 = TheCall->getArg(6);
504     if (!isBlockPointer(Arg6)) {
505       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506           << TheCall->getDirectCallee() << "block";
507       return true;
508     }
509     if (checkOpenCLBlockArgs(S, Arg6))
510       return true;
511 
512     // Forth argument has to be any integer type.
513     if (!Arg3->getType()->isIntegerType()) {
514       S.Diag(TheCall->getArg(3)->getLocStart(),
515              diag::err_opencl_builtin_expected_type)
516           << TheCall->getDirectCallee() << "integer";
517       return true;
518     }
519     // check remaining common arguments.
520     Expr *Arg4 = TheCall->getArg(4);
521     Expr *Arg5 = TheCall->getArg(5);
522 
523     // Fifth argument is always passed as a pointer to clk_event_t.
524     if (!Arg4->isNullPointerConstant(S.Context,
525                                      Expr::NPC_ValueDependentIsNotNull) &&
526         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
527       S.Diag(TheCall->getArg(4)->getLocStart(),
528              diag::err_opencl_builtin_expected_type)
529           << TheCall->getDirectCallee()
530           << S.Context.getPointerType(S.Context.OCLClkEventTy);
531       return true;
532     }
533 
534     // Sixth argument is always passed as a pointer to clk_event_t.
535     if (!Arg5->isNullPointerConstant(S.Context,
536                                      Expr::NPC_ValueDependentIsNotNull) &&
537         !(Arg5->getType()->isPointerType() &&
538           Arg5->getType()->getPointeeType()->isClkEventT())) {
539       S.Diag(TheCall->getArg(5)->getLocStart(),
540              diag::err_opencl_builtin_expected_type)
541           << TheCall->getDirectCallee()
542           << S.Context.getPointerType(S.Context.OCLClkEventTy);
543       return true;
544     }
545 
546     if (NumArgs == 7)
547       return false;
548 
549     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550   }
551 
552   // None of the specific case has been detected, give generic error
553   S.Diag(TheCall->getLocStart(),
554          diag::err_opencl_enqueue_kernel_incorrect_args);
555   return true;
556 }
557 
558 /// Returns OpenCL access qual.
559 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
560     return D->getAttr<OpenCLAccessAttr>();
561 }
562 
563 /// Returns true if pipe element type is different from the pointer.
564 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565   const Expr *Arg0 = Call->getArg(0);
566   // First argument type should always be pipe.
567   if (!Arg0->getType()->isPipeType()) {
568     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
569         << Call->getDirectCallee() << Arg0->getSourceRange();
570     return true;
571   }
572   OpenCLAccessAttr *AccessQual =
573       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574   // Validates the access qualifier is compatible with the call.
575   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576   // read_only and write_only, and assumed to be read_only if no qualifier is
577   // specified.
578   switch (Call->getDirectCallee()->getBuiltinID()) {
579   case Builtin::BIread_pipe:
580   case Builtin::BIreserve_read_pipe:
581   case Builtin::BIcommit_read_pipe:
582   case Builtin::BIwork_group_reserve_read_pipe:
583   case Builtin::BIsub_group_reserve_read_pipe:
584   case Builtin::BIwork_group_commit_read_pipe:
585   case Builtin::BIsub_group_commit_read_pipe:
586     if (!(!AccessQual || AccessQual->isReadOnly())) {
587       S.Diag(Arg0->getLocStart(),
588              diag::err_opencl_builtin_pipe_invalid_access_modifier)
589           << "read_only" << Arg0->getSourceRange();
590       return true;
591     }
592     break;
593   case Builtin::BIwrite_pipe:
594   case Builtin::BIreserve_write_pipe:
595   case Builtin::BIcommit_write_pipe:
596   case Builtin::BIwork_group_reserve_write_pipe:
597   case Builtin::BIsub_group_reserve_write_pipe:
598   case Builtin::BIwork_group_commit_write_pipe:
599   case Builtin::BIsub_group_commit_write_pipe:
600     if (!(AccessQual && AccessQual->isWriteOnly())) {
601       S.Diag(Arg0->getLocStart(),
602              diag::err_opencl_builtin_pipe_invalid_access_modifier)
603           << "write_only" << Arg0->getSourceRange();
604       return true;
605     }
606     break;
607   default:
608     break;
609   }
610   return false;
611 }
612 
613 /// Returns true if pipe element type is different from the pointer.
614 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615   const Expr *Arg0 = Call->getArg(0);
616   const Expr *ArgIdx = Call->getArg(Idx);
617   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
618   const QualType EltTy = PipeTy->getElementType();
619   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
620   // The Idx argument should be a pointer and the type of the pointer and
621   // the type of pipe element should also be the same.
622   if (!ArgTy ||
623       !S.Context.hasSameType(
624           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
625     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
626         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
627         << ArgIdx->getType() << ArgIdx->getSourceRange();
628     return true;
629   }
630   return false;
631 }
632 
633 // \brief Performs semantic analysis for the read/write_pipe call.
634 // \param S Reference to the semantic analyzer.
635 // \param Call A pointer to the builtin call.
636 // \return True if a semantic error has been found, false otherwise.
637 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
638   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639   // functions have two forms.
640   switch (Call->getNumArgs()) {
641   case 2: {
642     if (checkOpenCLPipeArg(S, Call))
643       return true;
644     // The call with 2 arguments should be
645     // read/write_pipe(pipe T, T*).
646     // Check packet type T.
647     if (checkOpenCLPipePacketType(S, Call, 1))
648       return true;
649   } break;
650 
651   case 4: {
652     if (checkOpenCLPipeArg(S, Call))
653       return true;
654     // The call with 4 arguments should be
655     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656     // Check reserve_id_t.
657     if (!Call->getArg(1)->getType()->isReserveIDT()) {
658       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
659           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
660           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
661       return true;
662     }
663 
664     // Check the index.
665     const Expr *Arg2 = Call->getArg(2);
666     if (!Arg2->getType()->isIntegerType() &&
667         !Arg2->getType()->isUnsignedIntegerType()) {
668       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
669           << Call->getDirectCallee() << S.Context.UnsignedIntTy
670           << Arg2->getType() << Arg2->getSourceRange();
671       return true;
672     }
673 
674     // Check packet type T.
675     if (checkOpenCLPipePacketType(S, Call, 3))
676       return true;
677   } break;
678   default:
679     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
680         << Call->getDirectCallee() << Call->getSourceRange();
681     return true;
682   }
683 
684   return false;
685 }
686 
687 // \brief Performs a semantic analysis on the {work_group_/sub_group_
688 //        /_}reserve_{read/write}_pipe
689 // \param S Reference to the semantic analyzer.
690 // \param Call The call to the builtin function to be analyzed.
691 // \return True if a semantic error was found, false otherwise.
692 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693   if (checkArgCount(S, Call, 2))
694     return true;
695 
696   if (checkOpenCLPipeArg(S, Call))
697     return true;
698 
699   // Check the reserve size.
700   if (!Call->getArg(1)->getType()->isIntegerType() &&
701       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
703         << Call->getDirectCallee() << S.Context.UnsignedIntTy
704         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
705     return true;
706   }
707 
708   // Since return type of reserve_read/write_pipe built-in function is
709   // reserve_id_t, which is not defined in the builtin def file , we used int
710   // as return type and need to override the return type of these functions.
711   Call->setType(S.Context.OCLReserveIDTy);
712 
713   return false;
714 }
715 
716 // \brief Performs a semantic analysis on {work_group_/sub_group_
717 //        /_}commit_{read/write}_pipe
718 // \param S Reference to the semantic analyzer.
719 // \param Call The call to the builtin function to be analyzed.
720 // \return True if a semantic error was found, false otherwise.
721 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722   if (checkArgCount(S, Call, 2))
723     return true;
724 
725   if (checkOpenCLPipeArg(S, Call))
726     return true;
727 
728   // Check reserve_id_t.
729   if (!Call->getArg(1)->getType()->isReserveIDT()) {
730     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
731         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
732         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
733     return true;
734   }
735 
736   return false;
737 }
738 
739 // \brief Performs a semantic analysis on the call to built-in Pipe
740 //        Query Functions.
741 // \param S Reference to the semantic analyzer.
742 // \param Call The call to the builtin function to be analyzed.
743 // \return True if a semantic error was found, false otherwise.
744 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745   if (checkArgCount(S, Call, 1))
746     return true;
747 
748   if (!Call->getArg(0)->getType()->isPipeType()) {
749     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
750         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
751     return true;
752   }
753 
754   return false;
755 }
756 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
757 // \brief Performs semantic analysis for the to_global/local/private call.
758 // \param S Reference to the semantic analyzer.
759 // \param BuiltinID ID of the builtin function.
760 // \param Call A pointer to the builtin call.
761 // \return True if a semantic error has been found, false otherwise.
762 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763                                     CallExpr *Call) {
764   if (Call->getNumArgs() != 1) {
765     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766         << Call->getDirectCallee() << Call->getSourceRange();
767     return true;
768   }
769 
770   auto RT = Call->getArg(0)->getType();
771   if (!RT->isPointerType() || RT->getPointeeType()
772       .getAddressSpace() == LangAS::opencl_constant) {
773     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775     return true;
776   }
777 
778   RT = RT->getPointeeType();
779   auto Qual = RT.getQualifiers();
780   switch (BuiltinID) {
781   case Builtin::BIto_global:
782     Qual.setAddressSpace(LangAS::opencl_global);
783     break;
784   case Builtin::BIto_local:
785     Qual.setAddressSpace(LangAS::opencl_local);
786     break;
787   default:
788     Qual.removeAddressSpace();
789   }
790   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
791       RT.getUnqualifiedType(), Qual)));
792 
793   return false;
794 }
795 
796 ExprResult
797 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
798                                CallExpr *TheCall) {
799   ExprResult TheCallResult(TheCall);
800 
801   // Find out if any arguments are required to be integer constant expressions.
802   unsigned ICEArguments = 0;
803   ASTContext::GetBuiltinTypeError Error;
804   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
805   if (Error != ASTContext::GE_None)
806     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
807 
808   // If any arguments are required to be ICE's, check and diagnose.
809   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
810     // Skip arguments not required to be ICE's.
811     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
812 
813     llvm::APSInt Result;
814     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
815       return true;
816     ICEArguments &= ~(1 << ArgNo);
817   }
818 
819   switch (BuiltinID) {
820   case Builtin::BI__builtin___CFStringMakeConstantString:
821     assert(TheCall->getNumArgs() == 1 &&
822            "Wrong # arguments to builtin CFStringMakeConstantString");
823     if (CheckObjCString(TheCall->getArg(0)))
824       return ExprError();
825     break;
826   case Builtin::BI__builtin_ms_va_start:
827   case Builtin::BI__builtin_stdarg_start:
828   case Builtin::BI__builtin_va_start:
829     if (SemaBuiltinVAStart(BuiltinID, TheCall))
830       return ExprError();
831     break;
832   case Builtin::BI__va_start: {
833     switch (Context.getTargetInfo().getTriple().getArch()) {
834     case llvm::Triple::arm:
835     case llvm::Triple::thumb:
836       if (SemaBuiltinVAStartARM(TheCall))
837         return ExprError();
838       break;
839     default:
840       if (SemaBuiltinVAStart(BuiltinID, TheCall))
841         return ExprError();
842       break;
843     }
844     break;
845   }
846   case Builtin::BI__builtin_isgreater:
847   case Builtin::BI__builtin_isgreaterequal:
848   case Builtin::BI__builtin_isless:
849   case Builtin::BI__builtin_islessequal:
850   case Builtin::BI__builtin_islessgreater:
851   case Builtin::BI__builtin_isunordered:
852     if (SemaBuiltinUnorderedCompare(TheCall))
853       return ExprError();
854     break;
855   case Builtin::BI__builtin_fpclassify:
856     if (SemaBuiltinFPClassification(TheCall, 6))
857       return ExprError();
858     break;
859   case Builtin::BI__builtin_isfinite:
860   case Builtin::BI__builtin_isinf:
861   case Builtin::BI__builtin_isinf_sign:
862   case Builtin::BI__builtin_isnan:
863   case Builtin::BI__builtin_isnormal:
864     if (SemaBuiltinFPClassification(TheCall, 1))
865       return ExprError();
866     break;
867   case Builtin::BI__builtin_shufflevector:
868     return SemaBuiltinShuffleVector(TheCall);
869     // TheCall will be freed by the smart pointer here, but that's fine, since
870     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
871   case Builtin::BI__builtin_prefetch:
872     if (SemaBuiltinPrefetch(TheCall))
873       return ExprError();
874     break;
875   case Builtin::BI__builtin_alloca_with_align:
876     if (SemaBuiltinAllocaWithAlign(TheCall))
877       return ExprError();
878     break;
879   case Builtin::BI__assume:
880   case Builtin::BI__builtin_assume:
881     if (SemaBuiltinAssume(TheCall))
882       return ExprError();
883     break;
884   case Builtin::BI__builtin_assume_aligned:
885     if (SemaBuiltinAssumeAligned(TheCall))
886       return ExprError();
887     break;
888   case Builtin::BI__builtin_object_size:
889     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
890       return ExprError();
891     break;
892   case Builtin::BI__builtin_longjmp:
893     if (SemaBuiltinLongjmp(TheCall))
894       return ExprError();
895     break;
896   case Builtin::BI__builtin_setjmp:
897     if (SemaBuiltinSetjmp(TheCall))
898       return ExprError();
899     break;
900   case Builtin::BI_setjmp:
901   case Builtin::BI_setjmpex:
902     if (checkArgCount(*this, TheCall, 1))
903       return true;
904     break;
905 
906   case Builtin::BI__builtin_classify_type:
907     if (checkArgCount(*this, TheCall, 1)) return true;
908     TheCall->setType(Context.IntTy);
909     break;
910   case Builtin::BI__builtin_constant_p:
911     if (checkArgCount(*this, TheCall, 1)) return true;
912     TheCall->setType(Context.IntTy);
913     break;
914   case Builtin::BI__sync_fetch_and_add:
915   case Builtin::BI__sync_fetch_and_add_1:
916   case Builtin::BI__sync_fetch_and_add_2:
917   case Builtin::BI__sync_fetch_and_add_4:
918   case Builtin::BI__sync_fetch_and_add_8:
919   case Builtin::BI__sync_fetch_and_add_16:
920   case Builtin::BI__sync_fetch_and_sub:
921   case Builtin::BI__sync_fetch_and_sub_1:
922   case Builtin::BI__sync_fetch_and_sub_2:
923   case Builtin::BI__sync_fetch_and_sub_4:
924   case Builtin::BI__sync_fetch_and_sub_8:
925   case Builtin::BI__sync_fetch_and_sub_16:
926   case Builtin::BI__sync_fetch_and_or:
927   case Builtin::BI__sync_fetch_and_or_1:
928   case Builtin::BI__sync_fetch_and_or_2:
929   case Builtin::BI__sync_fetch_and_or_4:
930   case Builtin::BI__sync_fetch_and_or_8:
931   case Builtin::BI__sync_fetch_and_or_16:
932   case Builtin::BI__sync_fetch_and_and:
933   case Builtin::BI__sync_fetch_and_and_1:
934   case Builtin::BI__sync_fetch_and_and_2:
935   case Builtin::BI__sync_fetch_and_and_4:
936   case Builtin::BI__sync_fetch_and_and_8:
937   case Builtin::BI__sync_fetch_and_and_16:
938   case Builtin::BI__sync_fetch_and_xor:
939   case Builtin::BI__sync_fetch_and_xor_1:
940   case Builtin::BI__sync_fetch_and_xor_2:
941   case Builtin::BI__sync_fetch_and_xor_4:
942   case Builtin::BI__sync_fetch_and_xor_8:
943   case Builtin::BI__sync_fetch_and_xor_16:
944   case Builtin::BI__sync_fetch_and_nand:
945   case Builtin::BI__sync_fetch_and_nand_1:
946   case Builtin::BI__sync_fetch_and_nand_2:
947   case Builtin::BI__sync_fetch_and_nand_4:
948   case Builtin::BI__sync_fetch_and_nand_8:
949   case Builtin::BI__sync_fetch_and_nand_16:
950   case Builtin::BI__sync_add_and_fetch:
951   case Builtin::BI__sync_add_and_fetch_1:
952   case Builtin::BI__sync_add_and_fetch_2:
953   case Builtin::BI__sync_add_and_fetch_4:
954   case Builtin::BI__sync_add_and_fetch_8:
955   case Builtin::BI__sync_add_and_fetch_16:
956   case Builtin::BI__sync_sub_and_fetch:
957   case Builtin::BI__sync_sub_and_fetch_1:
958   case Builtin::BI__sync_sub_and_fetch_2:
959   case Builtin::BI__sync_sub_and_fetch_4:
960   case Builtin::BI__sync_sub_and_fetch_8:
961   case Builtin::BI__sync_sub_and_fetch_16:
962   case Builtin::BI__sync_and_and_fetch:
963   case Builtin::BI__sync_and_and_fetch_1:
964   case Builtin::BI__sync_and_and_fetch_2:
965   case Builtin::BI__sync_and_and_fetch_4:
966   case Builtin::BI__sync_and_and_fetch_8:
967   case Builtin::BI__sync_and_and_fetch_16:
968   case Builtin::BI__sync_or_and_fetch:
969   case Builtin::BI__sync_or_and_fetch_1:
970   case Builtin::BI__sync_or_and_fetch_2:
971   case Builtin::BI__sync_or_and_fetch_4:
972   case Builtin::BI__sync_or_and_fetch_8:
973   case Builtin::BI__sync_or_and_fetch_16:
974   case Builtin::BI__sync_xor_and_fetch:
975   case Builtin::BI__sync_xor_and_fetch_1:
976   case Builtin::BI__sync_xor_and_fetch_2:
977   case Builtin::BI__sync_xor_and_fetch_4:
978   case Builtin::BI__sync_xor_and_fetch_8:
979   case Builtin::BI__sync_xor_and_fetch_16:
980   case Builtin::BI__sync_nand_and_fetch:
981   case Builtin::BI__sync_nand_and_fetch_1:
982   case Builtin::BI__sync_nand_and_fetch_2:
983   case Builtin::BI__sync_nand_and_fetch_4:
984   case Builtin::BI__sync_nand_and_fetch_8:
985   case Builtin::BI__sync_nand_and_fetch_16:
986   case Builtin::BI__sync_val_compare_and_swap:
987   case Builtin::BI__sync_val_compare_and_swap_1:
988   case Builtin::BI__sync_val_compare_and_swap_2:
989   case Builtin::BI__sync_val_compare_and_swap_4:
990   case Builtin::BI__sync_val_compare_and_swap_8:
991   case Builtin::BI__sync_val_compare_and_swap_16:
992   case Builtin::BI__sync_bool_compare_and_swap:
993   case Builtin::BI__sync_bool_compare_and_swap_1:
994   case Builtin::BI__sync_bool_compare_and_swap_2:
995   case Builtin::BI__sync_bool_compare_and_swap_4:
996   case Builtin::BI__sync_bool_compare_and_swap_8:
997   case Builtin::BI__sync_bool_compare_and_swap_16:
998   case Builtin::BI__sync_lock_test_and_set:
999   case Builtin::BI__sync_lock_test_and_set_1:
1000   case Builtin::BI__sync_lock_test_and_set_2:
1001   case Builtin::BI__sync_lock_test_and_set_4:
1002   case Builtin::BI__sync_lock_test_and_set_8:
1003   case Builtin::BI__sync_lock_test_and_set_16:
1004   case Builtin::BI__sync_lock_release:
1005   case Builtin::BI__sync_lock_release_1:
1006   case Builtin::BI__sync_lock_release_2:
1007   case Builtin::BI__sync_lock_release_4:
1008   case Builtin::BI__sync_lock_release_8:
1009   case Builtin::BI__sync_lock_release_16:
1010   case Builtin::BI__sync_swap:
1011   case Builtin::BI__sync_swap_1:
1012   case Builtin::BI__sync_swap_2:
1013   case Builtin::BI__sync_swap_4:
1014   case Builtin::BI__sync_swap_8:
1015   case Builtin::BI__sync_swap_16:
1016     return SemaBuiltinAtomicOverloaded(TheCallResult);
1017   case Builtin::BI__builtin_nontemporal_load:
1018   case Builtin::BI__builtin_nontemporal_store:
1019     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1020 #define BUILTIN(ID, TYPE, ATTRS)
1021 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1022   case Builtin::BI##ID: \
1023     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1024 #include "clang/Basic/Builtins.def"
1025   case Builtin::BI__annotation:
1026     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1027       return ExprError();
1028     break;
1029   case Builtin::BI__builtin_annotation:
1030     if (SemaBuiltinAnnotation(*this, TheCall))
1031       return ExprError();
1032     break;
1033   case Builtin::BI__builtin_addressof:
1034     if (SemaBuiltinAddressof(*this, TheCall))
1035       return ExprError();
1036     break;
1037   case Builtin::BI__builtin_add_overflow:
1038   case Builtin::BI__builtin_sub_overflow:
1039   case Builtin::BI__builtin_mul_overflow:
1040     if (SemaBuiltinOverflow(*this, TheCall))
1041       return ExprError();
1042     break;
1043   case Builtin::BI__builtin_operator_new:
1044   case Builtin::BI__builtin_operator_delete:
1045     if (!getLangOpts().CPlusPlus) {
1046       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1047         << (BuiltinID == Builtin::BI__builtin_operator_new
1048                 ? "__builtin_operator_new"
1049                 : "__builtin_operator_delete")
1050         << "C++";
1051       return ExprError();
1052     }
1053     // CodeGen assumes it can find the global new and delete to call,
1054     // so ensure that they are declared.
1055     DeclareGlobalNewDelete();
1056     break;
1057 
1058   // check secure string manipulation functions where overflows
1059   // are detectable at compile time
1060   case Builtin::BI__builtin___memcpy_chk:
1061   case Builtin::BI__builtin___memmove_chk:
1062   case Builtin::BI__builtin___memset_chk:
1063   case Builtin::BI__builtin___strlcat_chk:
1064   case Builtin::BI__builtin___strlcpy_chk:
1065   case Builtin::BI__builtin___strncat_chk:
1066   case Builtin::BI__builtin___strncpy_chk:
1067   case Builtin::BI__builtin___stpncpy_chk:
1068     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1069     break;
1070   case Builtin::BI__builtin___memccpy_chk:
1071     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1072     break;
1073   case Builtin::BI__builtin___snprintf_chk:
1074   case Builtin::BI__builtin___vsnprintf_chk:
1075     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1076     break;
1077   case Builtin::BI__builtin_call_with_static_chain:
1078     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1079       return ExprError();
1080     break;
1081   case Builtin::BI__exception_code:
1082   case Builtin::BI_exception_code:
1083     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1084                                  diag::err_seh___except_block))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__exception_info:
1088   case Builtin::BI_exception_info:
1089     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1090                                  diag::err_seh___except_filter))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__GetExceptionInfo:
1094     if (checkArgCount(*this, TheCall, 1))
1095       return ExprError();
1096 
1097     if (CheckCXXThrowOperand(
1098             TheCall->getLocStart(),
1099             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1100             TheCall))
1101       return ExprError();
1102 
1103     TheCall->setType(Context.VoidPtrTy);
1104     break;
1105   // OpenCL v2.0, s6.13.16 - Pipe functions
1106   case Builtin::BIread_pipe:
1107   case Builtin::BIwrite_pipe:
1108     // Since those two functions are declared with var args, we need a semantic
1109     // check for the argument.
1110     if (SemaBuiltinRWPipe(*this, TheCall))
1111       return ExprError();
1112     TheCall->setType(Context.IntTy);
1113     break;
1114   case Builtin::BIreserve_read_pipe:
1115   case Builtin::BIreserve_write_pipe:
1116   case Builtin::BIwork_group_reserve_read_pipe:
1117   case Builtin::BIwork_group_reserve_write_pipe:
1118     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1119       return ExprError();
1120     break;
1121   case Builtin::BIsub_group_reserve_read_pipe:
1122   case Builtin::BIsub_group_reserve_write_pipe:
1123     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1124         SemaBuiltinReserveRWPipe(*this, TheCall))
1125       return ExprError();
1126     break;
1127   case Builtin::BIcommit_read_pipe:
1128   case Builtin::BIcommit_write_pipe:
1129   case Builtin::BIwork_group_commit_read_pipe:
1130   case Builtin::BIwork_group_commit_write_pipe:
1131     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1132       return ExprError();
1133     break;
1134   case Builtin::BIsub_group_commit_read_pipe:
1135   case Builtin::BIsub_group_commit_write_pipe:
1136     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1137         SemaBuiltinCommitRWPipe(*this, TheCall))
1138       return ExprError();
1139     break;
1140   case Builtin::BIget_pipe_num_packets:
1141   case Builtin::BIget_pipe_max_packets:
1142     if (SemaBuiltinPipePackets(*this, TheCall))
1143       return ExprError();
1144     TheCall->setType(Context.UnsignedIntTy);
1145     break;
1146   case Builtin::BIto_global:
1147   case Builtin::BIto_local:
1148   case Builtin::BIto_private:
1149     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1150       return ExprError();
1151     break;
1152   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1153   case Builtin::BIenqueue_kernel:
1154     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1155       return ExprError();
1156     break;
1157   case Builtin::BIget_kernel_work_group_size:
1158   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1159     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1160       return ExprError();
1161     break;
1162     break;
1163   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1164   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1165     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1166       return ExprError();
1167     break;
1168   case Builtin::BI__builtin_os_log_format:
1169   case Builtin::BI__builtin_os_log_format_buffer_size:
1170     if (SemaBuiltinOSLogFormat(TheCall)) {
1171       return ExprError();
1172     }
1173     break;
1174   }
1175 
1176   // Since the target specific builtins for each arch overlap, only check those
1177   // of the arch we are compiling for.
1178   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1179     switch (Context.getTargetInfo().getTriple().getArch()) {
1180       case llvm::Triple::arm:
1181       case llvm::Triple::armeb:
1182       case llvm::Triple::thumb:
1183       case llvm::Triple::thumbeb:
1184         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1185           return ExprError();
1186         break;
1187       case llvm::Triple::aarch64:
1188       case llvm::Triple::aarch64_be:
1189         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1190           return ExprError();
1191         break;
1192       case llvm::Triple::mips:
1193       case llvm::Triple::mipsel:
1194       case llvm::Triple::mips64:
1195       case llvm::Triple::mips64el:
1196         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1197           return ExprError();
1198         break;
1199       case llvm::Triple::systemz:
1200         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1201           return ExprError();
1202         break;
1203       case llvm::Triple::x86:
1204       case llvm::Triple::x86_64:
1205         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1206           return ExprError();
1207         break;
1208       case llvm::Triple::ppc:
1209       case llvm::Triple::ppc64:
1210       case llvm::Triple::ppc64le:
1211         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1212           return ExprError();
1213         break;
1214       default:
1215         break;
1216     }
1217   }
1218 
1219   return TheCallResult;
1220 }
1221 
1222 // Get the valid immediate range for the specified NEON type code.
1223 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1224   NeonTypeFlags Type(t);
1225   int IsQuad = ForceQuad ? true : Type.isQuad();
1226   switch (Type.getEltType()) {
1227   case NeonTypeFlags::Int8:
1228   case NeonTypeFlags::Poly8:
1229     return shift ? 7 : (8 << IsQuad) - 1;
1230   case NeonTypeFlags::Int16:
1231   case NeonTypeFlags::Poly16:
1232     return shift ? 15 : (4 << IsQuad) - 1;
1233   case NeonTypeFlags::Int32:
1234     return shift ? 31 : (2 << IsQuad) - 1;
1235   case NeonTypeFlags::Int64:
1236   case NeonTypeFlags::Poly64:
1237     return shift ? 63 : (1 << IsQuad) - 1;
1238   case NeonTypeFlags::Poly128:
1239     return shift ? 127 : (1 << IsQuad) - 1;
1240   case NeonTypeFlags::Float16:
1241     assert(!shift && "cannot shift float types!");
1242     return (4 << IsQuad) - 1;
1243   case NeonTypeFlags::Float32:
1244     assert(!shift && "cannot shift float types!");
1245     return (2 << IsQuad) - 1;
1246   case NeonTypeFlags::Float64:
1247     assert(!shift && "cannot shift float types!");
1248     return (1 << IsQuad) - 1;
1249   }
1250   llvm_unreachable("Invalid NeonTypeFlag!");
1251 }
1252 
1253 /// getNeonEltType - Return the QualType corresponding to the elements of
1254 /// the vector type specified by the NeonTypeFlags.  This is used to check
1255 /// the pointer arguments for Neon load/store intrinsics.
1256 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1257                                bool IsPolyUnsigned, bool IsInt64Long) {
1258   switch (Flags.getEltType()) {
1259   case NeonTypeFlags::Int8:
1260     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1261   case NeonTypeFlags::Int16:
1262     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1263   case NeonTypeFlags::Int32:
1264     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1265   case NeonTypeFlags::Int64:
1266     if (IsInt64Long)
1267       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1268     else
1269       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1270                                 : Context.LongLongTy;
1271   case NeonTypeFlags::Poly8:
1272     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1273   case NeonTypeFlags::Poly16:
1274     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1275   case NeonTypeFlags::Poly64:
1276     if (IsInt64Long)
1277       return Context.UnsignedLongTy;
1278     else
1279       return Context.UnsignedLongLongTy;
1280   case NeonTypeFlags::Poly128:
1281     break;
1282   case NeonTypeFlags::Float16:
1283     return Context.HalfTy;
1284   case NeonTypeFlags::Float32:
1285     return Context.FloatTy;
1286   case NeonTypeFlags::Float64:
1287     return Context.DoubleTy;
1288   }
1289   llvm_unreachable("Invalid NeonTypeFlag!");
1290 }
1291 
1292 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1293   llvm::APSInt Result;
1294   uint64_t mask = 0;
1295   unsigned TV = 0;
1296   int PtrArgNum = -1;
1297   bool HasConstPtr = false;
1298   switch (BuiltinID) {
1299 #define GET_NEON_OVERLOAD_CHECK
1300 #include "clang/Basic/arm_neon.inc"
1301 #undef GET_NEON_OVERLOAD_CHECK
1302   }
1303 
1304   // For NEON intrinsics which are overloaded on vector element type, validate
1305   // the immediate which specifies which variant to emit.
1306   unsigned ImmArg = TheCall->getNumArgs()-1;
1307   if (mask) {
1308     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1309       return true;
1310 
1311     TV = Result.getLimitedValue(64);
1312     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1313       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1314         << TheCall->getArg(ImmArg)->getSourceRange();
1315   }
1316 
1317   if (PtrArgNum >= 0) {
1318     // Check that pointer arguments have the specified type.
1319     Expr *Arg = TheCall->getArg(PtrArgNum);
1320     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1321       Arg = ICE->getSubExpr();
1322     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1323     QualType RHSTy = RHS.get()->getType();
1324 
1325     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1326     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1327                           Arch == llvm::Triple::aarch64_be;
1328     bool IsInt64Long =
1329         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1330     QualType EltTy =
1331         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1332     if (HasConstPtr)
1333       EltTy = EltTy.withConst();
1334     QualType LHSTy = Context.getPointerType(EltTy);
1335     AssignConvertType ConvTy;
1336     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1337     if (RHS.isInvalid())
1338       return true;
1339     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1340                                  RHS.get(), AA_Assigning))
1341       return true;
1342   }
1343 
1344   // For NEON intrinsics which take an immediate value as part of the
1345   // instruction, range check them here.
1346   unsigned i = 0, l = 0, u = 0;
1347   switch (BuiltinID) {
1348   default:
1349     return false;
1350 #define GET_NEON_IMMEDIATE_CHECK
1351 #include "clang/Basic/arm_neon.inc"
1352 #undef GET_NEON_IMMEDIATE_CHECK
1353   }
1354 
1355   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1356 }
1357 
1358 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1359                                         unsigned MaxWidth) {
1360   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1361           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1362           BuiltinID == ARM::BI__builtin_arm_strex ||
1363           BuiltinID == ARM::BI__builtin_arm_stlex ||
1364           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1365           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1366           BuiltinID == AArch64::BI__builtin_arm_strex ||
1367           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1368          "unexpected ARM builtin");
1369   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1370                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1372                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1373 
1374   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1375 
1376   // Ensure that we have the proper number of arguments.
1377   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1378     return true;
1379 
1380   // Inspect the pointer argument of the atomic builtin.  This should always be
1381   // a pointer type, whose element is an integral scalar or pointer type.
1382   // Because it is a pointer type, we don't have to worry about any implicit
1383   // casts here.
1384   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1385   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1386   if (PointerArgRes.isInvalid())
1387     return true;
1388   PointerArg = PointerArgRes.get();
1389 
1390   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1391   if (!pointerType) {
1392     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1393       << PointerArg->getType() << PointerArg->getSourceRange();
1394     return true;
1395   }
1396 
1397   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1398   // task is to insert the appropriate casts into the AST. First work out just
1399   // what the appropriate type is.
1400   QualType ValType = pointerType->getPointeeType();
1401   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1402   if (IsLdrex)
1403     AddrType.addConst();
1404 
1405   // Issue a warning if the cast is dodgy.
1406   CastKind CastNeeded = CK_NoOp;
1407   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1408     CastNeeded = CK_BitCast;
1409     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1410       << PointerArg->getType()
1411       << Context.getPointerType(AddrType)
1412       << AA_Passing << PointerArg->getSourceRange();
1413   }
1414 
1415   // Finally, do the cast and replace the argument with the corrected version.
1416   AddrType = Context.getPointerType(AddrType);
1417   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1418   if (PointerArgRes.isInvalid())
1419     return true;
1420   PointerArg = PointerArgRes.get();
1421 
1422   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1423 
1424   // In general, we allow ints, floats and pointers to be loaded and stored.
1425   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1426       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1427     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1428       << PointerArg->getType() << PointerArg->getSourceRange();
1429     return true;
1430   }
1431 
1432   // But ARM doesn't have instructions to deal with 128-bit versions.
1433   if (Context.getTypeSize(ValType) > MaxWidth) {
1434     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1435     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1436       << PointerArg->getType() << PointerArg->getSourceRange();
1437     return true;
1438   }
1439 
1440   switch (ValType.getObjCLifetime()) {
1441   case Qualifiers::OCL_None:
1442   case Qualifiers::OCL_ExplicitNone:
1443     // okay
1444     break;
1445 
1446   case Qualifiers::OCL_Weak:
1447   case Qualifiers::OCL_Strong:
1448   case Qualifiers::OCL_Autoreleasing:
1449     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1450       << ValType << PointerArg->getSourceRange();
1451     return true;
1452   }
1453 
1454   if (IsLdrex) {
1455     TheCall->setType(ValType);
1456     return false;
1457   }
1458 
1459   // Initialize the argument to be stored.
1460   ExprResult ValArg = TheCall->getArg(0);
1461   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1462       Context, ValType, /*consume*/ false);
1463   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1464   if (ValArg.isInvalid())
1465     return true;
1466   TheCall->setArg(0, ValArg.get());
1467 
1468   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1469   // but the custom checker bypasses all default analysis.
1470   TheCall->setType(Context.IntTy);
1471   return false;
1472 }
1473 
1474 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1476       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1477       BuiltinID == ARM::BI__builtin_arm_strex ||
1478       BuiltinID == ARM::BI__builtin_arm_stlex) {
1479     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1480   }
1481 
1482   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1483     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1484       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1485   }
1486 
1487   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1488       BuiltinID == ARM::BI__builtin_arm_wsr64)
1489     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1490 
1491   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1492       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1493       BuiltinID == ARM::BI__builtin_arm_wsr ||
1494       BuiltinID == ARM::BI__builtin_arm_wsrp)
1495     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1496 
1497   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1498     return true;
1499 
1500   // For intrinsics which take an immediate value as part of the instruction,
1501   // range check them here.
1502   unsigned i = 0, l = 0, u = 0;
1503   switch (BuiltinID) {
1504   default: return false;
1505   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1506   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1507   case ARM::BI__builtin_arm_vcvtr_f:
1508   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1509   case ARM::BI__builtin_arm_dmb:
1510   case ARM::BI__builtin_arm_dsb:
1511   case ARM::BI__builtin_arm_isb:
1512   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1513   }
1514 
1515   // FIXME: VFP Intrinsics should error if VFP not present.
1516   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1517 }
1518 
1519 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1520                                          CallExpr *TheCall) {
1521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1523       BuiltinID == AArch64::BI__builtin_arm_strex ||
1524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1526   }
1527 
1528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1533   }
1534 
1535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1538 
1539   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1540       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1541       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1542       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1543     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1544 
1545   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1546     return true;
1547 
1548   // For intrinsics which take an immediate value as part of the instruction,
1549   // range check them here.
1550   unsigned i = 0, l = 0, u = 0;
1551   switch (BuiltinID) {
1552   default: return false;
1553   case AArch64::BI__builtin_arm_dmb:
1554   case AArch64::BI__builtin_arm_dsb:
1555   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1556   }
1557 
1558   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1559 }
1560 
1561 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1562 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1563 // ordering for DSP is unspecified. MSA is ordered by the data format used
1564 // by the underlying instruction i.e., df/m, df/n and then by size.
1565 //
1566 // FIXME: The size tests here should instead be tablegen'd along with the
1567 //        definitions from include/clang/Basic/BuiltinsMips.def.
1568 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1569 //        be too.
1570 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1571   unsigned i = 0, l = 0, u = 0, m = 0;
1572   switch (BuiltinID) {
1573   default: return false;
1574   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1575   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1576   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1577   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1578   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1579   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1580   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1581   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1582   // df/m field.
1583   // These intrinsics take an unsigned 3 bit immediate.
1584   case Mips::BI__builtin_msa_bclri_b:
1585   case Mips::BI__builtin_msa_bnegi_b:
1586   case Mips::BI__builtin_msa_bseti_b:
1587   case Mips::BI__builtin_msa_sat_s_b:
1588   case Mips::BI__builtin_msa_sat_u_b:
1589   case Mips::BI__builtin_msa_slli_b:
1590   case Mips::BI__builtin_msa_srai_b:
1591   case Mips::BI__builtin_msa_srari_b:
1592   case Mips::BI__builtin_msa_srli_b:
1593   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1594   case Mips::BI__builtin_msa_binsli_b:
1595   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1596   // These intrinsics take an unsigned 4 bit immediate.
1597   case Mips::BI__builtin_msa_bclri_h:
1598   case Mips::BI__builtin_msa_bnegi_h:
1599   case Mips::BI__builtin_msa_bseti_h:
1600   case Mips::BI__builtin_msa_sat_s_h:
1601   case Mips::BI__builtin_msa_sat_u_h:
1602   case Mips::BI__builtin_msa_slli_h:
1603   case Mips::BI__builtin_msa_srai_h:
1604   case Mips::BI__builtin_msa_srari_h:
1605   case Mips::BI__builtin_msa_srli_h:
1606   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1607   case Mips::BI__builtin_msa_binsli_h:
1608   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1609   // These intrinsics take an unsigned 5 bit immedate.
1610   // The first block of intrinsics actually have an unsigned 5 bit field,
1611   // not a df/n field.
1612   case Mips::BI__builtin_msa_clei_u_b:
1613   case Mips::BI__builtin_msa_clei_u_h:
1614   case Mips::BI__builtin_msa_clei_u_w:
1615   case Mips::BI__builtin_msa_clei_u_d:
1616   case Mips::BI__builtin_msa_clti_u_b:
1617   case Mips::BI__builtin_msa_clti_u_h:
1618   case Mips::BI__builtin_msa_clti_u_w:
1619   case Mips::BI__builtin_msa_clti_u_d:
1620   case Mips::BI__builtin_msa_maxi_u_b:
1621   case Mips::BI__builtin_msa_maxi_u_h:
1622   case Mips::BI__builtin_msa_maxi_u_w:
1623   case Mips::BI__builtin_msa_maxi_u_d:
1624   case Mips::BI__builtin_msa_mini_u_b:
1625   case Mips::BI__builtin_msa_mini_u_h:
1626   case Mips::BI__builtin_msa_mini_u_w:
1627   case Mips::BI__builtin_msa_mini_u_d:
1628   case Mips::BI__builtin_msa_addvi_b:
1629   case Mips::BI__builtin_msa_addvi_h:
1630   case Mips::BI__builtin_msa_addvi_w:
1631   case Mips::BI__builtin_msa_addvi_d:
1632   case Mips::BI__builtin_msa_bclri_w:
1633   case Mips::BI__builtin_msa_bnegi_w:
1634   case Mips::BI__builtin_msa_bseti_w:
1635   case Mips::BI__builtin_msa_sat_s_w:
1636   case Mips::BI__builtin_msa_sat_u_w:
1637   case Mips::BI__builtin_msa_slli_w:
1638   case Mips::BI__builtin_msa_srai_w:
1639   case Mips::BI__builtin_msa_srari_w:
1640   case Mips::BI__builtin_msa_srli_w:
1641   case Mips::BI__builtin_msa_srlri_w:
1642   case Mips::BI__builtin_msa_subvi_b:
1643   case Mips::BI__builtin_msa_subvi_h:
1644   case Mips::BI__builtin_msa_subvi_w:
1645   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1646   case Mips::BI__builtin_msa_binsli_w:
1647   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1648   // These intrinsics take an unsigned 6 bit immediate.
1649   case Mips::BI__builtin_msa_bclri_d:
1650   case Mips::BI__builtin_msa_bnegi_d:
1651   case Mips::BI__builtin_msa_bseti_d:
1652   case Mips::BI__builtin_msa_sat_s_d:
1653   case Mips::BI__builtin_msa_sat_u_d:
1654   case Mips::BI__builtin_msa_slli_d:
1655   case Mips::BI__builtin_msa_srai_d:
1656   case Mips::BI__builtin_msa_srari_d:
1657   case Mips::BI__builtin_msa_srli_d:
1658   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1659   case Mips::BI__builtin_msa_binsli_d:
1660   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1661   // These intrinsics take a signed 5 bit immediate.
1662   case Mips::BI__builtin_msa_ceqi_b:
1663   case Mips::BI__builtin_msa_ceqi_h:
1664   case Mips::BI__builtin_msa_ceqi_w:
1665   case Mips::BI__builtin_msa_ceqi_d:
1666   case Mips::BI__builtin_msa_clti_s_b:
1667   case Mips::BI__builtin_msa_clti_s_h:
1668   case Mips::BI__builtin_msa_clti_s_w:
1669   case Mips::BI__builtin_msa_clti_s_d:
1670   case Mips::BI__builtin_msa_clei_s_b:
1671   case Mips::BI__builtin_msa_clei_s_h:
1672   case Mips::BI__builtin_msa_clei_s_w:
1673   case Mips::BI__builtin_msa_clei_s_d:
1674   case Mips::BI__builtin_msa_maxi_s_b:
1675   case Mips::BI__builtin_msa_maxi_s_h:
1676   case Mips::BI__builtin_msa_maxi_s_w:
1677   case Mips::BI__builtin_msa_maxi_s_d:
1678   case Mips::BI__builtin_msa_mini_s_b:
1679   case Mips::BI__builtin_msa_mini_s_h:
1680   case Mips::BI__builtin_msa_mini_s_w:
1681   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1682   // These intrinsics take an unsigned 8 bit immediate.
1683   case Mips::BI__builtin_msa_andi_b:
1684   case Mips::BI__builtin_msa_nori_b:
1685   case Mips::BI__builtin_msa_ori_b:
1686   case Mips::BI__builtin_msa_shf_b:
1687   case Mips::BI__builtin_msa_shf_h:
1688   case Mips::BI__builtin_msa_shf_w:
1689   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1690   case Mips::BI__builtin_msa_bseli_b:
1691   case Mips::BI__builtin_msa_bmnzi_b:
1692   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1693   // df/n format
1694   // These intrinsics take an unsigned 4 bit immediate.
1695   case Mips::BI__builtin_msa_copy_s_b:
1696   case Mips::BI__builtin_msa_copy_u_b:
1697   case Mips::BI__builtin_msa_insve_b:
1698   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1699   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1700   // These intrinsics take an unsigned 3 bit immediate.
1701   case Mips::BI__builtin_msa_copy_s_h:
1702   case Mips::BI__builtin_msa_copy_u_h:
1703   case Mips::BI__builtin_msa_insve_h:
1704   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1705   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1706   // These intrinsics take an unsigned 2 bit immediate.
1707   case Mips::BI__builtin_msa_copy_s_w:
1708   case Mips::BI__builtin_msa_copy_u_w:
1709   case Mips::BI__builtin_msa_insve_w:
1710   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1711   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1712   // These intrinsics take an unsigned 1 bit immediate.
1713   case Mips::BI__builtin_msa_copy_s_d:
1714   case Mips::BI__builtin_msa_copy_u_d:
1715   case Mips::BI__builtin_msa_insve_d:
1716   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1717   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1718   // Memory offsets and immediate loads.
1719   // These intrinsics take a signed 10 bit immediate.
1720   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1721   case Mips::BI__builtin_msa_ldi_h:
1722   case Mips::BI__builtin_msa_ldi_w:
1723   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1724   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1725   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1726   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1727   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1728   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1729   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1730   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1731   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1732   }
1733 
1734   if (!m)
1735     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1736 
1737   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1738          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1739 }
1740 
1741 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1742   unsigned i = 0, l = 0, u = 0;
1743   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1744                       BuiltinID == PPC::BI__builtin_divdeu ||
1745                       BuiltinID == PPC::BI__builtin_bpermd;
1746   bool IsTarget64Bit = Context.getTargetInfo()
1747                               .getTypeWidth(Context
1748                                             .getTargetInfo()
1749                                             .getIntPtrType()) == 64;
1750   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1751                        BuiltinID == PPC::BI__builtin_divweu ||
1752                        BuiltinID == PPC::BI__builtin_divde ||
1753                        BuiltinID == PPC::BI__builtin_divdeu;
1754 
1755   if (Is64BitBltin && !IsTarget64Bit)
1756       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1757              << TheCall->getSourceRange();
1758 
1759   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1760       (BuiltinID == PPC::BI__builtin_bpermd &&
1761        !Context.getTargetInfo().hasFeature("bpermd")))
1762     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1763            << TheCall->getSourceRange();
1764 
1765   switch (BuiltinID) {
1766   default: return false;
1767   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1768   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1769     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1770            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1771   case PPC::BI__builtin_tbegin:
1772   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1773   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1774   case PPC::BI__builtin_tabortwc:
1775   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1776   case PPC::BI__builtin_tabortwci:
1777   case PPC::BI__builtin_tabortdci:
1778     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1779            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1780   case PPC::BI__builtin_vsx_xxpermdi:
1781   case PPC::BI__builtin_vsx_xxsldwi:
1782     return SemaBuiltinVSX(TheCall);
1783   }
1784   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1785 }
1786 
1787 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1788                                            CallExpr *TheCall) {
1789   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1790     Expr *Arg = TheCall->getArg(0);
1791     llvm::APSInt AbortCode(32);
1792     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1793         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1794       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1795              << Arg->getSourceRange();
1796   }
1797 
1798   // For intrinsics which take an immediate value as part of the instruction,
1799   // range check them here.
1800   unsigned i = 0, l = 0, u = 0;
1801   switch (BuiltinID) {
1802   default: return false;
1803   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1804   case SystemZ::BI__builtin_s390_verimb:
1805   case SystemZ::BI__builtin_s390_verimh:
1806   case SystemZ::BI__builtin_s390_verimf:
1807   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1808   case SystemZ::BI__builtin_s390_vfaeb:
1809   case SystemZ::BI__builtin_s390_vfaeh:
1810   case SystemZ::BI__builtin_s390_vfaef:
1811   case SystemZ::BI__builtin_s390_vfaebs:
1812   case SystemZ::BI__builtin_s390_vfaehs:
1813   case SystemZ::BI__builtin_s390_vfaefs:
1814   case SystemZ::BI__builtin_s390_vfaezb:
1815   case SystemZ::BI__builtin_s390_vfaezh:
1816   case SystemZ::BI__builtin_s390_vfaezf:
1817   case SystemZ::BI__builtin_s390_vfaezbs:
1818   case SystemZ::BI__builtin_s390_vfaezhs:
1819   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1820   case SystemZ::BI__builtin_s390_vfisb:
1821   case SystemZ::BI__builtin_s390_vfidb:
1822     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1823            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1824   case SystemZ::BI__builtin_s390_vftcisb:
1825   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1826   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1827   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1828   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1829   case SystemZ::BI__builtin_s390_vstrcb:
1830   case SystemZ::BI__builtin_s390_vstrch:
1831   case SystemZ::BI__builtin_s390_vstrcf:
1832   case SystemZ::BI__builtin_s390_vstrczb:
1833   case SystemZ::BI__builtin_s390_vstrczh:
1834   case SystemZ::BI__builtin_s390_vstrczf:
1835   case SystemZ::BI__builtin_s390_vstrcbs:
1836   case SystemZ::BI__builtin_s390_vstrchs:
1837   case SystemZ::BI__builtin_s390_vstrcfs:
1838   case SystemZ::BI__builtin_s390_vstrczbs:
1839   case SystemZ::BI__builtin_s390_vstrczhs:
1840   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1841   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1842   case SystemZ::BI__builtin_s390_vfminsb:
1843   case SystemZ::BI__builtin_s390_vfmaxsb:
1844   case SystemZ::BI__builtin_s390_vfmindb:
1845   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1846   }
1847   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1848 }
1849 
1850 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1851 /// This checks that the target supports __builtin_cpu_supports and
1852 /// that the string argument is constant and valid.
1853 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1854   Expr *Arg = TheCall->getArg(0);
1855 
1856   // Check if the argument is a string literal.
1857   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1858     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1859            << Arg->getSourceRange();
1860 
1861   // Check the contents of the string.
1862   StringRef Feature =
1863       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1864   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1865     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1866            << Arg->getSourceRange();
1867   return false;
1868 }
1869 
1870 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1871 /// This checks that the target supports __builtin_cpu_is and
1872 /// that the string argument is constant and valid.
1873 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1874   Expr *Arg = TheCall->getArg(0);
1875 
1876   // Check if the argument is a string literal.
1877   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1878     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1879            << Arg->getSourceRange();
1880 
1881   // Check the contents of the string.
1882   StringRef Feature =
1883       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1884   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1885     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1886            << Arg->getSourceRange();
1887   return false;
1888 }
1889 
1890 // Check if the rounding mode is legal.
1891 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1892   // Indicates if this instruction has rounding control or just SAE.
1893   bool HasRC = false;
1894 
1895   unsigned ArgNum = 0;
1896   switch (BuiltinID) {
1897   default:
1898     return false;
1899   case X86::BI__builtin_ia32_vcvttsd2si32:
1900   case X86::BI__builtin_ia32_vcvttsd2si64:
1901   case X86::BI__builtin_ia32_vcvttsd2usi32:
1902   case X86::BI__builtin_ia32_vcvttsd2usi64:
1903   case X86::BI__builtin_ia32_vcvttss2si32:
1904   case X86::BI__builtin_ia32_vcvttss2si64:
1905   case X86::BI__builtin_ia32_vcvttss2usi32:
1906   case X86::BI__builtin_ia32_vcvttss2usi64:
1907     ArgNum = 1;
1908     break;
1909   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1910   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1911   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1912   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1913   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1914   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1915   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1916   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1917   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1918   case X86::BI__builtin_ia32_exp2pd_mask:
1919   case X86::BI__builtin_ia32_exp2ps_mask:
1920   case X86::BI__builtin_ia32_getexppd512_mask:
1921   case X86::BI__builtin_ia32_getexpps512_mask:
1922   case X86::BI__builtin_ia32_rcp28pd_mask:
1923   case X86::BI__builtin_ia32_rcp28ps_mask:
1924   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1925   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1926   case X86::BI__builtin_ia32_vcomisd:
1927   case X86::BI__builtin_ia32_vcomiss:
1928   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1929     ArgNum = 3;
1930     break;
1931   case X86::BI__builtin_ia32_cmppd512_mask:
1932   case X86::BI__builtin_ia32_cmpps512_mask:
1933   case X86::BI__builtin_ia32_cmpsd_mask:
1934   case X86::BI__builtin_ia32_cmpss_mask:
1935   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1936   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1937   case X86::BI__builtin_ia32_getexpss128_round_mask:
1938   case X86::BI__builtin_ia32_maxpd512_mask:
1939   case X86::BI__builtin_ia32_maxps512_mask:
1940   case X86::BI__builtin_ia32_maxsd_round_mask:
1941   case X86::BI__builtin_ia32_maxss_round_mask:
1942   case X86::BI__builtin_ia32_minpd512_mask:
1943   case X86::BI__builtin_ia32_minps512_mask:
1944   case X86::BI__builtin_ia32_minsd_round_mask:
1945   case X86::BI__builtin_ia32_minss_round_mask:
1946   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1947   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1948   case X86::BI__builtin_ia32_reducepd512_mask:
1949   case X86::BI__builtin_ia32_reduceps512_mask:
1950   case X86::BI__builtin_ia32_rndscalepd_mask:
1951   case X86::BI__builtin_ia32_rndscaleps_mask:
1952   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1953   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1954     ArgNum = 4;
1955     break;
1956   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1957   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1958   case X86::BI__builtin_ia32_fixupimmps512_mask:
1959   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1960   case X86::BI__builtin_ia32_fixupimmsd_mask:
1961   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1962   case X86::BI__builtin_ia32_fixupimmss_mask:
1963   case X86::BI__builtin_ia32_fixupimmss_maskz:
1964   case X86::BI__builtin_ia32_rangepd512_mask:
1965   case X86::BI__builtin_ia32_rangeps512_mask:
1966   case X86::BI__builtin_ia32_rangesd128_round_mask:
1967   case X86::BI__builtin_ia32_rangess128_round_mask:
1968   case X86::BI__builtin_ia32_reducesd_mask:
1969   case X86::BI__builtin_ia32_reducess_mask:
1970   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1971   case X86::BI__builtin_ia32_rndscaless_round_mask:
1972     ArgNum = 5;
1973     break;
1974   case X86::BI__builtin_ia32_vcvtsd2si64:
1975   case X86::BI__builtin_ia32_vcvtsd2si32:
1976   case X86::BI__builtin_ia32_vcvtsd2usi32:
1977   case X86::BI__builtin_ia32_vcvtsd2usi64:
1978   case X86::BI__builtin_ia32_vcvtss2si32:
1979   case X86::BI__builtin_ia32_vcvtss2si64:
1980   case X86::BI__builtin_ia32_vcvtss2usi32:
1981   case X86::BI__builtin_ia32_vcvtss2usi64:
1982     ArgNum = 1;
1983     HasRC = true;
1984     break;
1985   case X86::BI__builtin_ia32_cvtsi2sd64:
1986   case X86::BI__builtin_ia32_cvtsi2ss32:
1987   case X86::BI__builtin_ia32_cvtsi2ss64:
1988   case X86::BI__builtin_ia32_cvtusi2sd64:
1989   case X86::BI__builtin_ia32_cvtusi2ss32:
1990   case X86::BI__builtin_ia32_cvtusi2ss64:
1991     ArgNum = 2;
1992     HasRC = true;
1993     break;
1994   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1995   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1996   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1997   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1998   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1999   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2000   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2001   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2002   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2003   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2004   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2005   case X86::BI__builtin_ia32_sqrtpd512_mask:
2006   case X86::BI__builtin_ia32_sqrtps512_mask:
2007     ArgNum = 3;
2008     HasRC = true;
2009     break;
2010   case X86::BI__builtin_ia32_addpd512_mask:
2011   case X86::BI__builtin_ia32_addps512_mask:
2012   case X86::BI__builtin_ia32_divpd512_mask:
2013   case X86::BI__builtin_ia32_divps512_mask:
2014   case X86::BI__builtin_ia32_mulpd512_mask:
2015   case X86::BI__builtin_ia32_mulps512_mask:
2016   case X86::BI__builtin_ia32_subpd512_mask:
2017   case X86::BI__builtin_ia32_subps512_mask:
2018   case X86::BI__builtin_ia32_addss_round_mask:
2019   case X86::BI__builtin_ia32_addsd_round_mask:
2020   case X86::BI__builtin_ia32_divss_round_mask:
2021   case X86::BI__builtin_ia32_divsd_round_mask:
2022   case X86::BI__builtin_ia32_mulss_round_mask:
2023   case X86::BI__builtin_ia32_mulsd_round_mask:
2024   case X86::BI__builtin_ia32_subss_round_mask:
2025   case X86::BI__builtin_ia32_subsd_round_mask:
2026   case X86::BI__builtin_ia32_scalefpd512_mask:
2027   case X86::BI__builtin_ia32_scalefps512_mask:
2028   case X86::BI__builtin_ia32_scalefsd_round_mask:
2029   case X86::BI__builtin_ia32_scalefss_round_mask:
2030   case X86::BI__builtin_ia32_getmantpd512_mask:
2031   case X86::BI__builtin_ia32_getmantps512_mask:
2032   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2033   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2034   case X86::BI__builtin_ia32_sqrtss_round_mask:
2035   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2036   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2037   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2038   case X86::BI__builtin_ia32_vfmaddps512_mask:
2039   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2040   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2041   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2042   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2043   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2044   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2045   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2046   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2047   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2048   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2049   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2050   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2051   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2052   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2053   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2054   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2055   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2056   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2057   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2058   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2059   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2060   case X86::BI__builtin_ia32_vfmaddss3_mask:
2061   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2062   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2063     ArgNum = 4;
2064     HasRC = true;
2065     break;
2066   case X86::BI__builtin_ia32_getmantsd_round_mask:
2067   case X86::BI__builtin_ia32_getmantss_round_mask:
2068     ArgNum = 5;
2069     HasRC = true;
2070     break;
2071   }
2072 
2073   llvm::APSInt Result;
2074 
2075   // We can't check the value of a dependent argument.
2076   Expr *Arg = TheCall->getArg(ArgNum);
2077   if (Arg->isTypeDependent() || Arg->isValueDependent())
2078     return false;
2079 
2080   // Check constant-ness first.
2081   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2082     return true;
2083 
2084   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2085   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2086   // combined with ROUND_NO_EXC.
2087   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2088       Result == 8/*ROUND_NO_EXC*/ ||
2089       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2090     return false;
2091 
2092   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2093     << Arg->getSourceRange();
2094 }
2095 
2096 // Check if the gather/scatter scale is legal.
2097 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2098                                              CallExpr *TheCall) {
2099   unsigned ArgNum = 0;
2100   switch (BuiltinID) {
2101   default:
2102     return false;
2103   case X86::BI__builtin_ia32_gatherpfdpd:
2104   case X86::BI__builtin_ia32_gatherpfdps:
2105   case X86::BI__builtin_ia32_gatherpfqpd:
2106   case X86::BI__builtin_ia32_gatherpfqps:
2107   case X86::BI__builtin_ia32_scatterpfdpd:
2108   case X86::BI__builtin_ia32_scatterpfdps:
2109   case X86::BI__builtin_ia32_scatterpfqpd:
2110   case X86::BI__builtin_ia32_scatterpfqps:
2111     ArgNum = 3;
2112     break;
2113   case X86::BI__builtin_ia32_gatherd_pd:
2114   case X86::BI__builtin_ia32_gatherd_pd256:
2115   case X86::BI__builtin_ia32_gatherq_pd:
2116   case X86::BI__builtin_ia32_gatherq_pd256:
2117   case X86::BI__builtin_ia32_gatherd_ps:
2118   case X86::BI__builtin_ia32_gatherd_ps256:
2119   case X86::BI__builtin_ia32_gatherq_ps:
2120   case X86::BI__builtin_ia32_gatherq_ps256:
2121   case X86::BI__builtin_ia32_gatherd_q:
2122   case X86::BI__builtin_ia32_gatherd_q256:
2123   case X86::BI__builtin_ia32_gatherq_q:
2124   case X86::BI__builtin_ia32_gatherq_q256:
2125   case X86::BI__builtin_ia32_gatherd_d:
2126   case X86::BI__builtin_ia32_gatherd_d256:
2127   case X86::BI__builtin_ia32_gatherq_d:
2128   case X86::BI__builtin_ia32_gatherq_d256:
2129   case X86::BI__builtin_ia32_gather3div2df:
2130   case X86::BI__builtin_ia32_gather3div2di:
2131   case X86::BI__builtin_ia32_gather3div4df:
2132   case X86::BI__builtin_ia32_gather3div4di:
2133   case X86::BI__builtin_ia32_gather3div4sf:
2134   case X86::BI__builtin_ia32_gather3div4si:
2135   case X86::BI__builtin_ia32_gather3div8sf:
2136   case X86::BI__builtin_ia32_gather3div8si:
2137   case X86::BI__builtin_ia32_gather3siv2df:
2138   case X86::BI__builtin_ia32_gather3siv2di:
2139   case X86::BI__builtin_ia32_gather3siv4df:
2140   case X86::BI__builtin_ia32_gather3siv4di:
2141   case X86::BI__builtin_ia32_gather3siv4sf:
2142   case X86::BI__builtin_ia32_gather3siv4si:
2143   case X86::BI__builtin_ia32_gather3siv8sf:
2144   case X86::BI__builtin_ia32_gather3siv8si:
2145   case X86::BI__builtin_ia32_gathersiv8df:
2146   case X86::BI__builtin_ia32_gathersiv16sf:
2147   case X86::BI__builtin_ia32_gatherdiv8df:
2148   case X86::BI__builtin_ia32_gatherdiv16sf:
2149   case X86::BI__builtin_ia32_gathersiv8di:
2150   case X86::BI__builtin_ia32_gathersiv16si:
2151   case X86::BI__builtin_ia32_gatherdiv8di:
2152   case X86::BI__builtin_ia32_gatherdiv16si:
2153   case X86::BI__builtin_ia32_scatterdiv2df:
2154   case X86::BI__builtin_ia32_scatterdiv2di:
2155   case X86::BI__builtin_ia32_scatterdiv4df:
2156   case X86::BI__builtin_ia32_scatterdiv4di:
2157   case X86::BI__builtin_ia32_scatterdiv4sf:
2158   case X86::BI__builtin_ia32_scatterdiv4si:
2159   case X86::BI__builtin_ia32_scatterdiv8sf:
2160   case X86::BI__builtin_ia32_scatterdiv8si:
2161   case X86::BI__builtin_ia32_scattersiv2df:
2162   case X86::BI__builtin_ia32_scattersiv2di:
2163   case X86::BI__builtin_ia32_scattersiv4df:
2164   case X86::BI__builtin_ia32_scattersiv4di:
2165   case X86::BI__builtin_ia32_scattersiv4sf:
2166   case X86::BI__builtin_ia32_scattersiv4si:
2167   case X86::BI__builtin_ia32_scattersiv8sf:
2168   case X86::BI__builtin_ia32_scattersiv8si:
2169   case X86::BI__builtin_ia32_scattersiv8df:
2170   case X86::BI__builtin_ia32_scattersiv16sf:
2171   case X86::BI__builtin_ia32_scatterdiv8df:
2172   case X86::BI__builtin_ia32_scatterdiv16sf:
2173   case X86::BI__builtin_ia32_scattersiv8di:
2174   case X86::BI__builtin_ia32_scattersiv16si:
2175   case X86::BI__builtin_ia32_scatterdiv8di:
2176   case X86::BI__builtin_ia32_scatterdiv16si:
2177     ArgNum = 4;
2178     break;
2179   }
2180 
2181   llvm::APSInt Result;
2182 
2183   // We can't check the value of a dependent argument.
2184   Expr *Arg = TheCall->getArg(ArgNum);
2185   if (Arg->isTypeDependent() || Arg->isValueDependent())
2186     return false;
2187 
2188   // Check constant-ness first.
2189   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2190     return true;
2191 
2192   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2193     return false;
2194 
2195   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2196     << Arg->getSourceRange();
2197 }
2198 
2199 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2200   if (BuiltinID == X86::BI__builtin_cpu_supports)
2201     return SemaBuiltinCpuSupports(*this, TheCall);
2202 
2203   if (BuiltinID == X86::BI__builtin_cpu_is)
2204     return SemaBuiltinCpuIs(*this, TheCall);
2205 
2206   // If the intrinsic has rounding or SAE make sure its valid.
2207   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2208     return true;
2209 
2210   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2211   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2212     return true;
2213 
2214   // For intrinsics which take an immediate value as part of the instruction,
2215   // range check them here.
2216   int i = 0, l = 0, u = 0;
2217   switch (BuiltinID) {
2218   default:
2219     return false;
2220   case X86::BI_mm_prefetch:
2221     i = 1; l = 0; u = 3;
2222     break;
2223   case X86::BI__builtin_ia32_sha1rnds4:
2224   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2225   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2226   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2227   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2228     i = 2; l = 0; u = 3;
2229     break;
2230   case X86::BI__builtin_ia32_vpermil2pd:
2231   case X86::BI__builtin_ia32_vpermil2pd256:
2232   case X86::BI__builtin_ia32_vpermil2ps:
2233   case X86::BI__builtin_ia32_vpermil2ps256:
2234     i = 3; l = 0; u = 3;
2235     break;
2236   case X86::BI__builtin_ia32_cmpb128_mask:
2237   case X86::BI__builtin_ia32_cmpw128_mask:
2238   case X86::BI__builtin_ia32_cmpd128_mask:
2239   case X86::BI__builtin_ia32_cmpq128_mask:
2240   case X86::BI__builtin_ia32_cmpb256_mask:
2241   case X86::BI__builtin_ia32_cmpw256_mask:
2242   case X86::BI__builtin_ia32_cmpd256_mask:
2243   case X86::BI__builtin_ia32_cmpq256_mask:
2244   case X86::BI__builtin_ia32_cmpb512_mask:
2245   case X86::BI__builtin_ia32_cmpw512_mask:
2246   case X86::BI__builtin_ia32_cmpd512_mask:
2247   case X86::BI__builtin_ia32_cmpq512_mask:
2248   case X86::BI__builtin_ia32_ucmpb128_mask:
2249   case X86::BI__builtin_ia32_ucmpw128_mask:
2250   case X86::BI__builtin_ia32_ucmpd128_mask:
2251   case X86::BI__builtin_ia32_ucmpq128_mask:
2252   case X86::BI__builtin_ia32_ucmpb256_mask:
2253   case X86::BI__builtin_ia32_ucmpw256_mask:
2254   case X86::BI__builtin_ia32_ucmpd256_mask:
2255   case X86::BI__builtin_ia32_ucmpq256_mask:
2256   case X86::BI__builtin_ia32_ucmpb512_mask:
2257   case X86::BI__builtin_ia32_ucmpw512_mask:
2258   case X86::BI__builtin_ia32_ucmpd512_mask:
2259   case X86::BI__builtin_ia32_ucmpq512_mask:
2260   case X86::BI__builtin_ia32_vpcomub:
2261   case X86::BI__builtin_ia32_vpcomuw:
2262   case X86::BI__builtin_ia32_vpcomud:
2263   case X86::BI__builtin_ia32_vpcomuq:
2264   case X86::BI__builtin_ia32_vpcomb:
2265   case X86::BI__builtin_ia32_vpcomw:
2266   case X86::BI__builtin_ia32_vpcomd:
2267   case X86::BI__builtin_ia32_vpcomq:
2268     i = 2; l = 0; u = 7;
2269     break;
2270   case X86::BI__builtin_ia32_roundps:
2271   case X86::BI__builtin_ia32_roundpd:
2272   case X86::BI__builtin_ia32_roundps256:
2273   case X86::BI__builtin_ia32_roundpd256:
2274     i = 1; l = 0; u = 15;
2275     break;
2276   case X86::BI__builtin_ia32_roundss:
2277   case X86::BI__builtin_ia32_roundsd:
2278   case X86::BI__builtin_ia32_rangepd128_mask:
2279   case X86::BI__builtin_ia32_rangepd256_mask:
2280   case X86::BI__builtin_ia32_rangepd512_mask:
2281   case X86::BI__builtin_ia32_rangeps128_mask:
2282   case X86::BI__builtin_ia32_rangeps256_mask:
2283   case X86::BI__builtin_ia32_rangeps512_mask:
2284   case X86::BI__builtin_ia32_getmantsd_round_mask:
2285   case X86::BI__builtin_ia32_getmantss_round_mask:
2286     i = 2; l = 0; u = 15;
2287     break;
2288   case X86::BI__builtin_ia32_cmpps:
2289   case X86::BI__builtin_ia32_cmpss:
2290   case X86::BI__builtin_ia32_cmppd:
2291   case X86::BI__builtin_ia32_cmpsd:
2292   case X86::BI__builtin_ia32_cmpps256:
2293   case X86::BI__builtin_ia32_cmppd256:
2294   case X86::BI__builtin_ia32_cmpps128_mask:
2295   case X86::BI__builtin_ia32_cmppd128_mask:
2296   case X86::BI__builtin_ia32_cmpps256_mask:
2297   case X86::BI__builtin_ia32_cmppd256_mask:
2298   case X86::BI__builtin_ia32_cmpps512_mask:
2299   case X86::BI__builtin_ia32_cmppd512_mask:
2300   case X86::BI__builtin_ia32_cmpsd_mask:
2301   case X86::BI__builtin_ia32_cmpss_mask:
2302     i = 2; l = 0; u = 31;
2303     break;
2304   case X86::BI__builtin_ia32_xabort:
2305     i = 0; l = -128; u = 255;
2306     break;
2307   case X86::BI__builtin_ia32_pshufw:
2308   case X86::BI__builtin_ia32_aeskeygenassist128:
2309     i = 1; l = -128; u = 255;
2310     break;
2311   case X86::BI__builtin_ia32_vcvtps2ph:
2312   case X86::BI__builtin_ia32_vcvtps2ph256:
2313   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2314   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2315   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2316   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2317   case X86::BI__builtin_ia32_rndscaleps_mask:
2318   case X86::BI__builtin_ia32_rndscalepd_mask:
2319   case X86::BI__builtin_ia32_reducepd128_mask:
2320   case X86::BI__builtin_ia32_reducepd256_mask:
2321   case X86::BI__builtin_ia32_reducepd512_mask:
2322   case X86::BI__builtin_ia32_reduceps128_mask:
2323   case X86::BI__builtin_ia32_reduceps256_mask:
2324   case X86::BI__builtin_ia32_reduceps512_mask:
2325   case X86::BI__builtin_ia32_prold512_mask:
2326   case X86::BI__builtin_ia32_prolq512_mask:
2327   case X86::BI__builtin_ia32_prold128_mask:
2328   case X86::BI__builtin_ia32_prold256_mask:
2329   case X86::BI__builtin_ia32_prolq128_mask:
2330   case X86::BI__builtin_ia32_prolq256_mask:
2331   case X86::BI__builtin_ia32_prord128_mask:
2332   case X86::BI__builtin_ia32_prord256_mask:
2333   case X86::BI__builtin_ia32_prorq128_mask:
2334   case X86::BI__builtin_ia32_prorq256_mask:
2335   case X86::BI__builtin_ia32_fpclasspd128_mask:
2336   case X86::BI__builtin_ia32_fpclasspd256_mask:
2337   case X86::BI__builtin_ia32_fpclassps128_mask:
2338   case X86::BI__builtin_ia32_fpclassps256_mask:
2339   case X86::BI__builtin_ia32_fpclassps512_mask:
2340   case X86::BI__builtin_ia32_fpclasspd512_mask:
2341   case X86::BI__builtin_ia32_fpclasssd_mask:
2342   case X86::BI__builtin_ia32_fpclassss_mask:
2343     i = 1; l = 0; u = 255;
2344     break;
2345   case X86::BI__builtin_ia32_palignr:
2346   case X86::BI__builtin_ia32_insertps128:
2347   case X86::BI__builtin_ia32_dpps:
2348   case X86::BI__builtin_ia32_dppd:
2349   case X86::BI__builtin_ia32_dpps256:
2350   case X86::BI__builtin_ia32_mpsadbw128:
2351   case X86::BI__builtin_ia32_mpsadbw256:
2352   case X86::BI__builtin_ia32_pcmpistrm128:
2353   case X86::BI__builtin_ia32_pcmpistri128:
2354   case X86::BI__builtin_ia32_pcmpistria128:
2355   case X86::BI__builtin_ia32_pcmpistric128:
2356   case X86::BI__builtin_ia32_pcmpistrio128:
2357   case X86::BI__builtin_ia32_pcmpistris128:
2358   case X86::BI__builtin_ia32_pcmpistriz128:
2359   case X86::BI__builtin_ia32_pclmulqdq128:
2360   case X86::BI__builtin_ia32_vperm2f128_pd256:
2361   case X86::BI__builtin_ia32_vperm2f128_ps256:
2362   case X86::BI__builtin_ia32_vperm2f128_si256:
2363   case X86::BI__builtin_ia32_permti256:
2364     i = 2; l = -128; u = 255;
2365     break;
2366   case X86::BI__builtin_ia32_palignr128:
2367   case X86::BI__builtin_ia32_palignr256:
2368   case X86::BI__builtin_ia32_palignr512_mask:
2369   case X86::BI__builtin_ia32_vcomisd:
2370   case X86::BI__builtin_ia32_vcomiss:
2371   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2372   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2373   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2374   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2375   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2376   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2377   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2378     i = 2; l = 0; u = 255;
2379     break;
2380   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2381   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2382   case X86::BI__builtin_ia32_fixupimmps512_mask:
2383   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2384   case X86::BI__builtin_ia32_fixupimmsd_mask:
2385   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2386   case X86::BI__builtin_ia32_fixupimmss_mask:
2387   case X86::BI__builtin_ia32_fixupimmss_maskz:
2388   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2389   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2390   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2391   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2392   case X86::BI__builtin_ia32_fixupimmps128_mask:
2393   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2394   case X86::BI__builtin_ia32_fixupimmps256_mask:
2395   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2396   case X86::BI__builtin_ia32_pternlogd512_mask:
2397   case X86::BI__builtin_ia32_pternlogd512_maskz:
2398   case X86::BI__builtin_ia32_pternlogq512_mask:
2399   case X86::BI__builtin_ia32_pternlogq512_maskz:
2400   case X86::BI__builtin_ia32_pternlogd128_mask:
2401   case X86::BI__builtin_ia32_pternlogd128_maskz:
2402   case X86::BI__builtin_ia32_pternlogd256_mask:
2403   case X86::BI__builtin_ia32_pternlogd256_maskz:
2404   case X86::BI__builtin_ia32_pternlogq128_mask:
2405   case X86::BI__builtin_ia32_pternlogq128_maskz:
2406   case X86::BI__builtin_ia32_pternlogq256_mask:
2407   case X86::BI__builtin_ia32_pternlogq256_maskz:
2408     i = 3; l = 0; u = 255;
2409     break;
2410   case X86::BI__builtin_ia32_gatherpfdpd:
2411   case X86::BI__builtin_ia32_gatherpfdps:
2412   case X86::BI__builtin_ia32_gatherpfqpd:
2413   case X86::BI__builtin_ia32_gatherpfqps:
2414   case X86::BI__builtin_ia32_scatterpfdpd:
2415   case X86::BI__builtin_ia32_scatterpfdps:
2416   case X86::BI__builtin_ia32_scatterpfqpd:
2417   case X86::BI__builtin_ia32_scatterpfqps:
2418     i = 4; l = 2; u = 3;
2419     break;
2420   case X86::BI__builtin_ia32_pcmpestrm128:
2421   case X86::BI__builtin_ia32_pcmpestri128:
2422   case X86::BI__builtin_ia32_pcmpestria128:
2423   case X86::BI__builtin_ia32_pcmpestric128:
2424   case X86::BI__builtin_ia32_pcmpestrio128:
2425   case X86::BI__builtin_ia32_pcmpestris128:
2426   case X86::BI__builtin_ia32_pcmpestriz128:
2427     i = 4; l = -128; u = 255;
2428     break;
2429   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2430   case X86::BI__builtin_ia32_rndscaless_round_mask:
2431     i = 4; l = 0; u = 255;
2432     break;
2433   }
2434   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2435 }
2436 
2437 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2438 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2439 /// Returns true when the format fits the function and the FormatStringInfo has
2440 /// been populated.
2441 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2442                                FormatStringInfo *FSI) {
2443   FSI->HasVAListArg = Format->getFirstArg() == 0;
2444   FSI->FormatIdx = Format->getFormatIdx() - 1;
2445   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2446 
2447   // The way the format attribute works in GCC, the implicit this argument
2448   // of member functions is counted. However, it doesn't appear in our own
2449   // lists, so decrement format_idx in that case.
2450   if (IsCXXMember) {
2451     if(FSI->FormatIdx == 0)
2452       return false;
2453     --FSI->FormatIdx;
2454     if (FSI->FirstDataArg != 0)
2455       --FSI->FirstDataArg;
2456   }
2457   return true;
2458 }
2459 
2460 /// Checks if a the given expression evaluates to null.
2461 ///
2462 /// \brief Returns true if the value evaluates to null.
2463 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2464   // If the expression has non-null type, it doesn't evaluate to null.
2465   if (auto nullability
2466         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2467     if (*nullability == NullabilityKind::NonNull)
2468       return false;
2469   }
2470 
2471   // As a special case, transparent unions initialized with zero are
2472   // considered null for the purposes of the nonnull attribute.
2473   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2474     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2475       if (const CompoundLiteralExpr *CLE =
2476           dyn_cast<CompoundLiteralExpr>(Expr))
2477         if (const InitListExpr *ILE =
2478             dyn_cast<InitListExpr>(CLE->getInitializer()))
2479           Expr = ILE->getInit(0);
2480   }
2481 
2482   bool Result;
2483   return (!Expr->isValueDependent() &&
2484           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2485           !Result);
2486 }
2487 
2488 static void CheckNonNullArgument(Sema &S,
2489                                  const Expr *ArgExpr,
2490                                  SourceLocation CallSiteLoc) {
2491   if (CheckNonNullExpr(S, ArgExpr))
2492     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2493            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2494 }
2495 
2496 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2497   FormatStringInfo FSI;
2498   if ((GetFormatStringType(Format) == FST_NSString) &&
2499       getFormatStringInfo(Format, false, &FSI)) {
2500     Idx = FSI.FormatIdx;
2501     return true;
2502   }
2503   return false;
2504 }
2505 /// \brief Diagnose use of %s directive in an NSString which is being passed
2506 /// as formatting string to formatting method.
2507 static void
2508 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2509                                         const NamedDecl *FDecl,
2510                                         Expr **Args,
2511                                         unsigned NumArgs) {
2512   unsigned Idx = 0;
2513   bool Format = false;
2514   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2515   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2516     Idx = 2;
2517     Format = true;
2518   }
2519   else
2520     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2521       if (S.GetFormatNSStringIdx(I, Idx)) {
2522         Format = true;
2523         break;
2524       }
2525     }
2526   if (!Format || NumArgs <= Idx)
2527     return;
2528   const Expr *FormatExpr = Args[Idx];
2529   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2530     FormatExpr = CSCE->getSubExpr();
2531   const StringLiteral *FormatString;
2532   if (const ObjCStringLiteral *OSL =
2533       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2534     FormatString = OSL->getString();
2535   else
2536     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2537   if (!FormatString)
2538     return;
2539   if (S.FormatStringHasSArg(FormatString)) {
2540     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2541       << "%s" << 1 << 1;
2542     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2543       << FDecl->getDeclName();
2544   }
2545 }
2546 
2547 /// Determine whether the given type has a non-null nullability annotation.
2548 static bool isNonNullType(ASTContext &ctx, QualType type) {
2549   if (auto nullability = type->getNullability(ctx))
2550     return *nullability == NullabilityKind::NonNull;
2551 
2552   return false;
2553 }
2554 
2555 static void CheckNonNullArguments(Sema &S,
2556                                   const NamedDecl *FDecl,
2557                                   const FunctionProtoType *Proto,
2558                                   ArrayRef<const Expr *> Args,
2559                                   SourceLocation CallSiteLoc) {
2560   assert((FDecl || Proto) && "Need a function declaration or prototype");
2561 
2562   // Check the attributes attached to the method/function itself.
2563   llvm::SmallBitVector NonNullArgs;
2564   if (FDecl) {
2565     // Handle the nonnull attribute on the function/method declaration itself.
2566     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2567       if (!NonNull->args_size()) {
2568         // Easy case: all pointer arguments are nonnull.
2569         for (const auto *Arg : Args)
2570           if (S.isValidPointerAttrType(Arg->getType()))
2571             CheckNonNullArgument(S, Arg, CallSiteLoc);
2572         return;
2573       }
2574 
2575       for (unsigned Val : NonNull->args()) {
2576         if (Val >= Args.size())
2577           continue;
2578         if (NonNullArgs.empty())
2579           NonNullArgs.resize(Args.size());
2580         NonNullArgs.set(Val);
2581       }
2582     }
2583   }
2584 
2585   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2586     // Handle the nonnull attribute on the parameters of the
2587     // function/method.
2588     ArrayRef<ParmVarDecl*> parms;
2589     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2590       parms = FD->parameters();
2591     else
2592       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2593 
2594     unsigned ParamIndex = 0;
2595     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2596          I != E; ++I, ++ParamIndex) {
2597       const ParmVarDecl *PVD = *I;
2598       if (PVD->hasAttr<NonNullAttr>() ||
2599           isNonNullType(S.Context, PVD->getType())) {
2600         if (NonNullArgs.empty())
2601           NonNullArgs.resize(Args.size());
2602 
2603         NonNullArgs.set(ParamIndex);
2604       }
2605     }
2606   } else {
2607     // If we have a non-function, non-method declaration but no
2608     // function prototype, try to dig out the function prototype.
2609     if (!Proto) {
2610       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2611         QualType type = VD->getType().getNonReferenceType();
2612         if (auto pointerType = type->getAs<PointerType>())
2613           type = pointerType->getPointeeType();
2614         else if (auto blockType = type->getAs<BlockPointerType>())
2615           type = blockType->getPointeeType();
2616         // FIXME: data member pointers?
2617 
2618         // Dig out the function prototype, if there is one.
2619         Proto = type->getAs<FunctionProtoType>();
2620       }
2621     }
2622 
2623     // Fill in non-null argument information from the nullability
2624     // information on the parameter types (if we have them).
2625     if (Proto) {
2626       unsigned Index = 0;
2627       for (auto paramType : Proto->getParamTypes()) {
2628         if (isNonNullType(S.Context, paramType)) {
2629           if (NonNullArgs.empty())
2630             NonNullArgs.resize(Args.size());
2631 
2632           NonNullArgs.set(Index);
2633         }
2634 
2635         ++Index;
2636       }
2637     }
2638   }
2639 
2640   // Check for non-null arguments.
2641   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2642        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2643     if (NonNullArgs[ArgIndex])
2644       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2645   }
2646 }
2647 
2648 /// Handles the checks for format strings, non-POD arguments to vararg
2649 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2650 /// attributes.
2651 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2652                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2653                      bool IsMemberFunction, SourceLocation Loc,
2654                      SourceRange Range, VariadicCallType CallType) {
2655   // FIXME: We should check as much as we can in the template definition.
2656   if (CurContext->isDependentContext())
2657     return;
2658 
2659   // Printf and scanf checking.
2660   llvm::SmallBitVector CheckedVarArgs;
2661   if (FDecl) {
2662     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2663       // Only create vector if there are format attributes.
2664       CheckedVarArgs.resize(Args.size());
2665 
2666       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2667                            CheckedVarArgs);
2668     }
2669   }
2670 
2671   // Refuse POD arguments that weren't caught by the format string
2672   // checks above.
2673   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2674   if (CallType != VariadicDoesNotApply &&
2675       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2676     unsigned NumParams = Proto ? Proto->getNumParams()
2677                        : FDecl && isa<FunctionDecl>(FDecl)
2678                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2679                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2680                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2681                        : 0;
2682 
2683     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2684       // Args[ArgIdx] can be null in malformed code.
2685       if (const Expr *Arg = Args[ArgIdx]) {
2686         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2687           checkVariadicArgument(Arg, CallType);
2688       }
2689     }
2690   }
2691 
2692   if (FDecl || Proto) {
2693     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2694 
2695     // Type safety checking.
2696     if (FDecl) {
2697       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2698         CheckArgumentWithTypeTag(I, Args.data());
2699     }
2700   }
2701 
2702   if (FD)
2703     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2704 }
2705 
2706 /// CheckConstructorCall - Check a constructor call for correctness and safety
2707 /// properties not enforced by the C type system.
2708 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2709                                 ArrayRef<const Expr *> Args,
2710                                 const FunctionProtoType *Proto,
2711                                 SourceLocation Loc) {
2712   VariadicCallType CallType =
2713     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2714   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2715             Loc, SourceRange(), CallType);
2716 }
2717 
2718 /// CheckFunctionCall - Check a direct function call for various correctness
2719 /// and safety properties not strictly enforced by the C type system.
2720 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2721                              const FunctionProtoType *Proto) {
2722   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2723                               isa<CXXMethodDecl>(FDecl);
2724   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2725                           IsMemberOperatorCall;
2726   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2727                                                   TheCall->getCallee());
2728   Expr** Args = TheCall->getArgs();
2729   unsigned NumArgs = TheCall->getNumArgs();
2730 
2731   Expr *ImplicitThis = nullptr;
2732   if (IsMemberOperatorCall) {
2733     // If this is a call to a member operator, hide the first argument
2734     // from checkCall.
2735     // FIXME: Our choice of AST representation here is less than ideal.
2736     ImplicitThis = Args[0];
2737     ++Args;
2738     --NumArgs;
2739   } else if (IsMemberFunction)
2740     ImplicitThis =
2741         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2742 
2743   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2744             IsMemberFunction, TheCall->getRParenLoc(),
2745             TheCall->getCallee()->getSourceRange(), CallType);
2746 
2747   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2748   // None of the checks below are needed for functions that don't have
2749   // simple names (e.g., C++ conversion functions).
2750   if (!FnInfo)
2751     return false;
2752 
2753   CheckAbsoluteValueFunction(TheCall, FDecl);
2754   CheckMaxUnsignedZero(TheCall, FDecl);
2755 
2756   if (getLangOpts().ObjC1)
2757     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2758 
2759   unsigned CMId = FDecl->getMemoryFunctionKind();
2760   if (CMId == 0)
2761     return false;
2762 
2763   // Handle memory setting and copying functions.
2764   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2765     CheckStrlcpycatArguments(TheCall, FnInfo);
2766   else if (CMId == Builtin::BIstrncat)
2767     CheckStrncatArguments(TheCall, FnInfo);
2768   else
2769     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2770 
2771   return false;
2772 }
2773 
2774 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2775                                ArrayRef<const Expr *> Args) {
2776   VariadicCallType CallType =
2777       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2778 
2779   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2780             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2781             CallType);
2782 
2783   return false;
2784 }
2785 
2786 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2787                             const FunctionProtoType *Proto) {
2788   QualType Ty;
2789   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2790     Ty = V->getType().getNonReferenceType();
2791   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2792     Ty = F->getType().getNonReferenceType();
2793   else
2794     return false;
2795 
2796   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2797       !Ty->isFunctionProtoType())
2798     return false;
2799 
2800   VariadicCallType CallType;
2801   if (!Proto || !Proto->isVariadic()) {
2802     CallType = VariadicDoesNotApply;
2803   } else if (Ty->isBlockPointerType()) {
2804     CallType = VariadicBlock;
2805   } else { // Ty->isFunctionPointerType()
2806     CallType = VariadicFunction;
2807   }
2808 
2809   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2810             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2811             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2812             TheCall->getCallee()->getSourceRange(), CallType);
2813 
2814   return false;
2815 }
2816 
2817 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2818 /// such as function pointers returned from functions.
2819 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2820   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2821                                                   TheCall->getCallee());
2822   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2823             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2824             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2825             TheCall->getCallee()->getSourceRange(), CallType);
2826 
2827   return false;
2828 }
2829 
2830 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2831   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2832     return false;
2833 
2834   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2835   switch (Op) {
2836   case AtomicExpr::AO__c11_atomic_init:
2837   case AtomicExpr::AO__opencl_atomic_init:
2838     llvm_unreachable("There is no ordering argument for an init");
2839 
2840   case AtomicExpr::AO__c11_atomic_load:
2841   case AtomicExpr::AO__opencl_atomic_load:
2842   case AtomicExpr::AO__atomic_load_n:
2843   case AtomicExpr::AO__atomic_load:
2844     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2845            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2846 
2847   case AtomicExpr::AO__c11_atomic_store:
2848   case AtomicExpr::AO__opencl_atomic_store:
2849   case AtomicExpr::AO__atomic_store:
2850   case AtomicExpr::AO__atomic_store_n:
2851     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2852            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2853            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2854 
2855   default:
2856     return true;
2857   }
2858 }
2859 
2860 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2861                                          AtomicExpr::AtomicOp Op) {
2862   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2863   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2864 
2865   // All the non-OpenCL operations take one of the following forms.
2866   // The OpenCL operations take the __c11 forms with one extra argument for
2867   // synchronization scope.
2868   enum {
2869     // C    __c11_atomic_init(A *, C)
2870     Init,
2871     // C    __c11_atomic_load(A *, int)
2872     Load,
2873     // void __atomic_load(A *, CP, int)
2874     LoadCopy,
2875     // void __atomic_store(A *, CP, int)
2876     Copy,
2877     // C    __c11_atomic_add(A *, M, int)
2878     Arithmetic,
2879     // C    __atomic_exchange_n(A *, CP, int)
2880     Xchg,
2881     // void __atomic_exchange(A *, C *, CP, int)
2882     GNUXchg,
2883     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2884     C11CmpXchg,
2885     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2886     GNUCmpXchg
2887   } Form = Init;
2888   const unsigned NumForm = GNUCmpXchg + 1;
2889   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2890   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2891   // where:
2892   //   C is an appropriate type,
2893   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2894   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2895   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2896   //   the int parameters are for orderings.
2897 
2898   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2899       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2900       "need to update code for modified forms");
2901   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2902                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2903                         AtomicExpr::AO__atomic_load,
2904                 "need to update code for modified C11 atomics");
2905   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2906                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2907   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2908                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2909                IsOpenCL;
2910   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2911              Op == AtomicExpr::AO__atomic_store_n ||
2912              Op == AtomicExpr::AO__atomic_exchange_n ||
2913              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2914   bool IsAddSub = false;
2915 
2916   switch (Op) {
2917   case AtomicExpr::AO__c11_atomic_init:
2918   case AtomicExpr::AO__opencl_atomic_init:
2919     Form = Init;
2920     break;
2921 
2922   case AtomicExpr::AO__c11_atomic_load:
2923   case AtomicExpr::AO__opencl_atomic_load:
2924   case AtomicExpr::AO__atomic_load_n:
2925     Form = Load;
2926     break;
2927 
2928   case AtomicExpr::AO__atomic_load:
2929     Form = LoadCopy;
2930     break;
2931 
2932   case AtomicExpr::AO__c11_atomic_store:
2933   case AtomicExpr::AO__opencl_atomic_store:
2934   case AtomicExpr::AO__atomic_store:
2935   case AtomicExpr::AO__atomic_store_n:
2936     Form = Copy;
2937     break;
2938 
2939   case AtomicExpr::AO__c11_atomic_fetch_add:
2940   case AtomicExpr::AO__c11_atomic_fetch_sub:
2941   case AtomicExpr::AO__opencl_atomic_fetch_add:
2942   case AtomicExpr::AO__opencl_atomic_fetch_sub:
2943   case AtomicExpr::AO__opencl_atomic_fetch_min:
2944   case AtomicExpr::AO__opencl_atomic_fetch_max:
2945   case AtomicExpr::AO__atomic_fetch_add:
2946   case AtomicExpr::AO__atomic_fetch_sub:
2947   case AtomicExpr::AO__atomic_add_fetch:
2948   case AtomicExpr::AO__atomic_sub_fetch:
2949     IsAddSub = true;
2950     // Fall through.
2951   case AtomicExpr::AO__c11_atomic_fetch_and:
2952   case AtomicExpr::AO__c11_atomic_fetch_or:
2953   case AtomicExpr::AO__c11_atomic_fetch_xor:
2954   case AtomicExpr::AO__opencl_atomic_fetch_and:
2955   case AtomicExpr::AO__opencl_atomic_fetch_or:
2956   case AtomicExpr::AO__opencl_atomic_fetch_xor:
2957   case AtomicExpr::AO__atomic_fetch_and:
2958   case AtomicExpr::AO__atomic_fetch_or:
2959   case AtomicExpr::AO__atomic_fetch_xor:
2960   case AtomicExpr::AO__atomic_fetch_nand:
2961   case AtomicExpr::AO__atomic_and_fetch:
2962   case AtomicExpr::AO__atomic_or_fetch:
2963   case AtomicExpr::AO__atomic_xor_fetch:
2964   case AtomicExpr::AO__atomic_nand_fetch:
2965     Form = Arithmetic;
2966     break;
2967 
2968   case AtomicExpr::AO__c11_atomic_exchange:
2969   case AtomicExpr::AO__opencl_atomic_exchange:
2970   case AtomicExpr::AO__atomic_exchange_n:
2971     Form = Xchg;
2972     break;
2973 
2974   case AtomicExpr::AO__atomic_exchange:
2975     Form = GNUXchg;
2976     break;
2977 
2978   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2979   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2980   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2981   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
2982     Form = C11CmpXchg;
2983     break;
2984 
2985   case AtomicExpr::AO__atomic_compare_exchange:
2986   case AtomicExpr::AO__atomic_compare_exchange_n:
2987     Form = GNUCmpXchg;
2988     break;
2989   }
2990 
2991   unsigned AdjustedNumArgs = NumArgs[Form];
2992   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2993     ++AdjustedNumArgs;
2994   // Check we have the right number of arguments.
2995   if (TheCall->getNumArgs() < AdjustedNumArgs) {
2996     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2997       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
2998       << TheCall->getCallee()->getSourceRange();
2999     return ExprError();
3000   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3001     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3002          diag::err_typecheck_call_too_many_args)
3003       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3004       << TheCall->getCallee()->getSourceRange();
3005     return ExprError();
3006   }
3007 
3008   // Inspect the first argument of the atomic operation.
3009   Expr *Ptr = TheCall->getArg(0);
3010   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3011   if (ConvertedPtr.isInvalid())
3012     return ExprError();
3013 
3014   Ptr = ConvertedPtr.get();
3015   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3016   if (!pointerType) {
3017     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3018       << Ptr->getType() << Ptr->getSourceRange();
3019     return ExprError();
3020   }
3021 
3022   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3023   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3024   QualType ValType = AtomTy; // 'C'
3025   if (IsC11) {
3026     if (!AtomTy->isAtomicType()) {
3027       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3028         << Ptr->getType() << Ptr->getSourceRange();
3029       return ExprError();
3030     }
3031     if (AtomTy.isConstQualified() ||
3032         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3033       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3034           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3035           << Ptr->getSourceRange();
3036       return ExprError();
3037     }
3038     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3039   } else if (Form != Load && Form != LoadCopy) {
3040     if (ValType.isConstQualified()) {
3041       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3042         << Ptr->getType() << Ptr->getSourceRange();
3043       return ExprError();
3044     }
3045   }
3046 
3047   // For an arithmetic operation, the implied arithmetic must be well-formed.
3048   if (Form == Arithmetic) {
3049     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3050     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3051       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3052         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3053       return ExprError();
3054     }
3055     if (!IsAddSub && !ValType->isIntegerType()) {
3056       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3057         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3058       return ExprError();
3059     }
3060     if (IsC11 && ValType->isPointerType() &&
3061         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3062                             diag::err_incomplete_type)) {
3063       return ExprError();
3064     }
3065   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3066     // For __atomic_*_n operations, the value type must be a scalar integral or
3067     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3068     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3069       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3070     return ExprError();
3071   }
3072 
3073   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3074       !AtomTy->isScalarType()) {
3075     // For GNU atomics, require a trivially-copyable type. This is not part of
3076     // the GNU atomics specification, but we enforce it for sanity.
3077     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3078       << Ptr->getType() << Ptr->getSourceRange();
3079     return ExprError();
3080   }
3081 
3082   switch (ValType.getObjCLifetime()) {
3083   case Qualifiers::OCL_None:
3084   case Qualifiers::OCL_ExplicitNone:
3085     // okay
3086     break;
3087 
3088   case Qualifiers::OCL_Weak:
3089   case Qualifiers::OCL_Strong:
3090   case Qualifiers::OCL_Autoreleasing:
3091     // FIXME: Can this happen? By this point, ValType should be known
3092     // to be trivially copyable.
3093     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3094       << ValType << Ptr->getSourceRange();
3095     return ExprError();
3096   }
3097 
3098   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3099   // volatile-ness of the pointee-type inject itself into the result or the
3100   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3101   ValType.removeLocalVolatile();
3102   ValType.removeLocalConst();
3103   QualType ResultType = ValType;
3104   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3105       Form == Init)
3106     ResultType = Context.VoidTy;
3107   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3108     ResultType = Context.BoolTy;
3109 
3110   // The type of a parameter passed 'by value'. In the GNU atomics, such
3111   // arguments are actually passed as pointers.
3112   QualType ByValType = ValType; // 'CP'
3113   if (!IsC11 && !IsN)
3114     ByValType = Ptr->getType();
3115 
3116   // The first argument --- the pointer --- has a fixed type; we
3117   // deduce the types of the rest of the arguments accordingly.  Walk
3118   // the remaining arguments, converting them to the deduced value type.
3119   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3120     QualType Ty;
3121     if (i < NumVals[Form] + 1) {
3122       switch (i) {
3123       case 1:
3124         // The second argument is the non-atomic operand. For arithmetic, this
3125         // is always passed by value, and for a compare_exchange it is always
3126         // passed by address. For the rest, GNU uses by-address and C11 uses
3127         // by-value.
3128         assert(Form != Load);
3129         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3130           Ty = ValType;
3131         else if (Form == Copy || Form == Xchg)
3132           Ty = ByValType;
3133         else if (Form == Arithmetic)
3134           Ty = Context.getPointerDiffType();
3135         else {
3136           Expr *ValArg = TheCall->getArg(i);
3137           // Treat this argument as _Nonnull as we want to show a warning if
3138           // NULL is passed into it.
3139           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3140           unsigned AS = 0;
3141           // Keep address space of non-atomic pointer type.
3142           if (const PointerType *PtrTy =
3143                   ValArg->getType()->getAs<PointerType>()) {
3144             AS = PtrTy->getPointeeType().getAddressSpace();
3145           }
3146           Ty = Context.getPointerType(
3147               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3148         }
3149         break;
3150       case 2:
3151         // The third argument to compare_exchange / GNU exchange is a
3152         // (pointer to a) desired value.
3153         Ty = ByValType;
3154         break;
3155       case 3:
3156         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3157         Ty = Context.BoolTy;
3158         break;
3159       }
3160     } else {
3161       // The order(s) and scope are always converted to int.
3162       Ty = Context.IntTy;
3163     }
3164 
3165     InitializedEntity Entity =
3166         InitializedEntity::InitializeParameter(Context, Ty, false);
3167     ExprResult Arg = TheCall->getArg(i);
3168     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3169     if (Arg.isInvalid())
3170       return true;
3171     TheCall->setArg(i, Arg.get());
3172   }
3173 
3174   // Permute the arguments into a 'consistent' order.
3175   SmallVector<Expr*, 5> SubExprs;
3176   SubExprs.push_back(Ptr);
3177   switch (Form) {
3178   case Init:
3179     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3180     SubExprs.push_back(TheCall->getArg(1)); // Val1
3181     break;
3182   case Load:
3183     SubExprs.push_back(TheCall->getArg(1)); // Order
3184     break;
3185   case LoadCopy:
3186   case Copy:
3187   case Arithmetic:
3188   case Xchg:
3189     SubExprs.push_back(TheCall->getArg(2)); // Order
3190     SubExprs.push_back(TheCall->getArg(1)); // Val1
3191     break;
3192   case GNUXchg:
3193     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3194     SubExprs.push_back(TheCall->getArg(3)); // Order
3195     SubExprs.push_back(TheCall->getArg(1)); // Val1
3196     SubExprs.push_back(TheCall->getArg(2)); // Val2
3197     break;
3198   case C11CmpXchg:
3199     SubExprs.push_back(TheCall->getArg(3)); // Order
3200     SubExprs.push_back(TheCall->getArg(1)); // Val1
3201     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3202     SubExprs.push_back(TheCall->getArg(2)); // Val2
3203     break;
3204   case GNUCmpXchg:
3205     SubExprs.push_back(TheCall->getArg(4)); // Order
3206     SubExprs.push_back(TheCall->getArg(1)); // Val1
3207     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3208     SubExprs.push_back(TheCall->getArg(2)); // Val2
3209     SubExprs.push_back(TheCall->getArg(3)); // Weak
3210     break;
3211   }
3212 
3213   if (SubExprs.size() >= 2 && Form != Init) {
3214     llvm::APSInt Result(32);
3215     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3216         !isValidOrderingForOp(Result.getSExtValue(), Op))
3217       Diag(SubExprs[1]->getLocStart(),
3218            diag::warn_atomic_op_has_invalid_memory_order)
3219           << SubExprs[1]->getSourceRange();
3220   }
3221 
3222   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3223     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3224     llvm::APSInt Result(32);
3225     if (Scope->isIntegerConstantExpr(Result, Context) &&
3226         !ScopeModel->isValid(Result.getZExtValue())) {
3227       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3228           << Scope->getSourceRange();
3229     }
3230     SubExprs.push_back(Scope);
3231   }
3232 
3233   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3234                                             SubExprs, ResultType, Op,
3235                                             TheCall->getRParenLoc());
3236 
3237   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3238        Op == AtomicExpr::AO__c11_atomic_store ||
3239        Op == AtomicExpr::AO__opencl_atomic_load ||
3240        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3241       Context.AtomicUsesUnsupportedLibcall(AE))
3242     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3243         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3244             Op == AtomicExpr::AO__opencl_atomic_load)
3245                 ? 0 : 1);
3246 
3247   return AE;
3248 }
3249 
3250 /// checkBuiltinArgument - Given a call to a builtin function, perform
3251 /// normal type-checking on the given argument, updating the call in
3252 /// place.  This is useful when a builtin function requires custom
3253 /// type-checking for some of its arguments but not necessarily all of
3254 /// them.
3255 ///
3256 /// Returns true on error.
3257 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3258   FunctionDecl *Fn = E->getDirectCallee();
3259   assert(Fn && "builtin call without direct callee!");
3260 
3261   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3262   InitializedEntity Entity =
3263     InitializedEntity::InitializeParameter(S.Context, Param);
3264 
3265   ExprResult Arg = E->getArg(0);
3266   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3267   if (Arg.isInvalid())
3268     return true;
3269 
3270   E->setArg(ArgIndex, Arg.get());
3271   return false;
3272 }
3273 
3274 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3275 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3276 /// type of its first argument.  The main ActOnCallExpr routines have already
3277 /// promoted the types of arguments because all of these calls are prototyped as
3278 /// void(...).
3279 ///
3280 /// This function goes through and does final semantic checking for these
3281 /// builtins,
3282 ExprResult
3283 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3284   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3285   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3286   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3287 
3288   // Ensure that we have at least one argument to do type inference from.
3289   if (TheCall->getNumArgs() < 1) {
3290     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3291       << 0 << 1 << TheCall->getNumArgs()
3292       << TheCall->getCallee()->getSourceRange();
3293     return ExprError();
3294   }
3295 
3296   // Inspect the first argument of the atomic builtin.  This should always be
3297   // a pointer type, whose element is an integral scalar or pointer type.
3298   // Because it is a pointer type, we don't have to worry about any implicit
3299   // casts here.
3300   // FIXME: We don't allow floating point scalars as input.
3301   Expr *FirstArg = TheCall->getArg(0);
3302   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3303   if (FirstArgResult.isInvalid())
3304     return ExprError();
3305   FirstArg = FirstArgResult.get();
3306   TheCall->setArg(0, FirstArg);
3307 
3308   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3309   if (!pointerType) {
3310     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3311       << FirstArg->getType() << FirstArg->getSourceRange();
3312     return ExprError();
3313   }
3314 
3315   QualType ValType = pointerType->getPointeeType();
3316   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3317       !ValType->isBlockPointerType()) {
3318     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3319       << FirstArg->getType() << FirstArg->getSourceRange();
3320     return ExprError();
3321   }
3322 
3323   switch (ValType.getObjCLifetime()) {
3324   case Qualifiers::OCL_None:
3325   case Qualifiers::OCL_ExplicitNone:
3326     // okay
3327     break;
3328 
3329   case Qualifiers::OCL_Weak:
3330   case Qualifiers::OCL_Strong:
3331   case Qualifiers::OCL_Autoreleasing:
3332     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3333       << ValType << FirstArg->getSourceRange();
3334     return ExprError();
3335   }
3336 
3337   // Strip any qualifiers off ValType.
3338   ValType = ValType.getUnqualifiedType();
3339 
3340   // The majority of builtins return a value, but a few have special return
3341   // types, so allow them to override appropriately below.
3342   QualType ResultType = ValType;
3343 
3344   // We need to figure out which concrete builtin this maps onto.  For example,
3345   // __sync_fetch_and_add with a 2 byte object turns into
3346   // __sync_fetch_and_add_2.
3347 #define BUILTIN_ROW(x) \
3348   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3349     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3350 
3351   static const unsigned BuiltinIndices[][5] = {
3352     BUILTIN_ROW(__sync_fetch_and_add),
3353     BUILTIN_ROW(__sync_fetch_and_sub),
3354     BUILTIN_ROW(__sync_fetch_and_or),
3355     BUILTIN_ROW(__sync_fetch_and_and),
3356     BUILTIN_ROW(__sync_fetch_and_xor),
3357     BUILTIN_ROW(__sync_fetch_and_nand),
3358 
3359     BUILTIN_ROW(__sync_add_and_fetch),
3360     BUILTIN_ROW(__sync_sub_and_fetch),
3361     BUILTIN_ROW(__sync_and_and_fetch),
3362     BUILTIN_ROW(__sync_or_and_fetch),
3363     BUILTIN_ROW(__sync_xor_and_fetch),
3364     BUILTIN_ROW(__sync_nand_and_fetch),
3365 
3366     BUILTIN_ROW(__sync_val_compare_and_swap),
3367     BUILTIN_ROW(__sync_bool_compare_and_swap),
3368     BUILTIN_ROW(__sync_lock_test_and_set),
3369     BUILTIN_ROW(__sync_lock_release),
3370     BUILTIN_ROW(__sync_swap)
3371   };
3372 #undef BUILTIN_ROW
3373 
3374   // Determine the index of the size.
3375   unsigned SizeIndex;
3376   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3377   case 1: SizeIndex = 0; break;
3378   case 2: SizeIndex = 1; break;
3379   case 4: SizeIndex = 2; break;
3380   case 8: SizeIndex = 3; break;
3381   case 16: SizeIndex = 4; break;
3382   default:
3383     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3384       << FirstArg->getType() << FirstArg->getSourceRange();
3385     return ExprError();
3386   }
3387 
3388   // Each of these builtins has one pointer argument, followed by some number of
3389   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3390   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3391   // as the number of fixed args.
3392   unsigned BuiltinID = FDecl->getBuiltinID();
3393   unsigned BuiltinIndex, NumFixed = 1;
3394   bool WarnAboutSemanticsChange = false;
3395   switch (BuiltinID) {
3396   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3397   case Builtin::BI__sync_fetch_and_add:
3398   case Builtin::BI__sync_fetch_and_add_1:
3399   case Builtin::BI__sync_fetch_and_add_2:
3400   case Builtin::BI__sync_fetch_and_add_4:
3401   case Builtin::BI__sync_fetch_and_add_8:
3402   case Builtin::BI__sync_fetch_and_add_16:
3403     BuiltinIndex = 0;
3404     break;
3405 
3406   case Builtin::BI__sync_fetch_and_sub:
3407   case Builtin::BI__sync_fetch_and_sub_1:
3408   case Builtin::BI__sync_fetch_and_sub_2:
3409   case Builtin::BI__sync_fetch_and_sub_4:
3410   case Builtin::BI__sync_fetch_and_sub_8:
3411   case Builtin::BI__sync_fetch_and_sub_16:
3412     BuiltinIndex = 1;
3413     break;
3414 
3415   case Builtin::BI__sync_fetch_and_or:
3416   case Builtin::BI__sync_fetch_and_or_1:
3417   case Builtin::BI__sync_fetch_and_or_2:
3418   case Builtin::BI__sync_fetch_and_or_4:
3419   case Builtin::BI__sync_fetch_and_or_8:
3420   case Builtin::BI__sync_fetch_and_or_16:
3421     BuiltinIndex = 2;
3422     break;
3423 
3424   case Builtin::BI__sync_fetch_and_and:
3425   case Builtin::BI__sync_fetch_and_and_1:
3426   case Builtin::BI__sync_fetch_and_and_2:
3427   case Builtin::BI__sync_fetch_and_and_4:
3428   case Builtin::BI__sync_fetch_and_and_8:
3429   case Builtin::BI__sync_fetch_and_and_16:
3430     BuiltinIndex = 3;
3431     break;
3432 
3433   case Builtin::BI__sync_fetch_and_xor:
3434   case Builtin::BI__sync_fetch_and_xor_1:
3435   case Builtin::BI__sync_fetch_and_xor_2:
3436   case Builtin::BI__sync_fetch_and_xor_4:
3437   case Builtin::BI__sync_fetch_and_xor_8:
3438   case Builtin::BI__sync_fetch_and_xor_16:
3439     BuiltinIndex = 4;
3440     break;
3441 
3442   case Builtin::BI__sync_fetch_and_nand:
3443   case Builtin::BI__sync_fetch_and_nand_1:
3444   case Builtin::BI__sync_fetch_and_nand_2:
3445   case Builtin::BI__sync_fetch_and_nand_4:
3446   case Builtin::BI__sync_fetch_and_nand_8:
3447   case Builtin::BI__sync_fetch_and_nand_16:
3448     BuiltinIndex = 5;
3449     WarnAboutSemanticsChange = true;
3450     break;
3451 
3452   case Builtin::BI__sync_add_and_fetch:
3453   case Builtin::BI__sync_add_and_fetch_1:
3454   case Builtin::BI__sync_add_and_fetch_2:
3455   case Builtin::BI__sync_add_and_fetch_4:
3456   case Builtin::BI__sync_add_and_fetch_8:
3457   case Builtin::BI__sync_add_and_fetch_16:
3458     BuiltinIndex = 6;
3459     break;
3460 
3461   case Builtin::BI__sync_sub_and_fetch:
3462   case Builtin::BI__sync_sub_and_fetch_1:
3463   case Builtin::BI__sync_sub_and_fetch_2:
3464   case Builtin::BI__sync_sub_and_fetch_4:
3465   case Builtin::BI__sync_sub_and_fetch_8:
3466   case Builtin::BI__sync_sub_and_fetch_16:
3467     BuiltinIndex = 7;
3468     break;
3469 
3470   case Builtin::BI__sync_and_and_fetch:
3471   case Builtin::BI__sync_and_and_fetch_1:
3472   case Builtin::BI__sync_and_and_fetch_2:
3473   case Builtin::BI__sync_and_and_fetch_4:
3474   case Builtin::BI__sync_and_and_fetch_8:
3475   case Builtin::BI__sync_and_and_fetch_16:
3476     BuiltinIndex = 8;
3477     break;
3478 
3479   case Builtin::BI__sync_or_and_fetch:
3480   case Builtin::BI__sync_or_and_fetch_1:
3481   case Builtin::BI__sync_or_and_fetch_2:
3482   case Builtin::BI__sync_or_and_fetch_4:
3483   case Builtin::BI__sync_or_and_fetch_8:
3484   case Builtin::BI__sync_or_and_fetch_16:
3485     BuiltinIndex = 9;
3486     break;
3487 
3488   case Builtin::BI__sync_xor_and_fetch:
3489   case Builtin::BI__sync_xor_and_fetch_1:
3490   case Builtin::BI__sync_xor_and_fetch_2:
3491   case Builtin::BI__sync_xor_and_fetch_4:
3492   case Builtin::BI__sync_xor_and_fetch_8:
3493   case Builtin::BI__sync_xor_and_fetch_16:
3494     BuiltinIndex = 10;
3495     break;
3496 
3497   case Builtin::BI__sync_nand_and_fetch:
3498   case Builtin::BI__sync_nand_and_fetch_1:
3499   case Builtin::BI__sync_nand_and_fetch_2:
3500   case Builtin::BI__sync_nand_and_fetch_4:
3501   case Builtin::BI__sync_nand_and_fetch_8:
3502   case Builtin::BI__sync_nand_and_fetch_16:
3503     BuiltinIndex = 11;
3504     WarnAboutSemanticsChange = true;
3505     break;
3506 
3507   case Builtin::BI__sync_val_compare_and_swap:
3508   case Builtin::BI__sync_val_compare_and_swap_1:
3509   case Builtin::BI__sync_val_compare_and_swap_2:
3510   case Builtin::BI__sync_val_compare_and_swap_4:
3511   case Builtin::BI__sync_val_compare_and_swap_8:
3512   case Builtin::BI__sync_val_compare_and_swap_16:
3513     BuiltinIndex = 12;
3514     NumFixed = 2;
3515     break;
3516 
3517   case Builtin::BI__sync_bool_compare_and_swap:
3518   case Builtin::BI__sync_bool_compare_and_swap_1:
3519   case Builtin::BI__sync_bool_compare_and_swap_2:
3520   case Builtin::BI__sync_bool_compare_and_swap_4:
3521   case Builtin::BI__sync_bool_compare_and_swap_8:
3522   case Builtin::BI__sync_bool_compare_and_swap_16:
3523     BuiltinIndex = 13;
3524     NumFixed = 2;
3525     ResultType = Context.BoolTy;
3526     break;
3527 
3528   case Builtin::BI__sync_lock_test_and_set:
3529   case Builtin::BI__sync_lock_test_and_set_1:
3530   case Builtin::BI__sync_lock_test_and_set_2:
3531   case Builtin::BI__sync_lock_test_and_set_4:
3532   case Builtin::BI__sync_lock_test_and_set_8:
3533   case Builtin::BI__sync_lock_test_and_set_16:
3534     BuiltinIndex = 14;
3535     break;
3536 
3537   case Builtin::BI__sync_lock_release:
3538   case Builtin::BI__sync_lock_release_1:
3539   case Builtin::BI__sync_lock_release_2:
3540   case Builtin::BI__sync_lock_release_4:
3541   case Builtin::BI__sync_lock_release_8:
3542   case Builtin::BI__sync_lock_release_16:
3543     BuiltinIndex = 15;
3544     NumFixed = 0;
3545     ResultType = Context.VoidTy;
3546     break;
3547 
3548   case Builtin::BI__sync_swap:
3549   case Builtin::BI__sync_swap_1:
3550   case Builtin::BI__sync_swap_2:
3551   case Builtin::BI__sync_swap_4:
3552   case Builtin::BI__sync_swap_8:
3553   case Builtin::BI__sync_swap_16:
3554     BuiltinIndex = 16;
3555     break;
3556   }
3557 
3558   // Now that we know how many fixed arguments we expect, first check that we
3559   // have at least that many.
3560   if (TheCall->getNumArgs() < 1+NumFixed) {
3561     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3562       << 0 << 1+NumFixed << TheCall->getNumArgs()
3563       << TheCall->getCallee()->getSourceRange();
3564     return ExprError();
3565   }
3566 
3567   if (WarnAboutSemanticsChange) {
3568     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3569       << TheCall->getCallee()->getSourceRange();
3570   }
3571 
3572   // Get the decl for the concrete builtin from this, we can tell what the
3573   // concrete integer type we should convert to is.
3574   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3575   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3576   FunctionDecl *NewBuiltinDecl;
3577   if (NewBuiltinID == BuiltinID)
3578     NewBuiltinDecl = FDecl;
3579   else {
3580     // Perform builtin lookup to avoid redeclaring it.
3581     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3582     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3583     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3584     assert(Res.getFoundDecl());
3585     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3586     if (!NewBuiltinDecl)
3587       return ExprError();
3588   }
3589 
3590   // The first argument --- the pointer --- has a fixed type; we
3591   // deduce the types of the rest of the arguments accordingly.  Walk
3592   // the remaining arguments, converting them to the deduced value type.
3593   for (unsigned i = 0; i != NumFixed; ++i) {
3594     ExprResult Arg = TheCall->getArg(i+1);
3595 
3596     // GCC does an implicit conversion to the pointer or integer ValType.  This
3597     // can fail in some cases (1i -> int**), check for this error case now.
3598     // Initialize the argument.
3599     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3600                                                    ValType, /*consume*/ false);
3601     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3602     if (Arg.isInvalid())
3603       return ExprError();
3604 
3605     // Okay, we have something that *can* be converted to the right type.  Check
3606     // to see if there is a potentially weird extension going on here.  This can
3607     // happen when you do an atomic operation on something like an char* and
3608     // pass in 42.  The 42 gets converted to char.  This is even more strange
3609     // for things like 45.123 -> char, etc.
3610     // FIXME: Do this check.
3611     TheCall->setArg(i+1, Arg.get());
3612   }
3613 
3614   ASTContext& Context = this->getASTContext();
3615 
3616   // Create a new DeclRefExpr to refer to the new decl.
3617   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3618       Context,
3619       DRE->getQualifierLoc(),
3620       SourceLocation(),
3621       NewBuiltinDecl,
3622       /*enclosing*/ false,
3623       DRE->getLocation(),
3624       Context.BuiltinFnTy,
3625       DRE->getValueKind());
3626 
3627   // Set the callee in the CallExpr.
3628   // FIXME: This loses syntactic information.
3629   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3630   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3631                                               CK_BuiltinFnToFnPtr);
3632   TheCall->setCallee(PromotedCall.get());
3633 
3634   // Change the result type of the call to match the original value type. This
3635   // is arbitrary, but the codegen for these builtins ins design to handle it
3636   // gracefully.
3637   TheCall->setType(ResultType);
3638 
3639   return TheCallResult;
3640 }
3641 
3642 /// SemaBuiltinNontemporalOverloaded - We have a call to
3643 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3644 /// overloaded function based on the pointer type of its last argument.
3645 ///
3646 /// This function goes through and does final semantic checking for these
3647 /// builtins.
3648 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3649   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3650   DeclRefExpr *DRE =
3651       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3652   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3653   unsigned BuiltinID = FDecl->getBuiltinID();
3654   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3655           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3656          "Unexpected nontemporal load/store builtin!");
3657   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3658   unsigned numArgs = isStore ? 2 : 1;
3659 
3660   // Ensure that we have the proper number of arguments.
3661   if (checkArgCount(*this, TheCall, numArgs))
3662     return ExprError();
3663 
3664   // Inspect the last argument of the nontemporal builtin.  This should always
3665   // be a pointer type, from which we imply the type of the memory access.
3666   // Because it is a pointer type, we don't have to worry about any implicit
3667   // casts here.
3668   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3669   ExprResult PointerArgResult =
3670       DefaultFunctionArrayLvalueConversion(PointerArg);
3671 
3672   if (PointerArgResult.isInvalid())
3673     return ExprError();
3674   PointerArg = PointerArgResult.get();
3675   TheCall->setArg(numArgs - 1, PointerArg);
3676 
3677   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3678   if (!pointerType) {
3679     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3680         << PointerArg->getType() << PointerArg->getSourceRange();
3681     return ExprError();
3682   }
3683 
3684   QualType ValType = pointerType->getPointeeType();
3685 
3686   // Strip any qualifiers off ValType.
3687   ValType = ValType.getUnqualifiedType();
3688   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3689       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3690       !ValType->isVectorType()) {
3691     Diag(DRE->getLocStart(),
3692          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3693         << PointerArg->getType() << PointerArg->getSourceRange();
3694     return ExprError();
3695   }
3696 
3697   if (!isStore) {
3698     TheCall->setType(ValType);
3699     return TheCallResult;
3700   }
3701 
3702   ExprResult ValArg = TheCall->getArg(0);
3703   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3704       Context, ValType, /*consume*/ false);
3705   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3706   if (ValArg.isInvalid())
3707     return ExprError();
3708 
3709   TheCall->setArg(0, ValArg.get());
3710   TheCall->setType(Context.VoidTy);
3711   return TheCallResult;
3712 }
3713 
3714 /// CheckObjCString - Checks that the argument to the builtin
3715 /// CFString constructor is correct
3716 /// Note: It might also make sense to do the UTF-16 conversion here (would
3717 /// simplify the backend).
3718 bool Sema::CheckObjCString(Expr *Arg) {
3719   Arg = Arg->IgnoreParenCasts();
3720   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3721 
3722   if (!Literal || !Literal->isAscii()) {
3723     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3724       << Arg->getSourceRange();
3725     return true;
3726   }
3727 
3728   if (Literal->containsNonAsciiOrNull()) {
3729     StringRef String = Literal->getString();
3730     unsigned NumBytes = String.size();
3731     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3732     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3733     llvm::UTF16 *ToPtr = &ToBuf[0];
3734 
3735     llvm::ConversionResult Result =
3736         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3737                                  ToPtr + NumBytes, llvm::strictConversion);
3738     // Check for conversion failure.
3739     if (Result != llvm::conversionOK)
3740       Diag(Arg->getLocStart(),
3741            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3742   }
3743   return false;
3744 }
3745 
3746 /// CheckObjCString - Checks that the format string argument to the os_log()
3747 /// and os_trace() functions is correct, and converts it to const char *.
3748 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3749   Arg = Arg->IgnoreParenCasts();
3750   auto *Literal = dyn_cast<StringLiteral>(Arg);
3751   if (!Literal) {
3752     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3753       Literal = ObjcLiteral->getString();
3754     }
3755   }
3756 
3757   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3758     return ExprError(
3759         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3760         << Arg->getSourceRange());
3761   }
3762 
3763   ExprResult Result(Literal);
3764   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3765   InitializedEntity Entity =
3766       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3767   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3768   return Result;
3769 }
3770 
3771 /// Check that the user is calling the appropriate va_start builtin for the
3772 /// target and calling convention.
3773 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3774   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3775   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3776   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3777   bool IsWindows = TT.isOSWindows();
3778   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3779   if (IsX64 || IsAArch64) {
3780     clang::CallingConv CC = CC_C;
3781     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3782       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3783     if (IsMSVAStart) {
3784       // Don't allow this in System V ABI functions.
3785       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3786         return S.Diag(Fn->getLocStart(),
3787                       diag::err_ms_va_start_used_in_sysv_function);
3788     } else {
3789       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3790       // On x64 Windows, don't allow this in System V ABI functions.
3791       // (Yes, that means there's no corresponding way to support variadic
3792       // System V ABI functions on Windows.)
3793       if ((IsWindows && CC == CC_X86_64SysV) ||
3794           (!IsWindows && CC == CC_Win64))
3795         return S.Diag(Fn->getLocStart(),
3796                       diag::err_va_start_used_in_wrong_abi_function)
3797                << !IsWindows;
3798     }
3799     return false;
3800   }
3801 
3802   if (IsMSVAStart)
3803     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3804   return false;
3805 }
3806 
3807 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3808                                              ParmVarDecl **LastParam = nullptr) {
3809   // Determine whether the current function, block, or obj-c method is variadic
3810   // and get its parameter list.
3811   bool IsVariadic = false;
3812   ArrayRef<ParmVarDecl *> Params;
3813   DeclContext *Caller = S.CurContext;
3814   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3815     IsVariadic = Block->isVariadic();
3816     Params = Block->parameters();
3817   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3818     IsVariadic = FD->isVariadic();
3819     Params = FD->parameters();
3820   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3821     IsVariadic = MD->isVariadic();
3822     // FIXME: This isn't correct for methods (results in bogus warning).
3823     Params = MD->parameters();
3824   } else if (isa<CapturedDecl>(Caller)) {
3825     // We don't support va_start in a CapturedDecl.
3826     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3827     return true;
3828   } else {
3829     // This must be some other declcontext that parses exprs.
3830     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3831     return true;
3832   }
3833 
3834   if (!IsVariadic) {
3835     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3836     return true;
3837   }
3838 
3839   if (LastParam)
3840     *LastParam = Params.empty() ? nullptr : Params.back();
3841 
3842   return false;
3843 }
3844 
3845 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3846 /// for validity.  Emit an error and return true on failure; return false
3847 /// on success.
3848 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3849   Expr *Fn = TheCall->getCallee();
3850 
3851   if (checkVAStartABI(*this, BuiltinID, Fn))
3852     return true;
3853 
3854   if (TheCall->getNumArgs() > 2) {
3855     Diag(TheCall->getArg(2)->getLocStart(),
3856          diag::err_typecheck_call_too_many_args)
3857       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3858       << Fn->getSourceRange()
3859       << SourceRange(TheCall->getArg(2)->getLocStart(),
3860                      (*(TheCall->arg_end()-1))->getLocEnd());
3861     return true;
3862   }
3863 
3864   if (TheCall->getNumArgs() < 2) {
3865     return Diag(TheCall->getLocEnd(),
3866       diag::err_typecheck_call_too_few_args_at_least)
3867       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3868   }
3869 
3870   // Type-check the first argument normally.
3871   if (checkBuiltinArgument(*this, TheCall, 0))
3872     return true;
3873 
3874   // Check that the current function is variadic, and get its last parameter.
3875   ParmVarDecl *LastParam;
3876   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3877     return true;
3878 
3879   // Verify that the second argument to the builtin is the last argument of the
3880   // current function or method.
3881   bool SecondArgIsLastNamedArgument = false;
3882   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3883 
3884   // These are valid if SecondArgIsLastNamedArgument is false after the next
3885   // block.
3886   QualType Type;
3887   SourceLocation ParamLoc;
3888   bool IsCRegister = false;
3889 
3890   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3891     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3892       SecondArgIsLastNamedArgument = PV == LastParam;
3893 
3894       Type = PV->getType();
3895       ParamLoc = PV->getLocation();
3896       IsCRegister =
3897           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3898     }
3899   }
3900 
3901   if (!SecondArgIsLastNamedArgument)
3902     Diag(TheCall->getArg(1)->getLocStart(),
3903          diag::warn_second_arg_of_va_start_not_last_named_param);
3904   else if (IsCRegister || Type->isReferenceType() ||
3905            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3906              // Promotable integers are UB, but enumerations need a bit of
3907              // extra checking to see what their promotable type actually is.
3908              if (!Type->isPromotableIntegerType())
3909                return false;
3910              if (!Type->isEnumeralType())
3911                return true;
3912              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3913              return !(ED &&
3914                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3915            }()) {
3916     unsigned Reason = 0;
3917     if (Type->isReferenceType())  Reason = 1;
3918     else if (IsCRegister)         Reason = 2;
3919     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3920     Diag(ParamLoc, diag::note_parameter_type) << Type;
3921   }
3922 
3923   TheCall->setType(Context.VoidTy);
3924   return false;
3925 }
3926 
3927 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
3928   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3929   //                 const char *named_addr);
3930 
3931   Expr *Func = Call->getCallee();
3932 
3933   if (Call->getNumArgs() < 3)
3934     return Diag(Call->getLocEnd(),
3935                 diag::err_typecheck_call_too_few_args_at_least)
3936            << 0 /*function call*/ << 3 << Call->getNumArgs();
3937 
3938   // Type-check the first argument normally.
3939   if (checkBuiltinArgument(*this, Call, 0))
3940     return true;
3941 
3942   // Check that the current function is variadic.
3943   if (checkVAStartIsInVariadicFunction(*this, Func))
3944     return true;
3945 
3946   const struct {
3947     unsigned ArgNo;
3948     QualType Type;
3949   } ArgumentTypes[] = {
3950     { 1, Context.getPointerType(Context.CharTy.withConst()) },
3951     { 2, Context.getSizeType() },
3952   };
3953 
3954   for (const auto &AT : ArgumentTypes) {
3955     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
3956     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
3957       continue;
3958     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
3959       << Arg->getType() << AT.Type << 1 /* different class */
3960       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
3961       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
3962   }
3963 
3964   return false;
3965 }
3966 
3967 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3968 /// friends.  This is declared to take (...), so we have to check everything.
3969 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3970   if (TheCall->getNumArgs() < 2)
3971     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3972       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3973   if (TheCall->getNumArgs() > 2)
3974     return Diag(TheCall->getArg(2)->getLocStart(),
3975                 diag::err_typecheck_call_too_many_args)
3976       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3977       << SourceRange(TheCall->getArg(2)->getLocStart(),
3978                      (*(TheCall->arg_end()-1))->getLocEnd());
3979 
3980   ExprResult OrigArg0 = TheCall->getArg(0);
3981   ExprResult OrigArg1 = TheCall->getArg(1);
3982 
3983   // Do standard promotions between the two arguments, returning their common
3984   // type.
3985   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3986   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3987     return true;
3988 
3989   // Make sure any conversions are pushed back into the call; this is
3990   // type safe since unordered compare builtins are declared as "_Bool
3991   // foo(...)".
3992   TheCall->setArg(0, OrigArg0.get());
3993   TheCall->setArg(1, OrigArg1.get());
3994 
3995   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
3996     return false;
3997 
3998   // If the common type isn't a real floating type, then the arguments were
3999   // invalid for this operation.
4000   if (Res.isNull() || !Res->isRealFloatingType())
4001     return Diag(OrigArg0.get()->getLocStart(),
4002                 diag::err_typecheck_call_invalid_ordered_compare)
4003       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4004       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4005 
4006   return false;
4007 }
4008 
4009 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4010 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4011 /// to check everything. We expect the last argument to be a floating point
4012 /// value.
4013 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4014   if (TheCall->getNumArgs() < NumArgs)
4015     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4016       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4017   if (TheCall->getNumArgs() > NumArgs)
4018     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4019                 diag::err_typecheck_call_too_many_args)
4020       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4021       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4022                      (*(TheCall->arg_end()-1))->getLocEnd());
4023 
4024   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4025 
4026   if (OrigArg->isTypeDependent())
4027     return false;
4028 
4029   // This operation requires a non-_Complex floating-point number.
4030   if (!OrigArg->getType()->isRealFloatingType())
4031     return Diag(OrigArg->getLocStart(),
4032                 diag::err_typecheck_call_invalid_unary_fp)
4033       << OrigArg->getType() << OrigArg->getSourceRange();
4034 
4035   // If this is an implicit conversion from float -> float or double, remove it.
4036   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4037     // Only remove standard FloatCasts, leaving other casts inplace
4038     if (Cast->getCastKind() == CK_FloatingCast) {
4039       Expr *CastArg = Cast->getSubExpr();
4040       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4041           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4042                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4043                "promotion from float to either float or double is the only expected cast here");
4044         Cast->setSubExpr(nullptr);
4045         TheCall->setArg(NumArgs-1, CastArg);
4046       }
4047     }
4048   }
4049 
4050   return false;
4051 }
4052 
4053 // Customized Sema Checking for VSX builtins that have the following signature:
4054 // vector [...] builtinName(vector [...], vector [...], const int);
4055 // Which takes the same type of vectors (any legal vector type) for the first
4056 // two arguments and takes compile time constant for the third argument.
4057 // Example builtins are :
4058 // vector double vec_xxpermdi(vector double, vector double, int);
4059 // vector short vec_xxsldwi(vector short, vector short, int);
4060 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4061   unsigned ExpectedNumArgs = 3;
4062   if (TheCall->getNumArgs() < ExpectedNumArgs)
4063     return Diag(TheCall->getLocEnd(),
4064                 diag::err_typecheck_call_too_few_args_at_least)
4065            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4066            << TheCall->getSourceRange();
4067 
4068   if (TheCall->getNumArgs() > ExpectedNumArgs)
4069     return Diag(TheCall->getLocEnd(),
4070                 diag::err_typecheck_call_too_many_args_at_most)
4071            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4072            << TheCall->getSourceRange();
4073 
4074   // Check the third argument is a compile time constant
4075   llvm::APSInt Value;
4076   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4077     return Diag(TheCall->getLocStart(),
4078                 diag::err_vsx_builtin_nonconstant_argument)
4079            << 3 /* argument index */ << TheCall->getDirectCallee()
4080            << SourceRange(TheCall->getArg(2)->getLocStart(),
4081                           TheCall->getArg(2)->getLocEnd());
4082 
4083   QualType Arg1Ty = TheCall->getArg(0)->getType();
4084   QualType Arg2Ty = TheCall->getArg(1)->getType();
4085 
4086   // Check the type of argument 1 and argument 2 are vectors.
4087   SourceLocation BuiltinLoc = TheCall->getLocStart();
4088   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4089       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4090     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4091            << TheCall->getDirectCallee()
4092            << SourceRange(TheCall->getArg(0)->getLocStart(),
4093                           TheCall->getArg(1)->getLocEnd());
4094   }
4095 
4096   // Check the first two arguments are the same type.
4097   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4098     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4099            << TheCall->getDirectCallee()
4100            << SourceRange(TheCall->getArg(0)->getLocStart(),
4101                           TheCall->getArg(1)->getLocEnd());
4102   }
4103 
4104   // When default clang type checking is turned off and the customized type
4105   // checking is used, the returning type of the function must be explicitly
4106   // set. Otherwise it is _Bool by default.
4107   TheCall->setType(Arg1Ty);
4108 
4109   return false;
4110 }
4111 
4112 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4113 // This is declared to take (...), so we have to check everything.
4114 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4115   if (TheCall->getNumArgs() < 2)
4116     return ExprError(Diag(TheCall->getLocEnd(),
4117                           diag::err_typecheck_call_too_few_args_at_least)
4118                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4119                      << TheCall->getSourceRange());
4120 
4121   // Determine which of the following types of shufflevector we're checking:
4122   // 1) unary, vector mask: (lhs, mask)
4123   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4124   QualType resType = TheCall->getArg(0)->getType();
4125   unsigned numElements = 0;
4126 
4127   if (!TheCall->getArg(0)->isTypeDependent() &&
4128       !TheCall->getArg(1)->isTypeDependent()) {
4129     QualType LHSType = TheCall->getArg(0)->getType();
4130     QualType RHSType = TheCall->getArg(1)->getType();
4131 
4132     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4133       return ExprError(Diag(TheCall->getLocStart(),
4134                             diag::err_vec_builtin_non_vector)
4135                        << TheCall->getDirectCallee()
4136                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4137                                       TheCall->getArg(1)->getLocEnd()));
4138 
4139     numElements = LHSType->getAs<VectorType>()->getNumElements();
4140     unsigned numResElements = TheCall->getNumArgs() - 2;
4141 
4142     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4143     // with mask.  If so, verify that RHS is an integer vector type with the
4144     // same number of elts as lhs.
4145     if (TheCall->getNumArgs() == 2) {
4146       if (!RHSType->hasIntegerRepresentation() ||
4147           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4148         return ExprError(Diag(TheCall->getLocStart(),
4149                               diag::err_vec_builtin_incompatible_vector)
4150                          << TheCall->getDirectCallee()
4151                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4152                                         TheCall->getArg(1)->getLocEnd()));
4153     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4154       return ExprError(Diag(TheCall->getLocStart(),
4155                             diag::err_vec_builtin_incompatible_vector)
4156                        << TheCall->getDirectCallee()
4157                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4158                                       TheCall->getArg(1)->getLocEnd()));
4159     } else if (numElements != numResElements) {
4160       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4161       resType = Context.getVectorType(eltType, numResElements,
4162                                       VectorType::GenericVector);
4163     }
4164   }
4165 
4166   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4167     if (TheCall->getArg(i)->isTypeDependent() ||
4168         TheCall->getArg(i)->isValueDependent())
4169       continue;
4170 
4171     llvm::APSInt Result(32);
4172     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4173       return ExprError(Diag(TheCall->getLocStart(),
4174                             diag::err_shufflevector_nonconstant_argument)
4175                        << TheCall->getArg(i)->getSourceRange());
4176 
4177     // Allow -1 which will be translated to undef in the IR.
4178     if (Result.isSigned() && Result.isAllOnesValue())
4179       continue;
4180 
4181     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4182       return ExprError(Diag(TheCall->getLocStart(),
4183                             diag::err_shufflevector_argument_too_large)
4184                        << TheCall->getArg(i)->getSourceRange());
4185   }
4186 
4187   SmallVector<Expr*, 32> exprs;
4188 
4189   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4190     exprs.push_back(TheCall->getArg(i));
4191     TheCall->setArg(i, nullptr);
4192   }
4193 
4194   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4195                                          TheCall->getCallee()->getLocStart(),
4196                                          TheCall->getRParenLoc());
4197 }
4198 
4199 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4200 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4201                                        SourceLocation BuiltinLoc,
4202                                        SourceLocation RParenLoc) {
4203   ExprValueKind VK = VK_RValue;
4204   ExprObjectKind OK = OK_Ordinary;
4205   QualType DstTy = TInfo->getType();
4206   QualType SrcTy = E->getType();
4207 
4208   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4209     return ExprError(Diag(BuiltinLoc,
4210                           diag::err_convertvector_non_vector)
4211                      << E->getSourceRange());
4212   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4213     return ExprError(Diag(BuiltinLoc,
4214                           diag::err_convertvector_non_vector_type));
4215 
4216   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4217     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4218     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4219     if (SrcElts != DstElts)
4220       return ExprError(Diag(BuiltinLoc,
4221                             diag::err_convertvector_incompatible_vector)
4222                        << E->getSourceRange());
4223   }
4224 
4225   return new (Context)
4226       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4227 }
4228 
4229 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4230 // This is declared to take (const void*, ...) and can take two
4231 // optional constant int args.
4232 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4233   unsigned NumArgs = TheCall->getNumArgs();
4234 
4235   if (NumArgs > 3)
4236     return Diag(TheCall->getLocEnd(),
4237              diag::err_typecheck_call_too_many_args_at_most)
4238              << 0 /*function call*/ << 3 << NumArgs
4239              << TheCall->getSourceRange();
4240 
4241   // Argument 0 is checked for us and the remaining arguments must be
4242   // constant integers.
4243   for (unsigned i = 1; i != NumArgs; ++i)
4244     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4245       return true;
4246 
4247   return false;
4248 }
4249 
4250 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4251 // __assume does not evaluate its arguments, and should warn if its argument
4252 // has side effects.
4253 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4254   Expr *Arg = TheCall->getArg(0);
4255   if (Arg->isInstantiationDependent()) return false;
4256 
4257   if (Arg->HasSideEffects(Context))
4258     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4259       << Arg->getSourceRange()
4260       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4261 
4262   return false;
4263 }
4264 
4265 /// Handle __builtin_alloca_with_align. This is declared
4266 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4267 /// than 8.
4268 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4269   // The alignment must be a constant integer.
4270   Expr *Arg = TheCall->getArg(1);
4271 
4272   // We can't check the value of a dependent argument.
4273   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4274     if (const auto *UE =
4275             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4276       if (UE->getKind() == UETT_AlignOf)
4277         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4278           << Arg->getSourceRange();
4279 
4280     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4281 
4282     if (!Result.isPowerOf2())
4283       return Diag(TheCall->getLocStart(),
4284                   diag::err_alignment_not_power_of_two)
4285            << Arg->getSourceRange();
4286 
4287     if (Result < Context.getCharWidth())
4288       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4289            << (unsigned)Context.getCharWidth()
4290            << Arg->getSourceRange();
4291 
4292     if (Result > INT32_MAX)
4293       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4294            << INT32_MAX
4295            << Arg->getSourceRange();
4296   }
4297 
4298   return false;
4299 }
4300 
4301 /// Handle __builtin_assume_aligned. This is declared
4302 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4303 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4304   unsigned NumArgs = TheCall->getNumArgs();
4305 
4306   if (NumArgs > 3)
4307     return Diag(TheCall->getLocEnd(),
4308              diag::err_typecheck_call_too_many_args_at_most)
4309              << 0 /*function call*/ << 3 << NumArgs
4310              << TheCall->getSourceRange();
4311 
4312   // The alignment must be a constant integer.
4313   Expr *Arg = TheCall->getArg(1);
4314 
4315   // We can't check the value of a dependent argument.
4316   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4317     llvm::APSInt Result;
4318     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4319       return true;
4320 
4321     if (!Result.isPowerOf2())
4322       return Diag(TheCall->getLocStart(),
4323                   diag::err_alignment_not_power_of_two)
4324            << Arg->getSourceRange();
4325   }
4326 
4327   if (NumArgs > 2) {
4328     ExprResult Arg(TheCall->getArg(2));
4329     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4330       Context.getSizeType(), false);
4331     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4332     if (Arg.isInvalid()) return true;
4333     TheCall->setArg(2, Arg.get());
4334   }
4335 
4336   return false;
4337 }
4338 
4339 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4340   unsigned BuiltinID =
4341       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4342   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4343 
4344   unsigned NumArgs = TheCall->getNumArgs();
4345   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4346   if (NumArgs < NumRequiredArgs) {
4347     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4348            << 0 /* function call */ << NumRequiredArgs << NumArgs
4349            << TheCall->getSourceRange();
4350   }
4351   if (NumArgs >= NumRequiredArgs + 0x100) {
4352     return Diag(TheCall->getLocEnd(),
4353                 diag::err_typecheck_call_too_many_args_at_most)
4354            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4355            << TheCall->getSourceRange();
4356   }
4357   unsigned i = 0;
4358 
4359   // For formatting call, check buffer arg.
4360   if (!IsSizeCall) {
4361     ExprResult Arg(TheCall->getArg(i));
4362     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4363         Context, Context.VoidPtrTy, false);
4364     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4365     if (Arg.isInvalid())
4366       return true;
4367     TheCall->setArg(i, Arg.get());
4368     i++;
4369   }
4370 
4371   // Check string literal arg.
4372   unsigned FormatIdx = i;
4373   {
4374     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4375     if (Arg.isInvalid())
4376       return true;
4377     TheCall->setArg(i, Arg.get());
4378     i++;
4379   }
4380 
4381   // Make sure variadic args are scalar.
4382   unsigned FirstDataArg = i;
4383   while (i < NumArgs) {
4384     ExprResult Arg = DefaultVariadicArgumentPromotion(
4385         TheCall->getArg(i), VariadicFunction, nullptr);
4386     if (Arg.isInvalid())
4387       return true;
4388     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4389     if (ArgSize.getQuantity() >= 0x100) {
4390       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4391              << i << (int)ArgSize.getQuantity() << 0xff
4392              << TheCall->getSourceRange();
4393     }
4394     TheCall->setArg(i, Arg.get());
4395     i++;
4396   }
4397 
4398   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4399   // call to avoid duplicate diagnostics.
4400   if (!IsSizeCall) {
4401     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4402     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4403     bool Success = CheckFormatArguments(
4404         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4405         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4406         CheckedVarArgs);
4407     if (!Success)
4408       return true;
4409   }
4410 
4411   if (IsSizeCall) {
4412     TheCall->setType(Context.getSizeType());
4413   } else {
4414     TheCall->setType(Context.VoidPtrTy);
4415   }
4416   return false;
4417 }
4418 
4419 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4420 /// TheCall is a constant expression.
4421 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4422                                   llvm::APSInt &Result) {
4423   Expr *Arg = TheCall->getArg(ArgNum);
4424   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4425   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4426 
4427   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4428 
4429   if (!Arg->isIntegerConstantExpr(Result, Context))
4430     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4431                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4432 
4433   return false;
4434 }
4435 
4436 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4437 /// TheCall is a constant expression in the range [Low, High].
4438 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4439                                        int Low, int High) {
4440   llvm::APSInt Result;
4441 
4442   // We can't check the value of a dependent argument.
4443   Expr *Arg = TheCall->getArg(ArgNum);
4444   if (Arg->isTypeDependent() || Arg->isValueDependent())
4445     return false;
4446 
4447   // Check constant-ness first.
4448   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4449     return true;
4450 
4451   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4452     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4453       << Low << High << Arg->getSourceRange();
4454 
4455   return false;
4456 }
4457 
4458 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4459 /// TheCall is a constant expression is a multiple of Num..
4460 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4461                                           unsigned Num) {
4462   llvm::APSInt Result;
4463 
4464   // We can't check the value of a dependent argument.
4465   Expr *Arg = TheCall->getArg(ArgNum);
4466   if (Arg->isTypeDependent() || Arg->isValueDependent())
4467     return false;
4468 
4469   // Check constant-ness first.
4470   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4471     return true;
4472 
4473   if (Result.getSExtValue() % Num != 0)
4474     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4475       << Num << Arg->getSourceRange();
4476 
4477   return false;
4478 }
4479 
4480 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4481 /// TheCall is an ARM/AArch64 special register string literal.
4482 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4483                                     int ArgNum, unsigned ExpectedFieldNum,
4484                                     bool AllowName) {
4485   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4486                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4487                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4488                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4489                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4490                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4491   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4492                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4493                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4494                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4495                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4496                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4497   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4498 
4499   // We can't check the value of a dependent argument.
4500   Expr *Arg = TheCall->getArg(ArgNum);
4501   if (Arg->isTypeDependent() || Arg->isValueDependent())
4502     return false;
4503 
4504   // Check if the argument is a string literal.
4505   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4506     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4507            << Arg->getSourceRange();
4508 
4509   // Check the type of special register given.
4510   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4511   SmallVector<StringRef, 6> Fields;
4512   Reg.split(Fields, ":");
4513 
4514   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4515     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4516            << Arg->getSourceRange();
4517 
4518   // If the string is the name of a register then we cannot check that it is
4519   // valid here but if the string is of one the forms described in ACLE then we
4520   // can check that the supplied fields are integers and within the valid
4521   // ranges.
4522   if (Fields.size() > 1) {
4523     bool FiveFields = Fields.size() == 5;
4524 
4525     bool ValidString = true;
4526     if (IsARMBuiltin) {
4527       ValidString &= Fields[0].startswith_lower("cp") ||
4528                      Fields[0].startswith_lower("p");
4529       if (ValidString)
4530         Fields[0] =
4531           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4532 
4533       ValidString &= Fields[2].startswith_lower("c");
4534       if (ValidString)
4535         Fields[2] = Fields[2].drop_front(1);
4536 
4537       if (FiveFields) {
4538         ValidString &= Fields[3].startswith_lower("c");
4539         if (ValidString)
4540           Fields[3] = Fields[3].drop_front(1);
4541       }
4542     }
4543 
4544     SmallVector<int, 5> Ranges;
4545     if (FiveFields)
4546       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4547     else
4548       Ranges.append({15, 7, 15});
4549 
4550     for (unsigned i=0; i<Fields.size(); ++i) {
4551       int IntField;
4552       ValidString &= !Fields[i].getAsInteger(10, IntField);
4553       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4554     }
4555 
4556     if (!ValidString)
4557       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4558              << Arg->getSourceRange();
4559 
4560   } else if (IsAArch64Builtin && Fields.size() == 1) {
4561     // If the register name is one of those that appear in the condition below
4562     // and the special register builtin being used is one of the write builtins,
4563     // then we require that the argument provided for writing to the register
4564     // is an integer constant expression. This is because it will be lowered to
4565     // an MSR (immediate) instruction, so we need to know the immediate at
4566     // compile time.
4567     if (TheCall->getNumArgs() != 2)
4568       return false;
4569 
4570     std::string RegLower = Reg.lower();
4571     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4572         RegLower != "pan" && RegLower != "uao")
4573       return false;
4574 
4575     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4576   }
4577 
4578   return false;
4579 }
4580 
4581 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4582 /// This checks that the target supports __builtin_longjmp and
4583 /// that val is a constant 1.
4584 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4585   if (!Context.getTargetInfo().hasSjLjLowering())
4586     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4587              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4588 
4589   Expr *Arg = TheCall->getArg(1);
4590   llvm::APSInt Result;
4591 
4592   // TODO: This is less than ideal. Overload this to take a value.
4593   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4594     return true;
4595 
4596   if (Result != 1)
4597     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4598              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4599 
4600   return false;
4601 }
4602 
4603 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4604 /// This checks that the target supports __builtin_setjmp.
4605 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4606   if (!Context.getTargetInfo().hasSjLjLowering())
4607     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4608              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4609   return false;
4610 }
4611 
4612 namespace {
4613 class UncoveredArgHandler {
4614   enum { Unknown = -1, AllCovered = -2 };
4615   signed FirstUncoveredArg;
4616   SmallVector<const Expr *, 4> DiagnosticExprs;
4617 
4618 public:
4619   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4620 
4621   bool hasUncoveredArg() const {
4622     return (FirstUncoveredArg >= 0);
4623   }
4624 
4625   unsigned getUncoveredArg() const {
4626     assert(hasUncoveredArg() && "no uncovered argument");
4627     return FirstUncoveredArg;
4628   }
4629 
4630   void setAllCovered() {
4631     // A string has been found with all arguments covered, so clear out
4632     // the diagnostics.
4633     DiagnosticExprs.clear();
4634     FirstUncoveredArg = AllCovered;
4635   }
4636 
4637   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4638     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4639 
4640     // Don't update if a previous string covers all arguments.
4641     if (FirstUncoveredArg == AllCovered)
4642       return;
4643 
4644     // UncoveredArgHandler tracks the highest uncovered argument index
4645     // and with it all the strings that match this index.
4646     if (NewFirstUncoveredArg == FirstUncoveredArg)
4647       DiagnosticExprs.push_back(StrExpr);
4648     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4649       DiagnosticExprs.clear();
4650       DiagnosticExprs.push_back(StrExpr);
4651       FirstUncoveredArg = NewFirstUncoveredArg;
4652     }
4653   }
4654 
4655   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4656 };
4657 
4658 enum StringLiteralCheckType {
4659   SLCT_NotALiteral,
4660   SLCT_UncheckedLiteral,
4661   SLCT_CheckedLiteral
4662 };
4663 } // end anonymous namespace
4664 
4665 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4666                                      BinaryOperatorKind BinOpKind,
4667                                      bool AddendIsRight) {
4668   unsigned BitWidth = Offset.getBitWidth();
4669   unsigned AddendBitWidth = Addend.getBitWidth();
4670   // There might be negative interim results.
4671   if (Addend.isUnsigned()) {
4672     Addend = Addend.zext(++AddendBitWidth);
4673     Addend.setIsSigned(true);
4674   }
4675   // Adjust the bit width of the APSInts.
4676   if (AddendBitWidth > BitWidth) {
4677     Offset = Offset.sext(AddendBitWidth);
4678     BitWidth = AddendBitWidth;
4679   } else if (BitWidth > AddendBitWidth) {
4680     Addend = Addend.sext(BitWidth);
4681   }
4682 
4683   bool Ov = false;
4684   llvm::APSInt ResOffset = Offset;
4685   if (BinOpKind == BO_Add)
4686     ResOffset = Offset.sadd_ov(Addend, Ov);
4687   else {
4688     assert(AddendIsRight && BinOpKind == BO_Sub &&
4689            "operator must be add or sub with addend on the right");
4690     ResOffset = Offset.ssub_ov(Addend, Ov);
4691   }
4692 
4693   // We add an offset to a pointer here so we should support an offset as big as
4694   // possible.
4695   if (Ov) {
4696     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4697     Offset = Offset.sext(2 * BitWidth);
4698     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4699     return;
4700   }
4701 
4702   Offset = ResOffset;
4703 }
4704 
4705 namespace {
4706 // This is a wrapper class around StringLiteral to support offsetted string
4707 // literals as format strings. It takes the offset into account when returning
4708 // the string and its length or the source locations to display notes correctly.
4709 class FormatStringLiteral {
4710   const StringLiteral *FExpr;
4711   int64_t Offset;
4712 
4713  public:
4714   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4715       : FExpr(fexpr), Offset(Offset) {}
4716 
4717   StringRef getString() const {
4718     return FExpr->getString().drop_front(Offset);
4719   }
4720 
4721   unsigned getByteLength() const {
4722     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4723   }
4724   unsigned getLength() const { return FExpr->getLength() - Offset; }
4725   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4726 
4727   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4728 
4729   QualType getType() const { return FExpr->getType(); }
4730 
4731   bool isAscii() const { return FExpr->isAscii(); }
4732   bool isWide() const { return FExpr->isWide(); }
4733   bool isUTF8() const { return FExpr->isUTF8(); }
4734   bool isUTF16() const { return FExpr->isUTF16(); }
4735   bool isUTF32() const { return FExpr->isUTF32(); }
4736   bool isPascal() const { return FExpr->isPascal(); }
4737 
4738   SourceLocation getLocationOfByte(
4739       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4740       const TargetInfo &Target, unsigned *StartToken = nullptr,
4741       unsigned *StartTokenByteOffset = nullptr) const {
4742     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4743                                     StartToken, StartTokenByteOffset);
4744   }
4745 
4746   SourceLocation getLocStart() const LLVM_READONLY {
4747     return FExpr->getLocStart().getLocWithOffset(Offset);
4748   }
4749   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4750 };
4751 }  // end anonymous namespace
4752 
4753 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4754                               const Expr *OrigFormatExpr,
4755                               ArrayRef<const Expr *> Args,
4756                               bool HasVAListArg, unsigned format_idx,
4757                               unsigned firstDataArg,
4758                               Sema::FormatStringType Type,
4759                               bool inFunctionCall,
4760                               Sema::VariadicCallType CallType,
4761                               llvm::SmallBitVector &CheckedVarArgs,
4762                               UncoveredArgHandler &UncoveredArg);
4763 
4764 // Determine if an expression is a string literal or constant string.
4765 // If this function returns false on the arguments to a function expecting a
4766 // format string, we will usually need to emit a warning.
4767 // True string literals are then checked by CheckFormatString.
4768 static StringLiteralCheckType
4769 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4770                       bool HasVAListArg, unsigned format_idx,
4771                       unsigned firstDataArg, Sema::FormatStringType Type,
4772                       Sema::VariadicCallType CallType, bool InFunctionCall,
4773                       llvm::SmallBitVector &CheckedVarArgs,
4774                       UncoveredArgHandler &UncoveredArg,
4775                       llvm::APSInt Offset) {
4776  tryAgain:
4777   assert(Offset.isSigned() && "invalid offset");
4778 
4779   if (E->isTypeDependent() || E->isValueDependent())
4780     return SLCT_NotALiteral;
4781 
4782   E = E->IgnoreParenCasts();
4783 
4784   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4785     // Technically -Wformat-nonliteral does not warn about this case.
4786     // The behavior of printf and friends in this case is implementation
4787     // dependent.  Ideally if the format string cannot be null then
4788     // it should have a 'nonnull' attribute in the function prototype.
4789     return SLCT_UncheckedLiteral;
4790 
4791   switch (E->getStmtClass()) {
4792   case Stmt::BinaryConditionalOperatorClass:
4793   case Stmt::ConditionalOperatorClass: {
4794     // The expression is a literal if both sub-expressions were, and it was
4795     // completely checked only if both sub-expressions were checked.
4796     const AbstractConditionalOperator *C =
4797         cast<AbstractConditionalOperator>(E);
4798 
4799     // Determine whether it is necessary to check both sub-expressions, for
4800     // example, because the condition expression is a constant that can be
4801     // evaluated at compile time.
4802     bool CheckLeft = true, CheckRight = true;
4803 
4804     bool Cond;
4805     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4806       if (Cond)
4807         CheckRight = false;
4808       else
4809         CheckLeft = false;
4810     }
4811 
4812     // We need to maintain the offsets for the right and the left hand side
4813     // separately to check if every possible indexed expression is a valid
4814     // string literal. They might have different offsets for different string
4815     // literals in the end.
4816     StringLiteralCheckType Left;
4817     if (!CheckLeft)
4818       Left = SLCT_UncheckedLiteral;
4819     else {
4820       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4821                                    HasVAListArg, format_idx, firstDataArg,
4822                                    Type, CallType, InFunctionCall,
4823                                    CheckedVarArgs, UncoveredArg, Offset);
4824       if (Left == SLCT_NotALiteral || !CheckRight) {
4825         return Left;
4826       }
4827     }
4828 
4829     StringLiteralCheckType Right =
4830         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4831                               HasVAListArg, format_idx, firstDataArg,
4832                               Type, CallType, InFunctionCall, CheckedVarArgs,
4833                               UncoveredArg, Offset);
4834 
4835     return (CheckLeft && Left < Right) ? Left : Right;
4836   }
4837 
4838   case Stmt::ImplicitCastExprClass: {
4839     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4840     goto tryAgain;
4841   }
4842 
4843   case Stmt::OpaqueValueExprClass:
4844     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4845       E = src;
4846       goto tryAgain;
4847     }
4848     return SLCT_NotALiteral;
4849 
4850   case Stmt::PredefinedExprClass:
4851     // While __func__, etc., are technically not string literals, they
4852     // cannot contain format specifiers and thus are not a security
4853     // liability.
4854     return SLCT_UncheckedLiteral;
4855 
4856   case Stmt::DeclRefExprClass: {
4857     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4858 
4859     // As an exception, do not flag errors for variables binding to
4860     // const string literals.
4861     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4862       bool isConstant = false;
4863       QualType T = DR->getType();
4864 
4865       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4866         isConstant = AT->getElementType().isConstant(S.Context);
4867       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4868         isConstant = T.isConstant(S.Context) &&
4869                      PT->getPointeeType().isConstant(S.Context);
4870       } else if (T->isObjCObjectPointerType()) {
4871         // In ObjC, there is usually no "const ObjectPointer" type,
4872         // so don't check if the pointee type is constant.
4873         isConstant = T.isConstant(S.Context);
4874       }
4875 
4876       if (isConstant) {
4877         if (const Expr *Init = VD->getAnyInitializer()) {
4878           // Look through initializers like const char c[] = { "foo" }
4879           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4880             if (InitList->isStringLiteralInit())
4881               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4882           }
4883           return checkFormatStringExpr(S, Init, Args,
4884                                        HasVAListArg, format_idx,
4885                                        firstDataArg, Type, CallType,
4886                                        /*InFunctionCall*/ false, CheckedVarArgs,
4887                                        UncoveredArg, Offset);
4888         }
4889       }
4890 
4891       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4892       // special check to see if the format string is a function parameter
4893       // of the function calling the printf function.  If the function
4894       // has an attribute indicating it is a printf-like function, then we
4895       // should suppress warnings concerning non-literals being used in a call
4896       // to a vprintf function.  For example:
4897       //
4898       // void
4899       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4900       //      va_list ap;
4901       //      va_start(ap, fmt);
4902       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4903       //      ...
4904       // }
4905       if (HasVAListArg) {
4906         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4907           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4908             int PVIndex = PV->getFunctionScopeIndex() + 1;
4909             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4910               // adjust for implicit parameter
4911               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4912                 if (MD->isInstance())
4913                   ++PVIndex;
4914               // We also check if the formats are compatible.
4915               // We can't pass a 'scanf' string to a 'printf' function.
4916               if (PVIndex == PVFormat->getFormatIdx() &&
4917                   Type == S.GetFormatStringType(PVFormat))
4918                 return SLCT_UncheckedLiteral;
4919             }
4920           }
4921         }
4922       }
4923     }
4924 
4925     return SLCT_NotALiteral;
4926   }
4927 
4928   case Stmt::CallExprClass:
4929   case Stmt::CXXMemberCallExprClass: {
4930     const CallExpr *CE = cast<CallExpr>(E);
4931     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4932       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4933         unsigned ArgIndex = FA->getFormatIdx();
4934         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4935           if (MD->isInstance())
4936             --ArgIndex;
4937         const Expr *Arg = CE->getArg(ArgIndex - 1);
4938 
4939         return checkFormatStringExpr(S, Arg, Args,
4940                                      HasVAListArg, format_idx, firstDataArg,
4941                                      Type, CallType, InFunctionCall,
4942                                      CheckedVarArgs, UncoveredArg, Offset);
4943       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4944         unsigned BuiltinID = FD->getBuiltinID();
4945         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4946             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4947           const Expr *Arg = CE->getArg(0);
4948           return checkFormatStringExpr(S, Arg, Args,
4949                                        HasVAListArg, format_idx,
4950                                        firstDataArg, Type, CallType,
4951                                        InFunctionCall, CheckedVarArgs,
4952                                        UncoveredArg, Offset);
4953         }
4954       }
4955     }
4956 
4957     return SLCT_NotALiteral;
4958   }
4959   case Stmt::ObjCMessageExprClass: {
4960     const auto *ME = cast<ObjCMessageExpr>(E);
4961     if (const auto *ND = ME->getMethodDecl()) {
4962       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4963         unsigned ArgIndex = FA->getFormatIdx();
4964         const Expr *Arg = ME->getArg(ArgIndex - 1);
4965         return checkFormatStringExpr(
4966             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4967             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4968       }
4969     }
4970 
4971     return SLCT_NotALiteral;
4972   }
4973   case Stmt::ObjCStringLiteralClass:
4974   case Stmt::StringLiteralClass: {
4975     const StringLiteral *StrE = nullptr;
4976 
4977     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4978       StrE = ObjCFExpr->getString();
4979     else
4980       StrE = cast<StringLiteral>(E);
4981 
4982     if (StrE) {
4983       if (Offset.isNegative() || Offset > StrE->getLength()) {
4984         // TODO: It would be better to have an explicit warning for out of
4985         // bounds literals.
4986         return SLCT_NotALiteral;
4987       }
4988       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4989       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
4990                         firstDataArg, Type, InFunctionCall, CallType,
4991                         CheckedVarArgs, UncoveredArg);
4992       return SLCT_CheckedLiteral;
4993     }
4994 
4995     return SLCT_NotALiteral;
4996   }
4997   case Stmt::BinaryOperatorClass: {
4998     llvm::APSInt LResult;
4999     llvm::APSInt RResult;
5000 
5001     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5002 
5003     // A string literal + an int offset is still a string literal.
5004     if (BinOp->isAdditiveOp()) {
5005       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5006       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5007 
5008       if (LIsInt != RIsInt) {
5009         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5010 
5011         if (LIsInt) {
5012           if (BinOpKind == BO_Add) {
5013             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5014             E = BinOp->getRHS();
5015             goto tryAgain;
5016           }
5017         } else {
5018           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5019           E = BinOp->getLHS();
5020           goto tryAgain;
5021         }
5022       }
5023     }
5024 
5025     return SLCT_NotALiteral;
5026   }
5027   case Stmt::UnaryOperatorClass: {
5028     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5029     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5030     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5031       llvm::APSInt IndexResult;
5032       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5033         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5034         E = ASE->getBase();
5035         goto tryAgain;
5036       }
5037     }
5038 
5039     return SLCT_NotALiteral;
5040   }
5041 
5042   default:
5043     return SLCT_NotALiteral;
5044   }
5045 }
5046 
5047 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5048   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5049       .Case("scanf", FST_Scanf)
5050       .Cases("printf", "printf0", FST_Printf)
5051       .Cases("NSString", "CFString", FST_NSString)
5052       .Case("strftime", FST_Strftime)
5053       .Case("strfmon", FST_Strfmon)
5054       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5055       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5056       .Case("os_trace", FST_OSLog)
5057       .Case("os_log", FST_OSLog)
5058       .Default(FST_Unknown);
5059 }
5060 
5061 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5062 /// functions) for correct use of format strings.
5063 /// Returns true if a format string has been fully checked.
5064 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5065                                 ArrayRef<const Expr *> Args,
5066                                 bool IsCXXMember,
5067                                 VariadicCallType CallType,
5068                                 SourceLocation Loc, SourceRange Range,
5069                                 llvm::SmallBitVector &CheckedVarArgs) {
5070   FormatStringInfo FSI;
5071   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5072     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5073                                 FSI.FirstDataArg, GetFormatStringType(Format),
5074                                 CallType, Loc, Range, CheckedVarArgs);
5075   return false;
5076 }
5077 
5078 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5079                                 bool HasVAListArg, unsigned format_idx,
5080                                 unsigned firstDataArg, FormatStringType Type,
5081                                 VariadicCallType CallType,
5082                                 SourceLocation Loc, SourceRange Range,
5083                                 llvm::SmallBitVector &CheckedVarArgs) {
5084   // CHECK: printf/scanf-like function is called with no format string.
5085   if (format_idx >= Args.size()) {
5086     Diag(Loc, diag::warn_missing_format_string) << Range;
5087     return false;
5088   }
5089 
5090   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5091 
5092   // CHECK: format string is not a string literal.
5093   //
5094   // Dynamically generated format strings are difficult to
5095   // automatically vet at compile time.  Requiring that format strings
5096   // are string literals: (1) permits the checking of format strings by
5097   // the compiler and thereby (2) can practically remove the source of
5098   // many format string exploits.
5099 
5100   // Format string can be either ObjC string (e.g. @"%d") or
5101   // C string (e.g. "%d")
5102   // ObjC string uses the same format specifiers as C string, so we can use
5103   // the same format string checking logic for both ObjC and C strings.
5104   UncoveredArgHandler UncoveredArg;
5105   StringLiteralCheckType CT =
5106       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5107                             format_idx, firstDataArg, Type, CallType,
5108                             /*IsFunctionCall*/ true, CheckedVarArgs,
5109                             UncoveredArg,
5110                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5111 
5112   // Generate a diagnostic where an uncovered argument is detected.
5113   if (UncoveredArg.hasUncoveredArg()) {
5114     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5115     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5116     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5117   }
5118 
5119   if (CT != SLCT_NotALiteral)
5120     // Literal format string found, check done!
5121     return CT == SLCT_CheckedLiteral;
5122 
5123   // Strftime is particular as it always uses a single 'time' argument,
5124   // so it is safe to pass a non-literal string.
5125   if (Type == FST_Strftime)
5126     return false;
5127 
5128   // Do not emit diag when the string param is a macro expansion and the
5129   // format is either NSString or CFString. This is a hack to prevent
5130   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5131   // which are usually used in place of NS and CF string literals.
5132   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5133   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5134     return false;
5135 
5136   // If there are no arguments specified, warn with -Wformat-security, otherwise
5137   // warn only with -Wformat-nonliteral.
5138   if (Args.size() == firstDataArg) {
5139     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5140       << OrigFormatExpr->getSourceRange();
5141     switch (Type) {
5142     default:
5143       break;
5144     case FST_Kprintf:
5145     case FST_FreeBSDKPrintf:
5146     case FST_Printf:
5147       Diag(FormatLoc, diag::note_format_security_fixit)
5148         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5149       break;
5150     case FST_NSString:
5151       Diag(FormatLoc, diag::note_format_security_fixit)
5152         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5153       break;
5154     }
5155   } else {
5156     Diag(FormatLoc, diag::warn_format_nonliteral)
5157       << OrigFormatExpr->getSourceRange();
5158   }
5159   return false;
5160 }
5161 
5162 namespace {
5163 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5164 protected:
5165   Sema &S;
5166   const FormatStringLiteral *FExpr;
5167   const Expr *OrigFormatExpr;
5168   const Sema::FormatStringType FSType;
5169   const unsigned FirstDataArg;
5170   const unsigned NumDataArgs;
5171   const char *Beg; // Start of format string.
5172   const bool HasVAListArg;
5173   ArrayRef<const Expr *> Args;
5174   unsigned FormatIdx;
5175   llvm::SmallBitVector CoveredArgs;
5176   bool usesPositionalArgs;
5177   bool atFirstArg;
5178   bool inFunctionCall;
5179   Sema::VariadicCallType CallType;
5180   llvm::SmallBitVector &CheckedVarArgs;
5181   UncoveredArgHandler &UncoveredArg;
5182 
5183 public:
5184   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5185                      const Expr *origFormatExpr,
5186                      const Sema::FormatStringType type, unsigned firstDataArg,
5187                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5188                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5189                      bool inFunctionCall, Sema::VariadicCallType callType,
5190                      llvm::SmallBitVector &CheckedVarArgs,
5191                      UncoveredArgHandler &UncoveredArg)
5192       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5193         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5194         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5195         usesPositionalArgs(false), atFirstArg(true),
5196         inFunctionCall(inFunctionCall), CallType(callType),
5197         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5198     CoveredArgs.resize(numDataArgs);
5199     CoveredArgs.reset();
5200   }
5201 
5202   void DoneProcessing();
5203 
5204   void HandleIncompleteSpecifier(const char *startSpecifier,
5205                                  unsigned specifierLen) override;
5206 
5207   void HandleInvalidLengthModifier(
5208                            const analyze_format_string::FormatSpecifier &FS,
5209                            const analyze_format_string::ConversionSpecifier &CS,
5210                            const char *startSpecifier, unsigned specifierLen,
5211                            unsigned DiagID);
5212 
5213   void HandleNonStandardLengthModifier(
5214                     const analyze_format_string::FormatSpecifier &FS,
5215                     const char *startSpecifier, unsigned specifierLen);
5216 
5217   void HandleNonStandardConversionSpecifier(
5218                     const analyze_format_string::ConversionSpecifier &CS,
5219                     const char *startSpecifier, unsigned specifierLen);
5220 
5221   void HandlePosition(const char *startPos, unsigned posLen) override;
5222 
5223   void HandleInvalidPosition(const char *startSpecifier,
5224                              unsigned specifierLen,
5225                              analyze_format_string::PositionContext p) override;
5226 
5227   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5228 
5229   void HandleNullChar(const char *nullCharacter) override;
5230 
5231   template <typename Range>
5232   static void
5233   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5234                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5235                        bool IsStringLocation, Range StringRange,
5236                        ArrayRef<FixItHint> Fixit = None);
5237 
5238 protected:
5239   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5240                                         const char *startSpec,
5241                                         unsigned specifierLen,
5242                                         const char *csStart, unsigned csLen);
5243 
5244   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5245                                          const char *startSpec,
5246                                          unsigned specifierLen);
5247 
5248   SourceRange getFormatStringRange();
5249   CharSourceRange getSpecifierRange(const char *startSpecifier,
5250                                     unsigned specifierLen);
5251   SourceLocation getLocationOfByte(const char *x);
5252 
5253   const Expr *getDataArg(unsigned i) const;
5254 
5255   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5256                     const analyze_format_string::ConversionSpecifier &CS,
5257                     const char *startSpecifier, unsigned specifierLen,
5258                     unsigned argIndex);
5259 
5260   template <typename Range>
5261   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5262                             bool IsStringLocation, Range StringRange,
5263                             ArrayRef<FixItHint> Fixit = None);
5264 };
5265 } // end anonymous namespace
5266 
5267 SourceRange CheckFormatHandler::getFormatStringRange() {
5268   return OrigFormatExpr->getSourceRange();
5269 }
5270 
5271 CharSourceRange CheckFormatHandler::
5272 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5273   SourceLocation Start = getLocationOfByte(startSpecifier);
5274   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5275 
5276   // Advance the end SourceLocation by one due to half-open ranges.
5277   End = End.getLocWithOffset(1);
5278 
5279   return CharSourceRange::getCharRange(Start, End);
5280 }
5281 
5282 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5283   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5284                                   S.getLangOpts(), S.Context.getTargetInfo());
5285 }
5286 
5287 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5288                                                    unsigned specifierLen){
5289   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5290                        getLocationOfByte(startSpecifier),
5291                        /*IsStringLocation*/true,
5292                        getSpecifierRange(startSpecifier, specifierLen));
5293 }
5294 
5295 void CheckFormatHandler::HandleInvalidLengthModifier(
5296     const analyze_format_string::FormatSpecifier &FS,
5297     const analyze_format_string::ConversionSpecifier &CS,
5298     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5299   using namespace analyze_format_string;
5300 
5301   const LengthModifier &LM = FS.getLengthModifier();
5302   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5303 
5304   // See if we know how to fix this length modifier.
5305   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5306   if (FixedLM) {
5307     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5308                          getLocationOfByte(LM.getStart()),
5309                          /*IsStringLocation*/true,
5310                          getSpecifierRange(startSpecifier, specifierLen));
5311 
5312     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5313       << FixedLM->toString()
5314       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5315 
5316   } else {
5317     FixItHint Hint;
5318     if (DiagID == diag::warn_format_nonsensical_length)
5319       Hint = FixItHint::CreateRemoval(LMRange);
5320 
5321     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5322                          getLocationOfByte(LM.getStart()),
5323                          /*IsStringLocation*/true,
5324                          getSpecifierRange(startSpecifier, specifierLen),
5325                          Hint);
5326   }
5327 }
5328 
5329 void CheckFormatHandler::HandleNonStandardLengthModifier(
5330     const analyze_format_string::FormatSpecifier &FS,
5331     const char *startSpecifier, unsigned specifierLen) {
5332   using namespace analyze_format_string;
5333 
5334   const LengthModifier &LM = FS.getLengthModifier();
5335   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5336 
5337   // See if we know how to fix this length modifier.
5338   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5339   if (FixedLM) {
5340     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5341                            << LM.toString() << 0,
5342                          getLocationOfByte(LM.getStart()),
5343                          /*IsStringLocation*/true,
5344                          getSpecifierRange(startSpecifier, specifierLen));
5345 
5346     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5347       << FixedLM->toString()
5348       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5349 
5350   } else {
5351     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5352                            << LM.toString() << 0,
5353                          getLocationOfByte(LM.getStart()),
5354                          /*IsStringLocation*/true,
5355                          getSpecifierRange(startSpecifier, specifierLen));
5356   }
5357 }
5358 
5359 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5360     const analyze_format_string::ConversionSpecifier &CS,
5361     const char *startSpecifier, unsigned specifierLen) {
5362   using namespace analyze_format_string;
5363 
5364   // See if we know how to fix this conversion specifier.
5365   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5366   if (FixedCS) {
5367     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5368                           << CS.toString() << /*conversion specifier*/1,
5369                          getLocationOfByte(CS.getStart()),
5370                          /*IsStringLocation*/true,
5371                          getSpecifierRange(startSpecifier, specifierLen));
5372 
5373     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5374     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5375       << FixedCS->toString()
5376       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5377   } else {
5378     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5379                           << CS.toString() << /*conversion specifier*/1,
5380                          getLocationOfByte(CS.getStart()),
5381                          /*IsStringLocation*/true,
5382                          getSpecifierRange(startSpecifier, specifierLen));
5383   }
5384 }
5385 
5386 void CheckFormatHandler::HandlePosition(const char *startPos,
5387                                         unsigned posLen) {
5388   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5389                                getLocationOfByte(startPos),
5390                                /*IsStringLocation*/true,
5391                                getSpecifierRange(startPos, posLen));
5392 }
5393 
5394 void
5395 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5396                                      analyze_format_string::PositionContext p) {
5397   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5398                          << (unsigned) p,
5399                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5400                        getSpecifierRange(startPos, posLen));
5401 }
5402 
5403 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5404                                             unsigned posLen) {
5405   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5406                                getLocationOfByte(startPos),
5407                                /*IsStringLocation*/true,
5408                                getSpecifierRange(startPos, posLen));
5409 }
5410 
5411 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5412   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5413     // The presence of a null character is likely an error.
5414     EmitFormatDiagnostic(
5415       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5416       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5417       getFormatStringRange());
5418   }
5419 }
5420 
5421 // Note that this may return NULL if there was an error parsing or building
5422 // one of the argument expressions.
5423 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5424   return Args[FirstDataArg + i];
5425 }
5426 
5427 void CheckFormatHandler::DoneProcessing() {
5428   // Does the number of data arguments exceed the number of
5429   // format conversions in the format string?
5430   if (!HasVAListArg) {
5431       // Find any arguments that weren't covered.
5432     CoveredArgs.flip();
5433     signed notCoveredArg = CoveredArgs.find_first();
5434     if (notCoveredArg >= 0) {
5435       assert((unsigned)notCoveredArg < NumDataArgs);
5436       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5437     } else {
5438       UncoveredArg.setAllCovered();
5439     }
5440   }
5441 }
5442 
5443 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5444                                    const Expr *ArgExpr) {
5445   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5446          "Invalid state");
5447 
5448   if (!ArgExpr)
5449     return;
5450 
5451   SourceLocation Loc = ArgExpr->getLocStart();
5452 
5453   if (S.getSourceManager().isInSystemMacro(Loc))
5454     return;
5455 
5456   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5457   for (auto E : DiagnosticExprs)
5458     PDiag << E->getSourceRange();
5459 
5460   CheckFormatHandler::EmitFormatDiagnostic(
5461                                   S, IsFunctionCall, DiagnosticExprs[0],
5462                                   PDiag, Loc, /*IsStringLocation*/false,
5463                                   DiagnosticExprs[0]->getSourceRange());
5464 }
5465 
5466 bool
5467 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5468                                                      SourceLocation Loc,
5469                                                      const char *startSpec,
5470                                                      unsigned specifierLen,
5471                                                      const char *csStart,
5472                                                      unsigned csLen) {
5473   bool keepGoing = true;
5474   if (argIndex < NumDataArgs) {
5475     // Consider the argument coverered, even though the specifier doesn't
5476     // make sense.
5477     CoveredArgs.set(argIndex);
5478   }
5479   else {
5480     // If argIndex exceeds the number of data arguments we
5481     // don't issue a warning because that is just a cascade of warnings (and
5482     // they may have intended '%%' anyway). We don't want to continue processing
5483     // the format string after this point, however, as we will like just get
5484     // gibberish when trying to match arguments.
5485     keepGoing = false;
5486   }
5487 
5488   StringRef Specifier(csStart, csLen);
5489 
5490   // If the specifier in non-printable, it could be the first byte of a UTF-8
5491   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5492   // hex value.
5493   std::string CodePointStr;
5494   if (!llvm::sys::locale::isPrint(*csStart)) {
5495     llvm::UTF32 CodePoint;
5496     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5497     const llvm::UTF8 *E =
5498         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5499     llvm::ConversionResult Result =
5500         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5501 
5502     if (Result != llvm::conversionOK) {
5503       unsigned char FirstChar = *csStart;
5504       CodePoint = (llvm::UTF32)FirstChar;
5505     }
5506 
5507     llvm::raw_string_ostream OS(CodePointStr);
5508     if (CodePoint < 256)
5509       OS << "\\x" << llvm::format("%02x", CodePoint);
5510     else if (CodePoint <= 0xFFFF)
5511       OS << "\\u" << llvm::format("%04x", CodePoint);
5512     else
5513       OS << "\\U" << llvm::format("%08x", CodePoint);
5514     OS.flush();
5515     Specifier = CodePointStr;
5516   }
5517 
5518   EmitFormatDiagnostic(
5519       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5520       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5521 
5522   return keepGoing;
5523 }
5524 
5525 void
5526 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5527                                                       const char *startSpec,
5528                                                       unsigned specifierLen) {
5529   EmitFormatDiagnostic(
5530     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5531     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5532 }
5533 
5534 bool
5535 CheckFormatHandler::CheckNumArgs(
5536   const analyze_format_string::FormatSpecifier &FS,
5537   const analyze_format_string::ConversionSpecifier &CS,
5538   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5539 
5540   if (argIndex >= NumDataArgs) {
5541     PartialDiagnostic PDiag = FS.usesPositionalArg()
5542       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5543            << (argIndex+1) << NumDataArgs)
5544       : S.PDiag(diag::warn_printf_insufficient_data_args);
5545     EmitFormatDiagnostic(
5546       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5547       getSpecifierRange(startSpecifier, specifierLen));
5548 
5549     // Since more arguments than conversion tokens are given, by extension
5550     // all arguments are covered, so mark this as so.
5551     UncoveredArg.setAllCovered();
5552     return false;
5553   }
5554   return true;
5555 }
5556 
5557 template<typename Range>
5558 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5559                                               SourceLocation Loc,
5560                                               bool IsStringLocation,
5561                                               Range StringRange,
5562                                               ArrayRef<FixItHint> FixIt) {
5563   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5564                        Loc, IsStringLocation, StringRange, FixIt);
5565 }
5566 
5567 /// \brief If the format string is not within the funcion call, emit a note
5568 /// so that the function call and string are in diagnostic messages.
5569 ///
5570 /// \param InFunctionCall if true, the format string is within the function
5571 /// call and only one diagnostic message will be produced.  Otherwise, an
5572 /// extra note will be emitted pointing to location of the format string.
5573 ///
5574 /// \param ArgumentExpr the expression that is passed as the format string
5575 /// argument in the function call.  Used for getting locations when two
5576 /// diagnostics are emitted.
5577 ///
5578 /// \param PDiag the callee should already have provided any strings for the
5579 /// diagnostic message.  This function only adds locations and fixits
5580 /// to diagnostics.
5581 ///
5582 /// \param Loc primary location for diagnostic.  If two diagnostics are
5583 /// required, one will be at Loc and a new SourceLocation will be created for
5584 /// the other one.
5585 ///
5586 /// \param IsStringLocation if true, Loc points to the format string should be
5587 /// used for the note.  Otherwise, Loc points to the argument list and will
5588 /// be used with PDiag.
5589 ///
5590 /// \param StringRange some or all of the string to highlight.  This is
5591 /// templated so it can accept either a CharSourceRange or a SourceRange.
5592 ///
5593 /// \param FixIt optional fix it hint for the format string.
5594 template <typename Range>
5595 void CheckFormatHandler::EmitFormatDiagnostic(
5596     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5597     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5598     Range StringRange, ArrayRef<FixItHint> FixIt) {
5599   if (InFunctionCall) {
5600     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5601     D << StringRange;
5602     D << FixIt;
5603   } else {
5604     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5605       << ArgumentExpr->getSourceRange();
5606 
5607     const Sema::SemaDiagnosticBuilder &Note =
5608       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5609              diag::note_format_string_defined);
5610 
5611     Note << StringRange;
5612     Note << FixIt;
5613   }
5614 }
5615 
5616 //===--- CHECK: Printf format string checking ------------------------------===//
5617 
5618 namespace {
5619 class CheckPrintfHandler : public CheckFormatHandler {
5620 public:
5621   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5622                      const Expr *origFormatExpr,
5623                      const Sema::FormatStringType type, unsigned firstDataArg,
5624                      unsigned numDataArgs, bool isObjC, const char *beg,
5625                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5626                      unsigned formatIdx, bool inFunctionCall,
5627                      Sema::VariadicCallType CallType,
5628                      llvm::SmallBitVector &CheckedVarArgs,
5629                      UncoveredArgHandler &UncoveredArg)
5630       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5631                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5632                            inFunctionCall, CallType, CheckedVarArgs,
5633                            UncoveredArg) {}
5634 
5635   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5636 
5637   /// Returns true if '%@' specifiers are allowed in the format string.
5638   bool allowsObjCArg() const {
5639     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5640            FSType == Sema::FST_OSTrace;
5641   }
5642 
5643   bool HandleInvalidPrintfConversionSpecifier(
5644                                       const analyze_printf::PrintfSpecifier &FS,
5645                                       const char *startSpecifier,
5646                                       unsigned specifierLen) override;
5647 
5648   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5649                              const char *startSpecifier,
5650                              unsigned specifierLen) override;
5651   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5652                        const char *StartSpecifier,
5653                        unsigned SpecifierLen,
5654                        const Expr *E);
5655 
5656   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5657                     const char *startSpecifier, unsigned specifierLen);
5658   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5659                            const analyze_printf::OptionalAmount &Amt,
5660                            unsigned type,
5661                            const char *startSpecifier, unsigned specifierLen);
5662   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5663                   const analyze_printf::OptionalFlag &flag,
5664                   const char *startSpecifier, unsigned specifierLen);
5665   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5666                          const analyze_printf::OptionalFlag &ignoredFlag,
5667                          const analyze_printf::OptionalFlag &flag,
5668                          const char *startSpecifier, unsigned specifierLen);
5669   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5670                            const Expr *E);
5671 
5672   void HandleEmptyObjCModifierFlag(const char *startFlag,
5673                                    unsigned flagLen) override;
5674 
5675   void HandleInvalidObjCModifierFlag(const char *startFlag,
5676                                             unsigned flagLen) override;
5677 
5678   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5679                                            const char *flagsEnd,
5680                                            const char *conversionPosition)
5681                                              override;
5682 };
5683 } // end anonymous namespace
5684 
5685 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5686                                       const analyze_printf::PrintfSpecifier &FS,
5687                                       const char *startSpecifier,
5688                                       unsigned specifierLen) {
5689   const analyze_printf::PrintfConversionSpecifier &CS =
5690     FS.getConversionSpecifier();
5691 
5692   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5693                                           getLocationOfByte(CS.getStart()),
5694                                           startSpecifier, specifierLen,
5695                                           CS.getStart(), CS.getLength());
5696 }
5697 
5698 bool CheckPrintfHandler::HandleAmount(
5699                                const analyze_format_string::OptionalAmount &Amt,
5700                                unsigned k, const char *startSpecifier,
5701                                unsigned specifierLen) {
5702   if (Amt.hasDataArgument()) {
5703     if (!HasVAListArg) {
5704       unsigned argIndex = Amt.getArgIndex();
5705       if (argIndex >= NumDataArgs) {
5706         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5707                                << k,
5708                              getLocationOfByte(Amt.getStart()),
5709                              /*IsStringLocation*/true,
5710                              getSpecifierRange(startSpecifier, specifierLen));
5711         // Don't do any more checking.  We will just emit
5712         // spurious errors.
5713         return false;
5714       }
5715 
5716       // Type check the data argument.  It should be an 'int'.
5717       // Although not in conformance with C99, we also allow the argument to be
5718       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5719       // doesn't emit a warning for that case.
5720       CoveredArgs.set(argIndex);
5721       const Expr *Arg = getDataArg(argIndex);
5722       if (!Arg)
5723         return false;
5724 
5725       QualType T = Arg->getType();
5726 
5727       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5728       assert(AT.isValid());
5729 
5730       if (!AT.matchesType(S.Context, T)) {
5731         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5732                                << k << AT.getRepresentativeTypeName(S.Context)
5733                                << T << Arg->getSourceRange(),
5734                              getLocationOfByte(Amt.getStart()),
5735                              /*IsStringLocation*/true,
5736                              getSpecifierRange(startSpecifier, specifierLen));
5737         // Don't do any more checking.  We will just emit
5738         // spurious errors.
5739         return false;
5740       }
5741     }
5742   }
5743   return true;
5744 }
5745 
5746 void CheckPrintfHandler::HandleInvalidAmount(
5747                                       const analyze_printf::PrintfSpecifier &FS,
5748                                       const analyze_printf::OptionalAmount &Amt,
5749                                       unsigned type,
5750                                       const char *startSpecifier,
5751                                       unsigned specifierLen) {
5752   const analyze_printf::PrintfConversionSpecifier &CS =
5753     FS.getConversionSpecifier();
5754 
5755   FixItHint fixit =
5756     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5757       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5758                                  Amt.getConstantLength()))
5759       : FixItHint();
5760 
5761   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5762                          << type << CS.toString(),
5763                        getLocationOfByte(Amt.getStart()),
5764                        /*IsStringLocation*/true,
5765                        getSpecifierRange(startSpecifier, specifierLen),
5766                        fixit);
5767 }
5768 
5769 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5770                                     const analyze_printf::OptionalFlag &flag,
5771                                     const char *startSpecifier,
5772                                     unsigned specifierLen) {
5773   // Warn about pointless flag with a fixit removal.
5774   const analyze_printf::PrintfConversionSpecifier &CS =
5775     FS.getConversionSpecifier();
5776   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5777                          << flag.toString() << CS.toString(),
5778                        getLocationOfByte(flag.getPosition()),
5779                        /*IsStringLocation*/true,
5780                        getSpecifierRange(startSpecifier, specifierLen),
5781                        FixItHint::CreateRemoval(
5782                          getSpecifierRange(flag.getPosition(), 1)));
5783 }
5784 
5785 void CheckPrintfHandler::HandleIgnoredFlag(
5786                                 const analyze_printf::PrintfSpecifier &FS,
5787                                 const analyze_printf::OptionalFlag &ignoredFlag,
5788                                 const analyze_printf::OptionalFlag &flag,
5789                                 const char *startSpecifier,
5790                                 unsigned specifierLen) {
5791   // Warn about ignored flag with a fixit removal.
5792   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5793                          << ignoredFlag.toString() << flag.toString(),
5794                        getLocationOfByte(ignoredFlag.getPosition()),
5795                        /*IsStringLocation*/true,
5796                        getSpecifierRange(startSpecifier, specifierLen),
5797                        FixItHint::CreateRemoval(
5798                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5799 }
5800 
5801 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5802 //                            bool IsStringLocation, Range StringRange,
5803 //                            ArrayRef<FixItHint> Fixit = None);
5804 
5805 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5806                                                      unsigned flagLen) {
5807   // Warn about an empty flag.
5808   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5809                        getLocationOfByte(startFlag),
5810                        /*IsStringLocation*/true,
5811                        getSpecifierRange(startFlag, flagLen));
5812 }
5813 
5814 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5815                                                        unsigned flagLen) {
5816   // Warn about an invalid flag.
5817   auto Range = getSpecifierRange(startFlag, flagLen);
5818   StringRef flag(startFlag, flagLen);
5819   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5820                       getLocationOfByte(startFlag),
5821                       /*IsStringLocation*/true,
5822                       Range, FixItHint::CreateRemoval(Range));
5823 }
5824 
5825 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5826     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5827     // Warn about using '[...]' without a '@' conversion.
5828     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5829     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5830     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5831                          getLocationOfByte(conversionPosition),
5832                          /*IsStringLocation*/true,
5833                          Range, FixItHint::CreateRemoval(Range));
5834 }
5835 
5836 // Determines if the specified is a C++ class or struct containing
5837 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5838 // "c_str()").
5839 template<typename MemberKind>
5840 static llvm::SmallPtrSet<MemberKind*, 1>
5841 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5842   const RecordType *RT = Ty->getAs<RecordType>();
5843   llvm::SmallPtrSet<MemberKind*, 1> Results;
5844 
5845   if (!RT)
5846     return Results;
5847   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5848   if (!RD || !RD->getDefinition())
5849     return Results;
5850 
5851   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5852                  Sema::LookupMemberName);
5853   R.suppressDiagnostics();
5854 
5855   // We just need to include all members of the right kind turned up by the
5856   // filter, at this point.
5857   if (S.LookupQualifiedName(R, RT->getDecl()))
5858     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5859       NamedDecl *decl = (*I)->getUnderlyingDecl();
5860       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5861         Results.insert(FK);
5862     }
5863   return Results;
5864 }
5865 
5866 /// Check if we could call '.c_str()' on an object.
5867 ///
5868 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5869 /// allow the call, or if it would be ambiguous).
5870 bool Sema::hasCStrMethod(const Expr *E) {
5871   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5872   MethodSet Results =
5873       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5874   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5875        MI != ME; ++MI)
5876     if ((*MI)->getMinRequiredArguments() == 0)
5877       return true;
5878   return false;
5879 }
5880 
5881 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5882 // better diagnostic if so. AT is assumed to be valid.
5883 // Returns true when a c_str() conversion method is found.
5884 bool CheckPrintfHandler::checkForCStrMembers(
5885     const analyze_printf::ArgType &AT, const Expr *E) {
5886   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5887 
5888   MethodSet Results =
5889       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5890 
5891   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5892        MI != ME; ++MI) {
5893     const CXXMethodDecl *Method = *MI;
5894     if (Method->getMinRequiredArguments() == 0 &&
5895         AT.matchesType(S.Context, Method->getReturnType())) {
5896       // FIXME: Suggest parens if the expression needs them.
5897       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5898       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5899           << "c_str()"
5900           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5901       return true;
5902     }
5903   }
5904 
5905   return false;
5906 }
5907 
5908 bool
5909 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5910                                             &FS,
5911                                           const char *startSpecifier,
5912                                           unsigned specifierLen) {
5913   using namespace analyze_format_string;
5914   using namespace analyze_printf;
5915   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5916 
5917   if (FS.consumesDataArgument()) {
5918     if (atFirstArg) {
5919         atFirstArg = false;
5920         usesPositionalArgs = FS.usesPositionalArg();
5921     }
5922     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5923       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5924                                         startSpecifier, specifierLen);
5925       return false;
5926     }
5927   }
5928 
5929   // First check if the field width, precision, and conversion specifier
5930   // have matching data arguments.
5931   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5932                     startSpecifier, specifierLen)) {
5933     return false;
5934   }
5935 
5936   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5937                     startSpecifier, specifierLen)) {
5938     return false;
5939   }
5940 
5941   if (!CS.consumesDataArgument()) {
5942     // FIXME: Technically specifying a precision or field width here
5943     // makes no sense.  Worth issuing a warning at some point.
5944     return true;
5945   }
5946 
5947   // Consume the argument.
5948   unsigned argIndex = FS.getArgIndex();
5949   if (argIndex < NumDataArgs) {
5950     // The check to see if the argIndex is valid will come later.
5951     // We set the bit here because we may exit early from this
5952     // function if we encounter some other error.
5953     CoveredArgs.set(argIndex);
5954   }
5955 
5956   // FreeBSD kernel extensions.
5957   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5958       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5959     // We need at least two arguments.
5960     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5961       return false;
5962 
5963     // Claim the second argument.
5964     CoveredArgs.set(argIndex + 1);
5965 
5966     // Type check the first argument (int for %b, pointer for %D)
5967     const Expr *Ex = getDataArg(argIndex);
5968     const analyze_printf::ArgType &AT =
5969       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5970         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5971     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5972       EmitFormatDiagnostic(
5973         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5974         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5975         << false << Ex->getSourceRange(),
5976         Ex->getLocStart(), /*IsStringLocation*/false,
5977         getSpecifierRange(startSpecifier, specifierLen));
5978 
5979     // Type check the second argument (char * for both %b and %D)
5980     Ex = getDataArg(argIndex + 1);
5981     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5982     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5983       EmitFormatDiagnostic(
5984         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5985         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5986         << false << Ex->getSourceRange(),
5987         Ex->getLocStart(), /*IsStringLocation*/false,
5988         getSpecifierRange(startSpecifier, specifierLen));
5989 
5990      return true;
5991   }
5992 
5993   // Check for using an Objective-C specific conversion specifier
5994   // in a non-ObjC literal.
5995   if (!allowsObjCArg() && CS.isObjCArg()) {
5996     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5997                                                   specifierLen);
5998   }
5999 
6000   // %P can only be used with os_log.
6001   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6002     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6003                                                   specifierLen);
6004   }
6005 
6006   // %n is not allowed with os_log.
6007   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6008     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6009                          getLocationOfByte(CS.getStart()),
6010                          /*IsStringLocation*/ false,
6011                          getSpecifierRange(startSpecifier, specifierLen));
6012 
6013     return true;
6014   }
6015 
6016   // Only scalars are allowed for os_trace.
6017   if (FSType == Sema::FST_OSTrace &&
6018       (CS.getKind() == ConversionSpecifier::PArg ||
6019        CS.getKind() == ConversionSpecifier::sArg ||
6020        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6021     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6022                                                   specifierLen);
6023   }
6024 
6025   // Check for use of public/private annotation outside of os_log().
6026   if (FSType != Sema::FST_OSLog) {
6027     if (FS.isPublic().isSet()) {
6028       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6029                                << "public",
6030                            getLocationOfByte(FS.isPublic().getPosition()),
6031                            /*IsStringLocation*/ false,
6032                            getSpecifierRange(startSpecifier, specifierLen));
6033     }
6034     if (FS.isPrivate().isSet()) {
6035       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6036                                << "private",
6037                            getLocationOfByte(FS.isPrivate().getPosition()),
6038                            /*IsStringLocation*/ false,
6039                            getSpecifierRange(startSpecifier, specifierLen));
6040     }
6041   }
6042 
6043   // Check for invalid use of field width
6044   if (!FS.hasValidFieldWidth()) {
6045     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6046         startSpecifier, specifierLen);
6047   }
6048 
6049   // Check for invalid use of precision
6050   if (!FS.hasValidPrecision()) {
6051     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6052         startSpecifier, specifierLen);
6053   }
6054 
6055   // Precision is mandatory for %P specifier.
6056   if (CS.getKind() == ConversionSpecifier::PArg &&
6057       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6058     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6059                          getLocationOfByte(startSpecifier),
6060                          /*IsStringLocation*/ false,
6061                          getSpecifierRange(startSpecifier, specifierLen));
6062   }
6063 
6064   // Check each flag does not conflict with any other component.
6065   if (!FS.hasValidThousandsGroupingPrefix())
6066     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6067   if (!FS.hasValidLeadingZeros())
6068     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6069   if (!FS.hasValidPlusPrefix())
6070     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6071   if (!FS.hasValidSpacePrefix())
6072     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6073   if (!FS.hasValidAlternativeForm())
6074     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6075   if (!FS.hasValidLeftJustified())
6076     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6077 
6078   // Check that flags are not ignored by another flag
6079   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6080     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6081         startSpecifier, specifierLen);
6082   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6083     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6084             startSpecifier, specifierLen);
6085 
6086   // Check the length modifier is valid with the given conversion specifier.
6087   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6088     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6089                                 diag::warn_format_nonsensical_length);
6090   else if (!FS.hasStandardLengthModifier())
6091     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6092   else if (!FS.hasStandardLengthConversionCombination())
6093     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6094                                 diag::warn_format_non_standard_conversion_spec);
6095 
6096   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6097     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6098 
6099   // The remaining checks depend on the data arguments.
6100   if (HasVAListArg)
6101     return true;
6102 
6103   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6104     return false;
6105 
6106   const Expr *Arg = getDataArg(argIndex);
6107   if (!Arg)
6108     return true;
6109 
6110   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6111 }
6112 
6113 static bool requiresParensToAddCast(const Expr *E) {
6114   // FIXME: We should have a general way to reason about operator
6115   // precedence and whether parens are actually needed here.
6116   // Take care of a few common cases where they aren't.
6117   const Expr *Inside = E->IgnoreImpCasts();
6118   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6119     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6120 
6121   switch (Inside->getStmtClass()) {
6122   case Stmt::ArraySubscriptExprClass:
6123   case Stmt::CallExprClass:
6124   case Stmt::CharacterLiteralClass:
6125   case Stmt::CXXBoolLiteralExprClass:
6126   case Stmt::DeclRefExprClass:
6127   case Stmt::FloatingLiteralClass:
6128   case Stmt::IntegerLiteralClass:
6129   case Stmt::MemberExprClass:
6130   case Stmt::ObjCArrayLiteralClass:
6131   case Stmt::ObjCBoolLiteralExprClass:
6132   case Stmt::ObjCBoxedExprClass:
6133   case Stmt::ObjCDictionaryLiteralClass:
6134   case Stmt::ObjCEncodeExprClass:
6135   case Stmt::ObjCIvarRefExprClass:
6136   case Stmt::ObjCMessageExprClass:
6137   case Stmt::ObjCPropertyRefExprClass:
6138   case Stmt::ObjCStringLiteralClass:
6139   case Stmt::ObjCSubscriptRefExprClass:
6140   case Stmt::ParenExprClass:
6141   case Stmt::StringLiteralClass:
6142   case Stmt::UnaryOperatorClass:
6143     return false;
6144   default:
6145     return true;
6146   }
6147 }
6148 
6149 static std::pair<QualType, StringRef>
6150 shouldNotPrintDirectly(const ASTContext &Context,
6151                        QualType IntendedTy,
6152                        const Expr *E) {
6153   // Use a 'while' to peel off layers of typedefs.
6154   QualType TyTy = IntendedTy;
6155   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6156     StringRef Name = UserTy->getDecl()->getName();
6157     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6158       .Case("CFIndex", Context.LongTy)
6159       .Case("NSInteger", Context.LongTy)
6160       .Case("NSUInteger", Context.UnsignedLongTy)
6161       .Case("SInt32", Context.IntTy)
6162       .Case("UInt32", Context.UnsignedIntTy)
6163       .Default(QualType());
6164 
6165     if (!CastTy.isNull())
6166       return std::make_pair(CastTy, Name);
6167 
6168     TyTy = UserTy->desugar();
6169   }
6170 
6171   // Strip parens if necessary.
6172   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6173     return shouldNotPrintDirectly(Context,
6174                                   PE->getSubExpr()->getType(),
6175                                   PE->getSubExpr());
6176 
6177   // If this is a conditional expression, then its result type is constructed
6178   // via usual arithmetic conversions and thus there might be no necessary
6179   // typedef sugar there.  Recurse to operands to check for NSInteger &
6180   // Co. usage condition.
6181   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6182     QualType TrueTy, FalseTy;
6183     StringRef TrueName, FalseName;
6184 
6185     std::tie(TrueTy, TrueName) =
6186       shouldNotPrintDirectly(Context,
6187                              CO->getTrueExpr()->getType(),
6188                              CO->getTrueExpr());
6189     std::tie(FalseTy, FalseName) =
6190       shouldNotPrintDirectly(Context,
6191                              CO->getFalseExpr()->getType(),
6192                              CO->getFalseExpr());
6193 
6194     if (TrueTy == FalseTy)
6195       return std::make_pair(TrueTy, TrueName);
6196     else if (TrueTy.isNull())
6197       return std::make_pair(FalseTy, FalseName);
6198     else if (FalseTy.isNull())
6199       return std::make_pair(TrueTy, TrueName);
6200   }
6201 
6202   return std::make_pair(QualType(), StringRef());
6203 }
6204 
6205 bool
6206 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6207                                     const char *StartSpecifier,
6208                                     unsigned SpecifierLen,
6209                                     const Expr *E) {
6210   using namespace analyze_format_string;
6211   using namespace analyze_printf;
6212   // Now type check the data expression that matches the
6213   // format specifier.
6214   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6215   if (!AT.isValid())
6216     return true;
6217 
6218   QualType ExprTy = E->getType();
6219   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6220     ExprTy = TET->getUnderlyingExpr()->getType();
6221   }
6222 
6223   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6224 
6225   if (match == analyze_printf::ArgType::Match) {
6226     return true;
6227   }
6228 
6229   // Look through argument promotions for our error message's reported type.
6230   // This includes the integral and floating promotions, but excludes array
6231   // and function pointer decay; seeing that an argument intended to be a
6232   // string has type 'char [6]' is probably more confusing than 'char *'.
6233   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6234     if (ICE->getCastKind() == CK_IntegralCast ||
6235         ICE->getCastKind() == CK_FloatingCast) {
6236       E = ICE->getSubExpr();
6237       ExprTy = E->getType();
6238 
6239       // Check if we didn't match because of an implicit cast from a 'char'
6240       // or 'short' to an 'int'.  This is done because printf is a varargs
6241       // function.
6242       if (ICE->getType() == S.Context.IntTy ||
6243           ICE->getType() == S.Context.UnsignedIntTy) {
6244         // All further checking is done on the subexpression.
6245         if (AT.matchesType(S.Context, ExprTy))
6246           return true;
6247       }
6248     }
6249   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6250     // Special case for 'a', which has type 'int' in C.
6251     // Note, however, that we do /not/ want to treat multibyte constants like
6252     // 'MooV' as characters! This form is deprecated but still exists.
6253     if (ExprTy == S.Context.IntTy)
6254       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6255         ExprTy = S.Context.CharTy;
6256   }
6257 
6258   // Look through enums to their underlying type.
6259   bool IsEnum = false;
6260   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6261     ExprTy = EnumTy->getDecl()->getIntegerType();
6262     IsEnum = true;
6263   }
6264 
6265   // %C in an Objective-C context prints a unichar, not a wchar_t.
6266   // If the argument is an integer of some kind, believe the %C and suggest
6267   // a cast instead of changing the conversion specifier.
6268   QualType IntendedTy = ExprTy;
6269   if (isObjCContext() &&
6270       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6271     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6272         !ExprTy->isCharType()) {
6273       // 'unichar' is defined as a typedef of unsigned short, but we should
6274       // prefer using the typedef if it is visible.
6275       IntendedTy = S.Context.UnsignedShortTy;
6276 
6277       // While we are here, check if the value is an IntegerLiteral that happens
6278       // to be within the valid range.
6279       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6280         const llvm::APInt &V = IL->getValue();
6281         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6282           return true;
6283       }
6284 
6285       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6286                           Sema::LookupOrdinaryName);
6287       if (S.LookupName(Result, S.getCurScope())) {
6288         NamedDecl *ND = Result.getFoundDecl();
6289         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6290           if (TD->getUnderlyingType() == IntendedTy)
6291             IntendedTy = S.Context.getTypedefType(TD);
6292       }
6293     }
6294   }
6295 
6296   // Special-case some of Darwin's platform-independence types by suggesting
6297   // casts to primitive types that are known to be large enough.
6298   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6299   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6300     QualType CastTy;
6301     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6302     if (!CastTy.isNull()) {
6303       IntendedTy = CastTy;
6304       ShouldNotPrintDirectly = true;
6305     }
6306   }
6307 
6308   // We may be able to offer a FixItHint if it is a supported type.
6309   PrintfSpecifier fixedFS = FS;
6310   bool success =
6311       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6312 
6313   if (success) {
6314     // Get the fix string from the fixed format specifier
6315     SmallString<16> buf;
6316     llvm::raw_svector_ostream os(buf);
6317     fixedFS.toString(os);
6318 
6319     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6320 
6321     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6322       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6323       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6324         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6325       }
6326       // In this case, the specifier is wrong and should be changed to match
6327       // the argument.
6328       EmitFormatDiagnostic(S.PDiag(diag)
6329                                << AT.getRepresentativeTypeName(S.Context)
6330                                << IntendedTy << IsEnum << E->getSourceRange(),
6331                            E->getLocStart(),
6332                            /*IsStringLocation*/ false, SpecRange,
6333                            FixItHint::CreateReplacement(SpecRange, os.str()));
6334     } else {
6335       // The canonical type for formatting this value is different from the
6336       // actual type of the expression. (This occurs, for example, with Darwin's
6337       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6338       // should be printed as 'long' for 64-bit compatibility.)
6339       // Rather than emitting a normal format/argument mismatch, we want to
6340       // add a cast to the recommended type (and correct the format string
6341       // if necessary).
6342       SmallString<16> CastBuf;
6343       llvm::raw_svector_ostream CastFix(CastBuf);
6344       CastFix << "(";
6345       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6346       CastFix << ")";
6347 
6348       SmallVector<FixItHint,4> Hints;
6349       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6350         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6351 
6352       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6353         // If there's already a cast present, just replace it.
6354         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6355         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6356 
6357       } else if (!requiresParensToAddCast(E)) {
6358         // If the expression has high enough precedence,
6359         // just write the C-style cast.
6360         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6361                                                    CastFix.str()));
6362       } else {
6363         // Otherwise, add parens around the expression as well as the cast.
6364         CastFix << "(";
6365         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6366                                                    CastFix.str()));
6367 
6368         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6369         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6370       }
6371 
6372       if (ShouldNotPrintDirectly) {
6373         // The expression has a type that should not be printed directly.
6374         // We extract the name from the typedef because we don't want to show
6375         // the underlying type in the diagnostic.
6376         StringRef Name;
6377         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6378           Name = TypedefTy->getDecl()->getName();
6379         else
6380           Name = CastTyName;
6381         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6382                                << Name << IntendedTy << IsEnum
6383                                << E->getSourceRange(),
6384                              E->getLocStart(), /*IsStringLocation=*/false,
6385                              SpecRange, Hints);
6386       } else {
6387         // In this case, the expression could be printed using a different
6388         // specifier, but we've decided that the specifier is probably correct
6389         // and we should cast instead. Just use the normal warning message.
6390         EmitFormatDiagnostic(
6391           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6392             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6393             << E->getSourceRange(),
6394           E->getLocStart(), /*IsStringLocation*/false,
6395           SpecRange, Hints);
6396       }
6397     }
6398   } else {
6399     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6400                                                    SpecifierLen);
6401     // Since the warning for passing non-POD types to variadic functions
6402     // was deferred until now, we emit a warning for non-POD
6403     // arguments here.
6404     switch (S.isValidVarArgType(ExprTy)) {
6405     case Sema::VAK_Valid:
6406     case Sema::VAK_ValidInCXX11: {
6407       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6408       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6409         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6410       }
6411 
6412       EmitFormatDiagnostic(
6413           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6414                         << IsEnum << CSR << E->getSourceRange(),
6415           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6416       break;
6417     }
6418     case Sema::VAK_Undefined:
6419     case Sema::VAK_MSVCUndefined:
6420       EmitFormatDiagnostic(
6421         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6422           << S.getLangOpts().CPlusPlus11
6423           << ExprTy
6424           << CallType
6425           << AT.getRepresentativeTypeName(S.Context)
6426           << CSR
6427           << E->getSourceRange(),
6428         E->getLocStart(), /*IsStringLocation*/false, CSR);
6429       checkForCStrMembers(AT, E);
6430       break;
6431 
6432     case Sema::VAK_Invalid:
6433       if (ExprTy->isObjCObjectType())
6434         EmitFormatDiagnostic(
6435           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6436             << S.getLangOpts().CPlusPlus11
6437             << ExprTy
6438             << CallType
6439             << AT.getRepresentativeTypeName(S.Context)
6440             << CSR
6441             << E->getSourceRange(),
6442           E->getLocStart(), /*IsStringLocation*/false, CSR);
6443       else
6444         // FIXME: If this is an initializer list, suggest removing the braces
6445         // or inserting a cast to the target type.
6446         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6447           << isa<InitListExpr>(E) << ExprTy << CallType
6448           << AT.getRepresentativeTypeName(S.Context)
6449           << E->getSourceRange();
6450       break;
6451     }
6452 
6453     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6454            "format string specifier index out of range");
6455     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6456   }
6457 
6458   return true;
6459 }
6460 
6461 //===--- CHECK: Scanf format string checking ------------------------------===//
6462 
6463 namespace {
6464 class CheckScanfHandler : public CheckFormatHandler {
6465 public:
6466   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6467                     const Expr *origFormatExpr, Sema::FormatStringType type,
6468                     unsigned firstDataArg, unsigned numDataArgs,
6469                     const char *beg, bool hasVAListArg,
6470                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6471                     bool inFunctionCall, Sema::VariadicCallType CallType,
6472                     llvm::SmallBitVector &CheckedVarArgs,
6473                     UncoveredArgHandler &UncoveredArg)
6474       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6475                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6476                            inFunctionCall, CallType, CheckedVarArgs,
6477                            UncoveredArg) {}
6478 
6479   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6480                             const char *startSpecifier,
6481                             unsigned specifierLen) override;
6482 
6483   bool HandleInvalidScanfConversionSpecifier(
6484           const analyze_scanf::ScanfSpecifier &FS,
6485           const char *startSpecifier,
6486           unsigned specifierLen) override;
6487 
6488   void HandleIncompleteScanList(const char *start, const char *end) override;
6489 };
6490 } // end anonymous namespace
6491 
6492 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6493                                                  const char *end) {
6494   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6495                        getLocationOfByte(end), /*IsStringLocation*/true,
6496                        getSpecifierRange(start, end - start));
6497 }
6498 
6499 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6500                                         const analyze_scanf::ScanfSpecifier &FS,
6501                                         const char *startSpecifier,
6502                                         unsigned specifierLen) {
6503 
6504   const analyze_scanf::ScanfConversionSpecifier &CS =
6505     FS.getConversionSpecifier();
6506 
6507   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6508                                           getLocationOfByte(CS.getStart()),
6509                                           startSpecifier, specifierLen,
6510                                           CS.getStart(), CS.getLength());
6511 }
6512 
6513 bool CheckScanfHandler::HandleScanfSpecifier(
6514                                        const analyze_scanf::ScanfSpecifier &FS,
6515                                        const char *startSpecifier,
6516                                        unsigned specifierLen) {
6517   using namespace analyze_scanf;
6518   using namespace analyze_format_string;
6519 
6520   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6521 
6522   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6523   // be used to decide if we are using positional arguments consistently.
6524   if (FS.consumesDataArgument()) {
6525     if (atFirstArg) {
6526       atFirstArg = false;
6527       usesPositionalArgs = FS.usesPositionalArg();
6528     }
6529     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6530       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6531                                         startSpecifier, specifierLen);
6532       return false;
6533     }
6534   }
6535 
6536   // Check if the field with is non-zero.
6537   const OptionalAmount &Amt = FS.getFieldWidth();
6538   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6539     if (Amt.getConstantAmount() == 0) {
6540       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6541                                                    Amt.getConstantLength());
6542       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6543                            getLocationOfByte(Amt.getStart()),
6544                            /*IsStringLocation*/true, R,
6545                            FixItHint::CreateRemoval(R));
6546     }
6547   }
6548 
6549   if (!FS.consumesDataArgument()) {
6550     // FIXME: Technically specifying a precision or field width here
6551     // makes no sense.  Worth issuing a warning at some point.
6552     return true;
6553   }
6554 
6555   // Consume the argument.
6556   unsigned argIndex = FS.getArgIndex();
6557   if (argIndex < NumDataArgs) {
6558       // The check to see if the argIndex is valid will come later.
6559       // We set the bit here because we may exit early from this
6560       // function if we encounter some other error.
6561     CoveredArgs.set(argIndex);
6562   }
6563 
6564   // Check the length modifier is valid with the given conversion specifier.
6565   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6566     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6567                                 diag::warn_format_nonsensical_length);
6568   else if (!FS.hasStandardLengthModifier())
6569     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6570   else if (!FS.hasStandardLengthConversionCombination())
6571     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6572                                 diag::warn_format_non_standard_conversion_spec);
6573 
6574   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6575     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6576 
6577   // The remaining checks depend on the data arguments.
6578   if (HasVAListArg)
6579     return true;
6580 
6581   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6582     return false;
6583 
6584   // Check that the argument type matches the format specifier.
6585   const Expr *Ex = getDataArg(argIndex);
6586   if (!Ex)
6587     return true;
6588 
6589   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6590 
6591   if (!AT.isValid()) {
6592     return true;
6593   }
6594 
6595   analyze_format_string::ArgType::MatchKind match =
6596       AT.matchesType(S.Context, Ex->getType());
6597   if (match == analyze_format_string::ArgType::Match) {
6598     return true;
6599   }
6600 
6601   ScanfSpecifier fixedFS = FS;
6602   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6603                                  S.getLangOpts(), S.Context);
6604 
6605   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6606   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6607     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6608   }
6609 
6610   if (success) {
6611     // Get the fix string from the fixed format specifier.
6612     SmallString<128> buf;
6613     llvm::raw_svector_ostream os(buf);
6614     fixedFS.toString(os);
6615 
6616     EmitFormatDiagnostic(
6617         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6618                       << Ex->getType() << false << Ex->getSourceRange(),
6619         Ex->getLocStart(),
6620         /*IsStringLocation*/ false,
6621         getSpecifierRange(startSpecifier, specifierLen),
6622         FixItHint::CreateReplacement(
6623             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6624   } else {
6625     EmitFormatDiagnostic(S.PDiag(diag)
6626                              << AT.getRepresentativeTypeName(S.Context)
6627                              << Ex->getType() << false << Ex->getSourceRange(),
6628                          Ex->getLocStart(),
6629                          /*IsStringLocation*/ false,
6630                          getSpecifierRange(startSpecifier, specifierLen));
6631   }
6632 
6633   return true;
6634 }
6635 
6636 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6637                               const Expr *OrigFormatExpr,
6638                               ArrayRef<const Expr *> Args,
6639                               bool HasVAListArg, unsigned format_idx,
6640                               unsigned firstDataArg,
6641                               Sema::FormatStringType Type,
6642                               bool inFunctionCall,
6643                               Sema::VariadicCallType CallType,
6644                               llvm::SmallBitVector &CheckedVarArgs,
6645                               UncoveredArgHandler &UncoveredArg) {
6646   // CHECK: is the format string a wide literal?
6647   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6648     CheckFormatHandler::EmitFormatDiagnostic(
6649       S, inFunctionCall, Args[format_idx],
6650       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6651       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6652     return;
6653   }
6654 
6655   // Str - The format string.  NOTE: this is NOT null-terminated!
6656   StringRef StrRef = FExpr->getString();
6657   const char *Str = StrRef.data();
6658   // Account for cases where the string literal is truncated in a declaration.
6659   const ConstantArrayType *T =
6660     S.Context.getAsConstantArrayType(FExpr->getType());
6661   assert(T && "String literal not of constant array type!");
6662   size_t TypeSize = T->getSize().getZExtValue();
6663   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6664   const unsigned numDataArgs = Args.size() - firstDataArg;
6665 
6666   // Emit a warning if the string literal is truncated and does not contain an
6667   // embedded null character.
6668   if (TypeSize <= StrRef.size() &&
6669       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6670     CheckFormatHandler::EmitFormatDiagnostic(
6671         S, inFunctionCall, Args[format_idx],
6672         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6673         FExpr->getLocStart(),
6674         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6675     return;
6676   }
6677 
6678   // CHECK: empty format string?
6679   if (StrLen == 0 && numDataArgs > 0) {
6680     CheckFormatHandler::EmitFormatDiagnostic(
6681       S, inFunctionCall, Args[format_idx],
6682       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6683       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6684     return;
6685   }
6686 
6687   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6688       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6689       Type == Sema::FST_OSTrace) {
6690     CheckPrintfHandler H(
6691         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6692         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6693         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6694         CheckedVarArgs, UncoveredArg);
6695 
6696     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6697                                                   S.getLangOpts(),
6698                                                   S.Context.getTargetInfo(),
6699                                             Type == Sema::FST_FreeBSDKPrintf))
6700       H.DoneProcessing();
6701   } else if (Type == Sema::FST_Scanf) {
6702     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6703                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6704                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6705 
6706     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6707                                                  S.getLangOpts(),
6708                                                  S.Context.getTargetInfo()))
6709       H.DoneProcessing();
6710   } // TODO: handle other formats
6711 }
6712 
6713 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6714   // Str - The format string.  NOTE: this is NOT null-terminated!
6715   StringRef StrRef = FExpr->getString();
6716   const char *Str = StrRef.data();
6717   // Account for cases where the string literal is truncated in a declaration.
6718   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6719   assert(T && "String literal not of constant array type!");
6720   size_t TypeSize = T->getSize().getZExtValue();
6721   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6722   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6723                                                          getLangOpts(),
6724                                                          Context.getTargetInfo());
6725 }
6726 
6727 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6728 
6729 // Returns the related absolute value function that is larger, of 0 if one
6730 // does not exist.
6731 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6732   switch (AbsFunction) {
6733   default:
6734     return 0;
6735 
6736   case Builtin::BI__builtin_abs:
6737     return Builtin::BI__builtin_labs;
6738   case Builtin::BI__builtin_labs:
6739     return Builtin::BI__builtin_llabs;
6740   case Builtin::BI__builtin_llabs:
6741     return 0;
6742 
6743   case Builtin::BI__builtin_fabsf:
6744     return Builtin::BI__builtin_fabs;
6745   case Builtin::BI__builtin_fabs:
6746     return Builtin::BI__builtin_fabsl;
6747   case Builtin::BI__builtin_fabsl:
6748     return 0;
6749 
6750   case Builtin::BI__builtin_cabsf:
6751     return Builtin::BI__builtin_cabs;
6752   case Builtin::BI__builtin_cabs:
6753     return Builtin::BI__builtin_cabsl;
6754   case Builtin::BI__builtin_cabsl:
6755     return 0;
6756 
6757   case Builtin::BIabs:
6758     return Builtin::BIlabs;
6759   case Builtin::BIlabs:
6760     return Builtin::BIllabs;
6761   case Builtin::BIllabs:
6762     return 0;
6763 
6764   case Builtin::BIfabsf:
6765     return Builtin::BIfabs;
6766   case Builtin::BIfabs:
6767     return Builtin::BIfabsl;
6768   case Builtin::BIfabsl:
6769     return 0;
6770 
6771   case Builtin::BIcabsf:
6772    return Builtin::BIcabs;
6773   case Builtin::BIcabs:
6774     return Builtin::BIcabsl;
6775   case Builtin::BIcabsl:
6776     return 0;
6777   }
6778 }
6779 
6780 // Returns the argument type of the absolute value function.
6781 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6782                                              unsigned AbsType) {
6783   if (AbsType == 0)
6784     return QualType();
6785 
6786   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6787   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6788   if (Error != ASTContext::GE_None)
6789     return QualType();
6790 
6791   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6792   if (!FT)
6793     return QualType();
6794 
6795   if (FT->getNumParams() != 1)
6796     return QualType();
6797 
6798   return FT->getParamType(0);
6799 }
6800 
6801 // Returns the best absolute value function, or zero, based on type and
6802 // current absolute value function.
6803 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6804                                    unsigned AbsFunctionKind) {
6805   unsigned BestKind = 0;
6806   uint64_t ArgSize = Context.getTypeSize(ArgType);
6807   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6808        Kind = getLargerAbsoluteValueFunction(Kind)) {
6809     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6810     if (Context.getTypeSize(ParamType) >= ArgSize) {
6811       if (BestKind == 0)
6812         BestKind = Kind;
6813       else if (Context.hasSameType(ParamType, ArgType)) {
6814         BestKind = Kind;
6815         break;
6816       }
6817     }
6818   }
6819   return BestKind;
6820 }
6821 
6822 enum AbsoluteValueKind {
6823   AVK_Integer,
6824   AVK_Floating,
6825   AVK_Complex
6826 };
6827 
6828 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6829   if (T->isIntegralOrEnumerationType())
6830     return AVK_Integer;
6831   if (T->isRealFloatingType())
6832     return AVK_Floating;
6833   if (T->isAnyComplexType())
6834     return AVK_Complex;
6835 
6836   llvm_unreachable("Type not integer, floating, or complex");
6837 }
6838 
6839 // Changes the absolute value function to a different type.  Preserves whether
6840 // the function is a builtin.
6841 static unsigned changeAbsFunction(unsigned AbsKind,
6842                                   AbsoluteValueKind ValueKind) {
6843   switch (ValueKind) {
6844   case AVK_Integer:
6845     switch (AbsKind) {
6846     default:
6847       return 0;
6848     case Builtin::BI__builtin_fabsf:
6849     case Builtin::BI__builtin_fabs:
6850     case Builtin::BI__builtin_fabsl:
6851     case Builtin::BI__builtin_cabsf:
6852     case Builtin::BI__builtin_cabs:
6853     case Builtin::BI__builtin_cabsl:
6854       return Builtin::BI__builtin_abs;
6855     case Builtin::BIfabsf:
6856     case Builtin::BIfabs:
6857     case Builtin::BIfabsl:
6858     case Builtin::BIcabsf:
6859     case Builtin::BIcabs:
6860     case Builtin::BIcabsl:
6861       return Builtin::BIabs;
6862     }
6863   case AVK_Floating:
6864     switch (AbsKind) {
6865     default:
6866       return 0;
6867     case Builtin::BI__builtin_abs:
6868     case Builtin::BI__builtin_labs:
6869     case Builtin::BI__builtin_llabs:
6870     case Builtin::BI__builtin_cabsf:
6871     case Builtin::BI__builtin_cabs:
6872     case Builtin::BI__builtin_cabsl:
6873       return Builtin::BI__builtin_fabsf;
6874     case Builtin::BIabs:
6875     case Builtin::BIlabs:
6876     case Builtin::BIllabs:
6877     case Builtin::BIcabsf:
6878     case Builtin::BIcabs:
6879     case Builtin::BIcabsl:
6880       return Builtin::BIfabsf;
6881     }
6882   case AVK_Complex:
6883     switch (AbsKind) {
6884     default:
6885       return 0;
6886     case Builtin::BI__builtin_abs:
6887     case Builtin::BI__builtin_labs:
6888     case Builtin::BI__builtin_llabs:
6889     case Builtin::BI__builtin_fabsf:
6890     case Builtin::BI__builtin_fabs:
6891     case Builtin::BI__builtin_fabsl:
6892       return Builtin::BI__builtin_cabsf;
6893     case Builtin::BIabs:
6894     case Builtin::BIlabs:
6895     case Builtin::BIllabs:
6896     case Builtin::BIfabsf:
6897     case Builtin::BIfabs:
6898     case Builtin::BIfabsl:
6899       return Builtin::BIcabsf;
6900     }
6901   }
6902   llvm_unreachable("Unable to convert function");
6903 }
6904 
6905 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6906   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6907   if (!FnInfo)
6908     return 0;
6909 
6910   switch (FDecl->getBuiltinID()) {
6911   default:
6912     return 0;
6913   case Builtin::BI__builtin_abs:
6914   case Builtin::BI__builtin_fabs:
6915   case Builtin::BI__builtin_fabsf:
6916   case Builtin::BI__builtin_fabsl:
6917   case Builtin::BI__builtin_labs:
6918   case Builtin::BI__builtin_llabs:
6919   case Builtin::BI__builtin_cabs:
6920   case Builtin::BI__builtin_cabsf:
6921   case Builtin::BI__builtin_cabsl:
6922   case Builtin::BIabs:
6923   case Builtin::BIlabs:
6924   case Builtin::BIllabs:
6925   case Builtin::BIfabs:
6926   case Builtin::BIfabsf:
6927   case Builtin::BIfabsl:
6928   case Builtin::BIcabs:
6929   case Builtin::BIcabsf:
6930   case Builtin::BIcabsl:
6931     return FDecl->getBuiltinID();
6932   }
6933   llvm_unreachable("Unknown Builtin type");
6934 }
6935 
6936 // If the replacement is valid, emit a note with replacement function.
6937 // Additionally, suggest including the proper header if not already included.
6938 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6939                             unsigned AbsKind, QualType ArgType) {
6940   bool EmitHeaderHint = true;
6941   const char *HeaderName = nullptr;
6942   const char *FunctionName = nullptr;
6943   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6944     FunctionName = "std::abs";
6945     if (ArgType->isIntegralOrEnumerationType()) {
6946       HeaderName = "cstdlib";
6947     } else if (ArgType->isRealFloatingType()) {
6948       HeaderName = "cmath";
6949     } else {
6950       llvm_unreachable("Invalid Type");
6951     }
6952 
6953     // Lookup all std::abs
6954     if (NamespaceDecl *Std = S.getStdNamespace()) {
6955       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6956       R.suppressDiagnostics();
6957       S.LookupQualifiedName(R, Std);
6958 
6959       for (const auto *I : R) {
6960         const FunctionDecl *FDecl = nullptr;
6961         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6962           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6963         } else {
6964           FDecl = dyn_cast<FunctionDecl>(I);
6965         }
6966         if (!FDecl)
6967           continue;
6968 
6969         // Found std::abs(), check that they are the right ones.
6970         if (FDecl->getNumParams() != 1)
6971           continue;
6972 
6973         // Check that the parameter type can handle the argument.
6974         QualType ParamType = FDecl->getParamDecl(0)->getType();
6975         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6976             S.Context.getTypeSize(ArgType) <=
6977                 S.Context.getTypeSize(ParamType)) {
6978           // Found a function, don't need the header hint.
6979           EmitHeaderHint = false;
6980           break;
6981         }
6982       }
6983     }
6984   } else {
6985     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6986     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6987 
6988     if (HeaderName) {
6989       DeclarationName DN(&S.Context.Idents.get(FunctionName));
6990       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
6991       R.suppressDiagnostics();
6992       S.LookupName(R, S.getCurScope());
6993 
6994       if (R.isSingleResult()) {
6995         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
6996         if (FD && FD->getBuiltinID() == AbsKind) {
6997           EmitHeaderHint = false;
6998         } else {
6999           return;
7000         }
7001       } else if (!R.empty()) {
7002         return;
7003       }
7004     }
7005   }
7006 
7007   S.Diag(Loc, diag::note_replace_abs_function)
7008       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7009 
7010   if (!HeaderName)
7011     return;
7012 
7013   if (!EmitHeaderHint)
7014     return;
7015 
7016   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7017                                                     << FunctionName;
7018 }
7019 
7020 template <std::size_t StrLen>
7021 static bool IsStdFunction(const FunctionDecl *FDecl,
7022                           const char (&Str)[StrLen]) {
7023   if (!FDecl)
7024     return false;
7025   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7026     return false;
7027   if (!FDecl->isInStdNamespace())
7028     return false;
7029 
7030   return true;
7031 }
7032 
7033 // Warn when using the wrong abs() function.
7034 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7035                                       const FunctionDecl *FDecl) {
7036   if (Call->getNumArgs() != 1)
7037     return;
7038 
7039   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7040   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7041   if (AbsKind == 0 && !IsStdAbs)
7042     return;
7043 
7044   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7045   QualType ParamType = Call->getArg(0)->getType();
7046 
7047   // Unsigned types cannot be negative.  Suggest removing the absolute value
7048   // function call.
7049   if (ArgType->isUnsignedIntegerType()) {
7050     const char *FunctionName =
7051         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7052     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7053     Diag(Call->getExprLoc(), diag::note_remove_abs)
7054         << FunctionName
7055         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7056     return;
7057   }
7058 
7059   // Taking the absolute value of a pointer is very suspicious, they probably
7060   // wanted to index into an array, dereference a pointer, call a function, etc.
7061   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7062     unsigned DiagType = 0;
7063     if (ArgType->isFunctionType())
7064       DiagType = 1;
7065     else if (ArgType->isArrayType())
7066       DiagType = 2;
7067 
7068     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7069     return;
7070   }
7071 
7072   // std::abs has overloads which prevent most of the absolute value problems
7073   // from occurring.
7074   if (IsStdAbs)
7075     return;
7076 
7077   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7078   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7079 
7080   // The argument and parameter are the same kind.  Check if they are the right
7081   // size.
7082   if (ArgValueKind == ParamValueKind) {
7083     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7084       return;
7085 
7086     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7087     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7088         << FDecl << ArgType << ParamType;
7089 
7090     if (NewAbsKind == 0)
7091       return;
7092 
7093     emitReplacement(*this, Call->getExprLoc(),
7094                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7095     return;
7096   }
7097 
7098   // ArgValueKind != ParamValueKind
7099   // The wrong type of absolute value function was used.  Attempt to find the
7100   // proper one.
7101   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7102   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7103   if (NewAbsKind == 0)
7104     return;
7105 
7106   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7107       << FDecl << ParamValueKind << ArgValueKind;
7108 
7109   emitReplacement(*this, Call->getExprLoc(),
7110                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7111 }
7112 
7113 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7114 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7115                                 const FunctionDecl *FDecl) {
7116   if (!Call || !FDecl) return;
7117 
7118   // Ignore template specializations and macros.
7119   if (inTemplateInstantiation()) return;
7120   if (Call->getExprLoc().isMacroID()) return;
7121 
7122   // Only care about the one template argument, two function parameter std::max
7123   if (Call->getNumArgs() != 2) return;
7124   if (!IsStdFunction(FDecl, "max")) return;
7125   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7126   if (!ArgList) return;
7127   if (ArgList->size() != 1) return;
7128 
7129   // Check that template type argument is unsigned integer.
7130   const auto& TA = ArgList->get(0);
7131   if (TA.getKind() != TemplateArgument::Type) return;
7132   QualType ArgType = TA.getAsType();
7133   if (!ArgType->isUnsignedIntegerType()) return;
7134 
7135   // See if either argument is a literal zero.
7136   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7137     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7138     if (!MTE) return false;
7139     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7140     if (!Num) return false;
7141     if (Num->getValue() != 0) return false;
7142     return true;
7143   };
7144 
7145   const Expr *FirstArg = Call->getArg(0);
7146   const Expr *SecondArg = Call->getArg(1);
7147   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7148   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7149 
7150   // Only warn when exactly one argument is zero.
7151   if (IsFirstArgZero == IsSecondArgZero) return;
7152 
7153   SourceRange FirstRange = FirstArg->getSourceRange();
7154   SourceRange SecondRange = SecondArg->getSourceRange();
7155 
7156   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7157 
7158   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7159       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7160 
7161   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7162   SourceRange RemovalRange;
7163   if (IsFirstArgZero) {
7164     RemovalRange = SourceRange(FirstRange.getBegin(),
7165                                SecondRange.getBegin().getLocWithOffset(-1));
7166   } else {
7167     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7168                                SecondRange.getEnd());
7169   }
7170 
7171   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7172         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7173         << FixItHint::CreateRemoval(RemovalRange);
7174 }
7175 
7176 //===--- CHECK: Standard memory functions ---------------------------------===//
7177 
7178 /// \brief Takes the expression passed to the size_t parameter of functions
7179 /// such as memcmp, strncat, etc and warns if it's a comparison.
7180 ///
7181 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7182 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7183                                            IdentifierInfo *FnName,
7184                                            SourceLocation FnLoc,
7185                                            SourceLocation RParenLoc) {
7186   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7187   if (!Size)
7188     return false;
7189 
7190   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7191   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7192     return false;
7193 
7194   SourceRange SizeRange = Size->getSourceRange();
7195   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7196       << SizeRange << FnName;
7197   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7198       << FnName << FixItHint::CreateInsertion(
7199                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7200       << FixItHint::CreateRemoval(RParenLoc);
7201   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7202       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7203       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7204                                     ")");
7205 
7206   return true;
7207 }
7208 
7209 /// \brief Determine whether the given type is or contains a dynamic class type
7210 /// (e.g., whether it has a vtable).
7211 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7212                                                      bool &IsContained) {
7213   // Look through array types while ignoring qualifiers.
7214   const Type *Ty = T->getBaseElementTypeUnsafe();
7215   IsContained = false;
7216 
7217   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7218   RD = RD ? RD->getDefinition() : nullptr;
7219   if (!RD || RD->isInvalidDecl())
7220     return nullptr;
7221 
7222   if (RD->isDynamicClass())
7223     return RD;
7224 
7225   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7226   // It's impossible for a class to transitively contain itself by value, so
7227   // infinite recursion is impossible.
7228   for (auto *FD : RD->fields()) {
7229     bool SubContained;
7230     if (const CXXRecordDecl *ContainedRD =
7231             getContainedDynamicClass(FD->getType(), SubContained)) {
7232       IsContained = true;
7233       return ContainedRD;
7234     }
7235   }
7236 
7237   return nullptr;
7238 }
7239 
7240 /// \brief If E is a sizeof expression, returns its argument expression,
7241 /// otherwise returns NULL.
7242 static const Expr *getSizeOfExprArg(const Expr *E) {
7243   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7244       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7245     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7246       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7247 
7248   return nullptr;
7249 }
7250 
7251 /// \brief If E is a sizeof expression, returns its argument type.
7252 static QualType getSizeOfArgType(const Expr *E) {
7253   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7254       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7255     if (SizeOf->getKind() == clang::UETT_SizeOf)
7256       return SizeOf->getTypeOfArgument();
7257 
7258   return QualType();
7259 }
7260 
7261 /// \brief Check for dangerous or invalid arguments to memset().
7262 ///
7263 /// This issues warnings on known problematic, dangerous or unspecified
7264 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7265 /// function calls.
7266 ///
7267 /// \param Call The call expression to diagnose.
7268 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7269                                    unsigned BId,
7270                                    IdentifierInfo *FnName) {
7271   assert(BId != 0);
7272 
7273   // It is possible to have a non-standard definition of memset.  Validate
7274   // we have enough arguments, and if not, abort further checking.
7275   unsigned ExpectedNumArgs =
7276       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7277   if (Call->getNumArgs() < ExpectedNumArgs)
7278     return;
7279 
7280   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7281                       BId == Builtin::BIstrndup ? 1 : 2);
7282   unsigned LenArg =
7283       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7284   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7285 
7286   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7287                                      Call->getLocStart(), Call->getRParenLoc()))
7288     return;
7289 
7290   // We have special checking when the length is a sizeof expression.
7291   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7292   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7293   llvm::FoldingSetNodeID SizeOfArgID;
7294 
7295   // Although widely used, 'bzero' is not a standard function. Be more strict
7296   // with the argument types before allowing diagnostics and only allow the
7297   // form bzero(ptr, sizeof(...)).
7298   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7299   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7300     return;
7301 
7302   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7303     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7304     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7305 
7306     QualType DestTy = Dest->getType();
7307     QualType PointeeTy;
7308     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7309       PointeeTy = DestPtrTy->getPointeeType();
7310 
7311       // Never warn about void type pointers. This can be used to suppress
7312       // false positives.
7313       if (PointeeTy->isVoidType())
7314         continue;
7315 
7316       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7317       // actually comparing the expressions for equality. Because computing the
7318       // expression IDs can be expensive, we only do this if the diagnostic is
7319       // enabled.
7320       if (SizeOfArg &&
7321           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7322                            SizeOfArg->getExprLoc())) {
7323         // We only compute IDs for expressions if the warning is enabled, and
7324         // cache the sizeof arg's ID.
7325         if (SizeOfArgID == llvm::FoldingSetNodeID())
7326           SizeOfArg->Profile(SizeOfArgID, Context, true);
7327         llvm::FoldingSetNodeID DestID;
7328         Dest->Profile(DestID, Context, true);
7329         if (DestID == SizeOfArgID) {
7330           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7331           //       over sizeof(src) as well.
7332           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7333           StringRef ReadableName = FnName->getName();
7334 
7335           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7336             if (UnaryOp->getOpcode() == UO_AddrOf)
7337               ActionIdx = 1; // If its an address-of operator, just remove it.
7338           if (!PointeeTy->isIncompleteType() &&
7339               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7340             ActionIdx = 2; // If the pointee's size is sizeof(char),
7341                            // suggest an explicit length.
7342 
7343           // If the function is defined as a builtin macro, do not show macro
7344           // expansion.
7345           SourceLocation SL = SizeOfArg->getExprLoc();
7346           SourceRange DSR = Dest->getSourceRange();
7347           SourceRange SSR = SizeOfArg->getSourceRange();
7348           SourceManager &SM = getSourceManager();
7349 
7350           if (SM.isMacroArgExpansion(SL)) {
7351             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7352             SL = SM.getSpellingLoc(SL);
7353             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7354                              SM.getSpellingLoc(DSR.getEnd()));
7355             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7356                              SM.getSpellingLoc(SSR.getEnd()));
7357           }
7358 
7359           DiagRuntimeBehavior(SL, SizeOfArg,
7360                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7361                                 << ReadableName
7362                                 << PointeeTy
7363                                 << DestTy
7364                                 << DSR
7365                                 << SSR);
7366           DiagRuntimeBehavior(SL, SizeOfArg,
7367                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7368                                 << ActionIdx
7369                                 << SSR);
7370 
7371           break;
7372         }
7373       }
7374 
7375       // Also check for cases where the sizeof argument is the exact same
7376       // type as the memory argument, and where it points to a user-defined
7377       // record type.
7378       if (SizeOfArgTy != QualType()) {
7379         if (PointeeTy->isRecordType() &&
7380             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7381           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7382                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7383                                 << FnName << SizeOfArgTy << ArgIdx
7384                                 << PointeeTy << Dest->getSourceRange()
7385                                 << LenExpr->getSourceRange());
7386           break;
7387         }
7388       }
7389     } else if (DestTy->isArrayType()) {
7390       PointeeTy = DestTy;
7391     }
7392 
7393     if (PointeeTy == QualType())
7394       continue;
7395 
7396     // Always complain about dynamic classes.
7397     bool IsContained;
7398     if (const CXXRecordDecl *ContainedRD =
7399             getContainedDynamicClass(PointeeTy, IsContained)) {
7400 
7401       unsigned OperationType = 0;
7402       // "overwritten" if we're warning about the destination for any call
7403       // but memcmp; otherwise a verb appropriate to the call.
7404       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7405         if (BId == Builtin::BImemcpy)
7406           OperationType = 1;
7407         else if(BId == Builtin::BImemmove)
7408           OperationType = 2;
7409         else if (BId == Builtin::BImemcmp)
7410           OperationType = 3;
7411       }
7412 
7413       DiagRuntimeBehavior(
7414         Dest->getExprLoc(), Dest,
7415         PDiag(diag::warn_dyn_class_memaccess)
7416           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7417           << FnName << IsContained << ContainedRD << OperationType
7418           << Call->getCallee()->getSourceRange());
7419     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7420              BId != Builtin::BImemset)
7421       DiagRuntimeBehavior(
7422         Dest->getExprLoc(), Dest,
7423         PDiag(diag::warn_arc_object_memaccess)
7424           << ArgIdx << FnName << PointeeTy
7425           << Call->getCallee()->getSourceRange());
7426     else
7427       continue;
7428 
7429     DiagRuntimeBehavior(
7430       Dest->getExprLoc(), Dest,
7431       PDiag(diag::note_bad_memaccess_silence)
7432         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7433     break;
7434   }
7435 }
7436 
7437 // A little helper routine: ignore addition and subtraction of integer literals.
7438 // This intentionally does not ignore all integer constant expressions because
7439 // we don't want to remove sizeof().
7440 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7441   Ex = Ex->IgnoreParenCasts();
7442 
7443   for (;;) {
7444     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7445     if (!BO || !BO->isAdditiveOp())
7446       break;
7447 
7448     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7449     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7450 
7451     if (isa<IntegerLiteral>(RHS))
7452       Ex = LHS;
7453     else if (isa<IntegerLiteral>(LHS))
7454       Ex = RHS;
7455     else
7456       break;
7457   }
7458 
7459   return Ex;
7460 }
7461 
7462 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7463                                                       ASTContext &Context) {
7464   // Only handle constant-sized or VLAs, but not flexible members.
7465   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7466     // Only issue the FIXIT for arrays of size > 1.
7467     if (CAT->getSize().getSExtValue() <= 1)
7468       return false;
7469   } else if (!Ty->isVariableArrayType()) {
7470     return false;
7471   }
7472   return true;
7473 }
7474 
7475 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7476 // be the size of the source, instead of the destination.
7477 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7478                                     IdentifierInfo *FnName) {
7479 
7480   // Don't crash if the user has the wrong number of arguments
7481   unsigned NumArgs = Call->getNumArgs();
7482   if ((NumArgs != 3) && (NumArgs != 4))
7483     return;
7484 
7485   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7486   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7487   const Expr *CompareWithSrc = nullptr;
7488 
7489   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7490                                      Call->getLocStart(), Call->getRParenLoc()))
7491     return;
7492 
7493   // Look for 'strlcpy(dst, x, sizeof(x))'
7494   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7495     CompareWithSrc = Ex;
7496   else {
7497     // Look for 'strlcpy(dst, x, strlen(x))'
7498     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7499       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7500           SizeCall->getNumArgs() == 1)
7501         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7502     }
7503   }
7504 
7505   if (!CompareWithSrc)
7506     return;
7507 
7508   // Determine if the argument to sizeof/strlen is equal to the source
7509   // argument.  In principle there's all kinds of things you could do
7510   // here, for instance creating an == expression and evaluating it with
7511   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7512   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7513   if (!SrcArgDRE)
7514     return;
7515 
7516   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7517   if (!CompareWithSrcDRE ||
7518       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7519     return;
7520 
7521   const Expr *OriginalSizeArg = Call->getArg(2);
7522   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7523     << OriginalSizeArg->getSourceRange() << FnName;
7524 
7525   // Output a FIXIT hint if the destination is an array (rather than a
7526   // pointer to an array).  This could be enhanced to handle some
7527   // pointers if we know the actual size, like if DstArg is 'array+2'
7528   // we could say 'sizeof(array)-2'.
7529   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7530   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7531     return;
7532 
7533   SmallString<128> sizeString;
7534   llvm::raw_svector_ostream OS(sizeString);
7535   OS << "sizeof(";
7536   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7537   OS << ")";
7538 
7539   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7540     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7541                                     OS.str());
7542 }
7543 
7544 /// Check if two expressions refer to the same declaration.
7545 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7546   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7547     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7548       return D1->getDecl() == D2->getDecl();
7549   return false;
7550 }
7551 
7552 static const Expr *getStrlenExprArg(const Expr *E) {
7553   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7554     const FunctionDecl *FD = CE->getDirectCallee();
7555     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7556       return nullptr;
7557     return CE->getArg(0)->IgnoreParenCasts();
7558   }
7559   return nullptr;
7560 }
7561 
7562 // Warn on anti-patterns as the 'size' argument to strncat.
7563 // The correct size argument should look like following:
7564 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7565 void Sema::CheckStrncatArguments(const CallExpr *CE,
7566                                  IdentifierInfo *FnName) {
7567   // Don't crash if the user has the wrong number of arguments.
7568   if (CE->getNumArgs() < 3)
7569     return;
7570   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7571   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7572   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7573 
7574   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7575                                      CE->getRParenLoc()))
7576     return;
7577 
7578   // Identify common expressions, which are wrongly used as the size argument
7579   // to strncat and may lead to buffer overflows.
7580   unsigned PatternType = 0;
7581   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7582     // - sizeof(dst)
7583     if (referToTheSameDecl(SizeOfArg, DstArg))
7584       PatternType = 1;
7585     // - sizeof(src)
7586     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7587       PatternType = 2;
7588   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7589     if (BE->getOpcode() == BO_Sub) {
7590       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7591       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7592       // - sizeof(dst) - strlen(dst)
7593       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7594           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7595         PatternType = 1;
7596       // - sizeof(src) - (anything)
7597       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7598         PatternType = 2;
7599     }
7600   }
7601 
7602   if (PatternType == 0)
7603     return;
7604 
7605   // Generate the diagnostic.
7606   SourceLocation SL = LenArg->getLocStart();
7607   SourceRange SR = LenArg->getSourceRange();
7608   SourceManager &SM = getSourceManager();
7609 
7610   // If the function is defined as a builtin macro, do not show macro expansion.
7611   if (SM.isMacroArgExpansion(SL)) {
7612     SL = SM.getSpellingLoc(SL);
7613     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7614                      SM.getSpellingLoc(SR.getEnd()));
7615   }
7616 
7617   // Check if the destination is an array (rather than a pointer to an array).
7618   QualType DstTy = DstArg->getType();
7619   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7620                                                                     Context);
7621   if (!isKnownSizeArray) {
7622     if (PatternType == 1)
7623       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7624     else
7625       Diag(SL, diag::warn_strncat_src_size) << SR;
7626     return;
7627   }
7628 
7629   if (PatternType == 1)
7630     Diag(SL, diag::warn_strncat_large_size) << SR;
7631   else
7632     Diag(SL, diag::warn_strncat_src_size) << SR;
7633 
7634   SmallString<128> sizeString;
7635   llvm::raw_svector_ostream OS(sizeString);
7636   OS << "sizeof(";
7637   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7638   OS << ") - ";
7639   OS << "strlen(";
7640   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7641   OS << ") - 1";
7642 
7643   Diag(SL, diag::note_strncat_wrong_size)
7644     << FixItHint::CreateReplacement(SR, OS.str());
7645 }
7646 
7647 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7648 
7649 static const Expr *EvalVal(const Expr *E,
7650                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7651                            const Decl *ParentDecl);
7652 static const Expr *EvalAddr(const Expr *E,
7653                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7654                             const Decl *ParentDecl);
7655 
7656 /// CheckReturnStackAddr - Check if a return statement returns the address
7657 ///   of a stack variable.
7658 static void
7659 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7660                      SourceLocation ReturnLoc) {
7661 
7662   const Expr *stackE = nullptr;
7663   SmallVector<const DeclRefExpr *, 8> refVars;
7664 
7665   // Perform checking for returned stack addresses, local blocks,
7666   // label addresses or references to temporaries.
7667   if (lhsType->isPointerType() ||
7668       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7669     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7670   } else if (lhsType->isReferenceType()) {
7671     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7672   }
7673 
7674   if (!stackE)
7675     return; // Nothing suspicious was found.
7676 
7677   // Parameters are initialized in the calling scope, so taking the address
7678   // of a parameter reference doesn't need a warning.
7679   for (auto *DRE : refVars)
7680     if (isa<ParmVarDecl>(DRE->getDecl()))
7681       return;
7682 
7683   SourceLocation diagLoc;
7684   SourceRange diagRange;
7685   if (refVars.empty()) {
7686     diagLoc = stackE->getLocStart();
7687     diagRange = stackE->getSourceRange();
7688   } else {
7689     // We followed through a reference variable. 'stackE' contains the
7690     // problematic expression but we will warn at the return statement pointing
7691     // at the reference variable. We will later display the "trail" of
7692     // reference variables using notes.
7693     diagLoc = refVars[0]->getLocStart();
7694     diagRange = refVars[0]->getSourceRange();
7695   }
7696 
7697   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7698     // address of local var
7699     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7700      << DR->getDecl()->getDeclName() << diagRange;
7701   } else if (isa<BlockExpr>(stackE)) { // local block.
7702     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7703   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7704     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7705   } else { // local temporary.
7706     // If there is an LValue->RValue conversion, then the value of the
7707     // reference type is used, not the reference.
7708     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7709       if (ICE->getCastKind() == CK_LValueToRValue) {
7710         return;
7711       }
7712     }
7713     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7714      << lhsType->isReferenceType() << diagRange;
7715   }
7716 
7717   // Display the "trail" of reference variables that we followed until we
7718   // found the problematic expression using notes.
7719   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7720     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7721     // If this var binds to another reference var, show the range of the next
7722     // var, otherwise the var binds to the problematic expression, in which case
7723     // show the range of the expression.
7724     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7725                                     : stackE->getSourceRange();
7726     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7727         << VD->getDeclName() << range;
7728   }
7729 }
7730 
7731 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7732 ///  check if the expression in a return statement evaluates to an address
7733 ///  to a location on the stack, a local block, an address of a label, or a
7734 ///  reference to local temporary. The recursion is used to traverse the
7735 ///  AST of the return expression, with recursion backtracking when we
7736 ///  encounter a subexpression that (1) clearly does not lead to one of the
7737 ///  above problematic expressions (2) is something we cannot determine leads to
7738 ///  a problematic expression based on such local checking.
7739 ///
7740 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7741 ///  the expression that they point to. Such variables are added to the
7742 ///  'refVars' vector so that we know what the reference variable "trail" was.
7743 ///
7744 ///  EvalAddr processes expressions that are pointers that are used as
7745 ///  references (and not L-values).  EvalVal handles all other values.
7746 ///  At the base case of the recursion is a check for the above problematic
7747 ///  expressions.
7748 ///
7749 ///  This implementation handles:
7750 ///
7751 ///   * pointer-to-pointer casts
7752 ///   * implicit conversions from array references to pointers
7753 ///   * taking the address of fields
7754 ///   * arbitrary interplay between "&" and "*" operators
7755 ///   * pointer arithmetic from an address of a stack variable
7756 ///   * taking the address of an array element where the array is on the stack
7757 static const Expr *EvalAddr(const Expr *E,
7758                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7759                             const Decl *ParentDecl) {
7760   if (E->isTypeDependent())
7761     return nullptr;
7762 
7763   // We should only be called for evaluating pointer expressions.
7764   assert((E->getType()->isAnyPointerType() ||
7765           E->getType()->isBlockPointerType() ||
7766           E->getType()->isObjCQualifiedIdType()) &&
7767          "EvalAddr only works on pointers");
7768 
7769   E = E->IgnoreParens();
7770 
7771   // Our "symbolic interpreter" is just a dispatch off the currently
7772   // viewed AST node.  We then recursively traverse the AST by calling
7773   // EvalAddr and EvalVal appropriately.
7774   switch (E->getStmtClass()) {
7775   case Stmt::DeclRefExprClass: {
7776     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7777 
7778     // If we leave the immediate function, the lifetime isn't about to end.
7779     if (DR->refersToEnclosingVariableOrCapture())
7780       return nullptr;
7781 
7782     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7783       // If this is a reference variable, follow through to the expression that
7784       // it points to.
7785       if (V->hasLocalStorage() &&
7786           V->getType()->isReferenceType() && V->hasInit()) {
7787         // Add the reference variable to the "trail".
7788         refVars.push_back(DR);
7789         return EvalAddr(V->getInit(), refVars, ParentDecl);
7790       }
7791 
7792     return nullptr;
7793   }
7794 
7795   case Stmt::UnaryOperatorClass: {
7796     // The only unary operator that make sense to handle here
7797     // is AddrOf.  All others don't make sense as pointers.
7798     const UnaryOperator *U = cast<UnaryOperator>(E);
7799 
7800     if (U->getOpcode() == UO_AddrOf)
7801       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7802     return nullptr;
7803   }
7804 
7805   case Stmt::BinaryOperatorClass: {
7806     // Handle pointer arithmetic.  All other binary operators are not valid
7807     // in this context.
7808     const BinaryOperator *B = cast<BinaryOperator>(E);
7809     BinaryOperatorKind op = B->getOpcode();
7810 
7811     if (op != BO_Add && op != BO_Sub)
7812       return nullptr;
7813 
7814     const Expr *Base = B->getLHS();
7815 
7816     // Determine which argument is the real pointer base.  It could be
7817     // the RHS argument instead of the LHS.
7818     if (!Base->getType()->isPointerType())
7819       Base = B->getRHS();
7820 
7821     assert(Base->getType()->isPointerType());
7822     return EvalAddr(Base, refVars, ParentDecl);
7823   }
7824 
7825   // For conditional operators we need to see if either the LHS or RHS are
7826   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7827   case Stmt::ConditionalOperatorClass: {
7828     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7829 
7830     // Handle the GNU extension for missing LHS.
7831     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7832     if (const Expr *LHSExpr = C->getLHS()) {
7833       // In C++, we can have a throw-expression, which has 'void' type.
7834       if (!LHSExpr->getType()->isVoidType())
7835         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7836           return LHS;
7837     }
7838 
7839     // In C++, we can have a throw-expression, which has 'void' type.
7840     if (C->getRHS()->getType()->isVoidType())
7841       return nullptr;
7842 
7843     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7844   }
7845 
7846   case Stmt::BlockExprClass:
7847     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7848       return E; // local block.
7849     return nullptr;
7850 
7851   case Stmt::AddrLabelExprClass:
7852     return E; // address of label.
7853 
7854   case Stmt::ExprWithCleanupsClass:
7855     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7856                     ParentDecl);
7857 
7858   // For casts, we need to handle conversions from arrays to
7859   // pointer values, and pointer-to-pointer conversions.
7860   case Stmt::ImplicitCastExprClass:
7861   case Stmt::CStyleCastExprClass:
7862   case Stmt::CXXFunctionalCastExprClass:
7863   case Stmt::ObjCBridgedCastExprClass:
7864   case Stmt::CXXStaticCastExprClass:
7865   case Stmt::CXXDynamicCastExprClass:
7866   case Stmt::CXXConstCastExprClass:
7867   case Stmt::CXXReinterpretCastExprClass: {
7868     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7869     switch (cast<CastExpr>(E)->getCastKind()) {
7870     case CK_LValueToRValue:
7871     case CK_NoOp:
7872     case CK_BaseToDerived:
7873     case CK_DerivedToBase:
7874     case CK_UncheckedDerivedToBase:
7875     case CK_Dynamic:
7876     case CK_CPointerToObjCPointerCast:
7877     case CK_BlockPointerToObjCPointerCast:
7878     case CK_AnyPointerToBlockPointerCast:
7879       return EvalAddr(SubExpr, refVars, ParentDecl);
7880 
7881     case CK_ArrayToPointerDecay:
7882       return EvalVal(SubExpr, refVars, ParentDecl);
7883 
7884     case CK_BitCast:
7885       if (SubExpr->getType()->isAnyPointerType() ||
7886           SubExpr->getType()->isBlockPointerType() ||
7887           SubExpr->getType()->isObjCQualifiedIdType())
7888         return EvalAddr(SubExpr, refVars, ParentDecl);
7889       else
7890         return nullptr;
7891 
7892     default:
7893       return nullptr;
7894     }
7895   }
7896 
7897   case Stmt::MaterializeTemporaryExprClass:
7898     if (const Expr *Result =
7899             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7900                      refVars, ParentDecl))
7901       return Result;
7902     return E;
7903 
7904   // Everything else: we simply don't reason about them.
7905   default:
7906     return nullptr;
7907   }
7908 }
7909 
7910 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7911 ///   See the comments for EvalAddr for more details.
7912 static const Expr *EvalVal(const Expr *E,
7913                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7914                            const Decl *ParentDecl) {
7915   do {
7916     // We should only be called for evaluating non-pointer expressions, or
7917     // expressions with a pointer type that are not used as references but
7918     // instead
7919     // are l-values (e.g., DeclRefExpr with a pointer type).
7920 
7921     // Our "symbolic interpreter" is just a dispatch off the currently
7922     // viewed AST node.  We then recursively traverse the AST by calling
7923     // EvalAddr and EvalVal appropriately.
7924 
7925     E = E->IgnoreParens();
7926     switch (E->getStmtClass()) {
7927     case Stmt::ImplicitCastExprClass: {
7928       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7929       if (IE->getValueKind() == VK_LValue) {
7930         E = IE->getSubExpr();
7931         continue;
7932       }
7933       return nullptr;
7934     }
7935 
7936     case Stmt::ExprWithCleanupsClass:
7937       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7938                      ParentDecl);
7939 
7940     case Stmt::DeclRefExprClass: {
7941       // When we hit a DeclRefExpr we are looking at code that refers to a
7942       // variable's name. If it's not a reference variable we check if it has
7943       // local storage within the function, and if so, return the expression.
7944       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7945 
7946       // If we leave the immediate function, the lifetime isn't about to end.
7947       if (DR->refersToEnclosingVariableOrCapture())
7948         return nullptr;
7949 
7950       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7951         // Check if it refers to itself, e.g. "int& i = i;".
7952         if (V == ParentDecl)
7953           return DR;
7954 
7955         if (V->hasLocalStorage()) {
7956           if (!V->getType()->isReferenceType())
7957             return DR;
7958 
7959           // Reference variable, follow through to the expression that
7960           // it points to.
7961           if (V->hasInit()) {
7962             // Add the reference variable to the "trail".
7963             refVars.push_back(DR);
7964             return EvalVal(V->getInit(), refVars, V);
7965           }
7966         }
7967       }
7968 
7969       return nullptr;
7970     }
7971 
7972     case Stmt::UnaryOperatorClass: {
7973       // The only unary operator that make sense to handle here
7974       // is Deref.  All others don't resolve to a "name."  This includes
7975       // handling all sorts of rvalues passed to a unary operator.
7976       const UnaryOperator *U = cast<UnaryOperator>(E);
7977 
7978       if (U->getOpcode() == UO_Deref)
7979         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7980 
7981       return nullptr;
7982     }
7983 
7984     case Stmt::ArraySubscriptExprClass: {
7985       // Array subscripts are potential references to data on the stack.  We
7986       // retrieve the DeclRefExpr* for the array variable if it indeed
7987       // has local storage.
7988       const auto *ASE = cast<ArraySubscriptExpr>(E);
7989       if (ASE->isTypeDependent())
7990         return nullptr;
7991       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7992     }
7993 
7994     case Stmt::OMPArraySectionExprClass: {
7995       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7996                       ParentDecl);
7997     }
7998 
7999     case Stmt::ConditionalOperatorClass: {
8000       // For conditional operators we need to see if either the LHS or RHS are
8001       // non-NULL Expr's.  If one is non-NULL, we return it.
8002       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8003 
8004       // Handle the GNU extension for missing LHS.
8005       if (const Expr *LHSExpr = C->getLHS()) {
8006         // In C++, we can have a throw-expression, which has 'void' type.
8007         if (!LHSExpr->getType()->isVoidType())
8008           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8009             return LHS;
8010       }
8011 
8012       // In C++, we can have a throw-expression, which has 'void' type.
8013       if (C->getRHS()->getType()->isVoidType())
8014         return nullptr;
8015 
8016       return EvalVal(C->getRHS(), refVars, ParentDecl);
8017     }
8018 
8019     // Accesses to members are potential references to data on the stack.
8020     case Stmt::MemberExprClass: {
8021       const MemberExpr *M = cast<MemberExpr>(E);
8022 
8023       // Check for indirect access.  We only want direct field accesses.
8024       if (M->isArrow())
8025         return nullptr;
8026 
8027       // Check whether the member type is itself a reference, in which case
8028       // we're not going to refer to the member, but to what the member refers
8029       // to.
8030       if (M->getMemberDecl()->getType()->isReferenceType())
8031         return nullptr;
8032 
8033       return EvalVal(M->getBase(), refVars, ParentDecl);
8034     }
8035 
8036     case Stmt::MaterializeTemporaryExprClass:
8037       if (const Expr *Result =
8038               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8039                       refVars, ParentDecl))
8040         return Result;
8041       return E;
8042 
8043     default:
8044       // Check that we don't return or take the address of a reference to a
8045       // temporary. This is only useful in C++.
8046       if (!E->isTypeDependent() && E->isRValue())
8047         return E;
8048 
8049       // Everything else: we simply don't reason about them.
8050       return nullptr;
8051     }
8052   } while (true);
8053 }
8054 
8055 void
8056 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8057                          SourceLocation ReturnLoc,
8058                          bool isObjCMethod,
8059                          const AttrVec *Attrs,
8060                          const FunctionDecl *FD) {
8061   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8062 
8063   // Check if the return value is null but should not be.
8064   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8065        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8066       CheckNonNullExpr(*this, RetValExp))
8067     Diag(ReturnLoc, diag::warn_null_ret)
8068       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8069 
8070   // C++11 [basic.stc.dynamic.allocation]p4:
8071   //   If an allocation function declared with a non-throwing
8072   //   exception-specification fails to allocate storage, it shall return
8073   //   a null pointer. Any other allocation function that fails to allocate
8074   //   storage shall indicate failure only by throwing an exception [...]
8075   if (FD) {
8076     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8077     if (Op == OO_New || Op == OO_Array_New) {
8078       const FunctionProtoType *Proto
8079         = FD->getType()->castAs<FunctionProtoType>();
8080       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8081           CheckNonNullExpr(*this, RetValExp))
8082         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8083           << FD << getLangOpts().CPlusPlus11;
8084     }
8085   }
8086 }
8087 
8088 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8089 
8090 /// Check for comparisons of floating point operands using != and ==.
8091 /// Issue a warning if these are no self-comparisons, as they are not likely
8092 /// to do what the programmer intended.
8093 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8094   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8095   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8096 
8097   // Special case: check for x == x (which is OK).
8098   // Do not emit warnings for such cases.
8099   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8100     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8101       if (DRL->getDecl() == DRR->getDecl())
8102         return;
8103 
8104   // Special case: check for comparisons against literals that can be exactly
8105   //  represented by APFloat.  In such cases, do not emit a warning.  This
8106   //  is a heuristic: often comparison against such literals are used to
8107   //  detect if a value in a variable has not changed.  This clearly can
8108   //  lead to false negatives.
8109   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8110     if (FLL->isExact())
8111       return;
8112   } else
8113     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8114       if (FLR->isExact())
8115         return;
8116 
8117   // Check for comparisons with builtin types.
8118   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8119     if (CL->getBuiltinCallee())
8120       return;
8121 
8122   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8123     if (CR->getBuiltinCallee())
8124       return;
8125 
8126   // Emit the diagnostic.
8127   Diag(Loc, diag::warn_floatingpoint_eq)
8128     << LHS->getSourceRange() << RHS->getSourceRange();
8129 }
8130 
8131 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8132 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8133 
8134 namespace {
8135 
8136 /// Structure recording the 'active' range of an integer-valued
8137 /// expression.
8138 struct IntRange {
8139   /// The number of bits active in the int.
8140   unsigned Width;
8141 
8142   /// True if the int is known not to have negative values.
8143   bool NonNegative;
8144 
8145   IntRange(unsigned Width, bool NonNegative)
8146     : Width(Width), NonNegative(NonNegative)
8147   {}
8148 
8149   /// Returns the range of the bool type.
8150   static IntRange forBoolType() {
8151     return IntRange(1, true);
8152   }
8153 
8154   /// Returns the range of an opaque value of the given integral type.
8155   static IntRange forValueOfType(ASTContext &C, QualType T) {
8156     return forValueOfCanonicalType(C,
8157                           T->getCanonicalTypeInternal().getTypePtr());
8158   }
8159 
8160   /// Returns the range of an opaque value of a canonical integral type.
8161   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8162     assert(T->isCanonicalUnqualified());
8163 
8164     if (const VectorType *VT = dyn_cast<VectorType>(T))
8165       T = VT->getElementType().getTypePtr();
8166     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8167       T = CT->getElementType().getTypePtr();
8168     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8169       T = AT->getValueType().getTypePtr();
8170 
8171     // For enum types, use the known bit width of the enumerators.
8172     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8173       EnumDecl *Enum = ET->getDecl();
8174       // In C++11, enums without definitions can have an explicitly specified
8175       // underlying type.  Use this type to compute the range.
8176       if (!Enum->isCompleteDefinition())
8177         return IntRange(C.getIntWidth(QualType(T, 0)),
8178                         !ET->isSignedIntegerOrEnumerationType());
8179 
8180       unsigned NumPositive = Enum->getNumPositiveBits();
8181       unsigned NumNegative = Enum->getNumNegativeBits();
8182 
8183       if (NumNegative == 0)
8184         return IntRange(NumPositive, true/*NonNegative*/);
8185       else
8186         return IntRange(std::max(NumPositive + 1, NumNegative),
8187                         false/*NonNegative*/);
8188     }
8189 
8190     const BuiltinType *BT = cast<BuiltinType>(T);
8191     assert(BT->isInteger());
8192 
8193     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8194   }
8195 
8196   /// Returns the "target" range of a canonical integral type, i.e.
8197   /// the range of values expressible in the type.
8198   ///
8199   /// This matches forValueOfCanonicalType except that enums have the
8200   /// full range of their type, not the range of their enumerators.
8201   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8202     assert(T->isCanonicalUnqualified());
8203 
8204     if (const VectorType *VT = dyn_cast<VectorType>(T))
8205       T = VT->getElementType().getTypePtr();
8206     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8207       T = CT->getElementType().getTypePtr();
8208     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8209       T = AT->getValueType().getTypePtr();
8210     if (const EnumType *ET = dyn_cast<EnumType>(T))
8211       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8212 
8213     const BuiltinType *BT = cast<BuiltinType>(T);
8214     assert(BT->isInteger());
8215 
8216     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8217   }
8218 
8219   /// Returns the supremum of two ranges: i.e. their conservative merge.
8220   static IntRange join(IntRange L, IntRange R) {
8221     return IntRange(std::max(L.Width, R.Width),
8222                     L.NonNegative && R.NonNegative);
8223   }
8224 
8225   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8226   static IntRange meet(IntRange L, IntRange R) {
8227     return IntRange(std::min(L.Width, R.Width),
8228                     L.NonNegative || R.NonNegative);
8229   }
8230 };
8231 
8232 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8233   if (value.isSigned() && value.isNegative())
8234     return IntRange(value.getMinSignedBits(), false);
8235 
8236   if (value.getBitWidth() > MaxWidth)
8237     value = value.trunc(MaxWidth);
8238 
8239   // isNonNegative() just checks the sign bit without considering
8240   // signedness.
8241   return IntRange(value.getActiveBits(), true);
8242 }
8243 
8244 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8245                        unsigned MaxWidth) {
8246   if (result.isInt())
8247     return GetValueRange(C, result.getInt(), MaxWidth);
8248 
8249   if (result.isVector()) {
8250     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8251     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8252       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8253       R = IntRange::join(R, El);
8254     }
8255     return R;
8256   }
8257 
8258   if (result.isComplexInt()) {
8259     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8260     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8261     return IntRange::join(R, I);
8262   }
8263 
8264   // This can happen with lossless casts to intptr_t of "based" lvalues.
8265   // Assume it might use arbitrary bits.
8266   // FIXME: The only reason we need to pass the type in here is to get
8267   // the sign right on this one case.  It would be nice if APValue
8268   // preserved this.
8269   assert(result.isLValue() || result.isAddrLabelDiff());
8270   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8271 }
8272 
8273 QualType GetExprType(const Expr *E) {
8274   QualType Ty = E->getType();
8275   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8276     Ty = AtomicRHS->getValueType();
8277   return Ty;
8278 }
8279 
8280 /// Pseudo-evaluate the given integer expression, estimating the
8281 /// range of values it might take.
8282 ///
8283 /// \param MaxWidth - the width to which the value will be truncated
8284 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8285   E = E->IgnoreParens();
8286 
8287   // Try a full evaluation first.
8288   Expr::EvalResult result;
8289   if (E->EvaluateAsRValue(result, C))
8290     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8291 
8292   // I think we only want to look through implicit casts here; if the
8293   // user has an explicit widening cast, we should treat the value as
8294   // being of the new, wider type.
8295   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8296     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8297       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8298 
8299     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8300 
8301     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8302                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8303 
8304     // Assume that non-integer casts can span the full range of the type.
8305     if (!isIntegerCast)
8306       return OutputTypeRange;
8307 
8308     IntRange SubRange
8309       = GetExprRange(C, CE->getSubExpr(),
8310                      std::min(MaxWidth, OutputTypeRange.Width));
8311 
8312     // Bail out if the subexpr's range is as wide as the cast type.
8313     if (SubRange.Width >= OutputTypeRange.Width)
8314       return OutputTypeRange;
8315 
8316     // Otherwise, we take the smaller width, and we're non-negative if
8317     // either the output type or the subexpr is.
8318     return IntRange(SubRange.Width,
8319                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8320   }
8321 
8322   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8323     // If we can fold the condition, just take that operand.
8324     bool CondResult;
8325     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8326       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8327                                         : CO->getFalseExpr(),
8328                           MaxWidth);
8329 
8330     // Otherwise, conservatively merge.
8331     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8332     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8333     return IntRange::join(L, R);
8334   }
8335 
8336   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8337     switch (BO->getOpcode()) {
8338 
8339     // Boolean-valued operations are single-bit and positive.
8340     case BO_LAnd:
8341     case BO_LOr:
8342     case BO_LT:
8343     case BO_GT:
8344     case BO_LE:
8345     case BO_GE:
8346     case BO_EQ:
8347     case BO_NE:
8348       return IntRange::forBoolType();
8349 
8350     // The type of the assignments is the type of the LHS, so the RHS
8351     // is not necessarily the same type.
8352     case BO_MulAssign:
8353     case BO_DivAssign:
8354     case BO_RemAssign:
8355     case BO_AddAssign:
8356     case BO_SubAssign:
8357     case BO_XorAssign:
8358     case BO_OrAssign:
8359       // TODO: bitfields?
8360       return IntRange::forValueOfType(C, GetExprType(E));
8361 
8362     // Simple assignments just pass through the RHS, which will have
8363     // been coerced to the LHS type.
8364     case BO_Assign:
8365       // TODO: bitfields?
8366       return GetExprRange(C, BO->getRHS(), MaxWidth);
8367 
8368     // Operations with opaque sources are black-listed.
8369     case BO_PtrMemD:
8370     case BO_PtrMemI:
8371       return IntRange::forValueOfType(C, GetExprType(E));
8372 
8373     // Bitwise-and uses the *infinum* of the two source ranges.
8374     case BO_And:
8375     case BO_AndAssign:
8376       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8377                             GetExprRange(C, BO->getRHS(), MaxWidth));
8378 
8379     // Left shift gets black-listed based on a judgement call.
8380     case BO_Shl:
8381       // ...except that we want to treat '1 << (blah)' as logically
8382       // positive.  It's an important idiom.
8383       if (IntegerLiteral *I
8384             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8385         if (I->getValue() == 1) {
8386           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8387           return IntRange(R.Width, /*NonNegative*/ true);
8388         }
8389       }
8390       // fallthrough
8391 
8392     case BO_ShlAssign:
8393       return IntRange::forValueOfType(C, GetExprType(E));
8394 
8395     // Right shift by a constant can narrow its left argument.
8396     case BO_Shr:
8397     case BO_ShrAssign: {
8398       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8399 
8400       // If the shift amount is a positive constant, drop the width by
8401       // that much.
8402       llvm::APSInt shift;
8403       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8404           shift.isNonNegative()) {
8405         unsigned zext = shift.getZExtValue();
8406         if (zext >= L.Width)
8407           L.Width = (L.NonNegative ? 0 : 1);
8408         else
8409           L.Width -= zext;
8410       }
8411 
8412       return L;
8413     }
8414 
8415     // Comma acts as its right operand.
8416     case BO_Comma:
8417       return GetExprRange(C, BO->getRHS(), MaxWidth);
8418 
8419     // Black-list pointer subtractions.
8420     case BO_Sub:
8421       if (BO->getLHS()->getType()->isPointerType())
8422         return IntRange::forValueOfType(C, GetExprType(E));
8423       break;
8424 
8425     // The width of a division result is mostly determined by the size
8426     // of the LHS.
8427     case BO_Div: {
8428       // Don't 'pre-truncate' the operands.
8429       unsigned opWidth = C.getIntWidth(GetExprType(E));
8430       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8431 
8432       // If the divisor is constant, use that.
8433       llvm::APSInt divisor;
8434       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8435         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8436         if (log2 >= L.Width)
8437           L.Width = (L.NonNegative ? 0 : 1);
8438         else
8439           L.Width = std::min(L.Width - log2, MaxWidth);
8440         return L;
8441       }
8442 
8443       // Otherwise, just use the LHS's width.
8444       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8445       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8446     }
8447 
8448     // The result of a remainder can't be larger than the result of
8449     // either side.
8450     case BO_Rem: {
8451       // Don't 'pre-truncate' the operands.
8452       unsigned opWidth = C.getIntWidth(GetExprType(E));
8453       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8454       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8455 
8456       IntRange meet = IntRange::meet(L, R);
8457       meet.Width = std::min(meet.Width, MaxWidth);
8458       return meet;
8459     }
8460 
8461     // The default behavior is okay for these.
8462     case BO_Mul:
8463     case BO_Add:
8464     case BO_Xor:
8465     case BO_Or:
8466       break;
8467     }
8468 
8469     // The default case is to treat the operation as if it were closed
8470     // on the narrowest type that encompasses both operands.
8471     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8472     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8473     return IntRange::join(L, R);
8474   }
8475 
8476   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8477     switch (UO->getOpcode()) {
8478     // Boolean-valued operations are white-listed.
8479     case UO_LNot:
8480       return IntRange::forBoolType();
8481 
8482     // Operations with opaque sources are black-listed.
8483     case UO_Deref:
8484     case UO_AddrOf: // should be impossible
8485       return IntRange::forValueOfType(C, GetExprType(E));
8486 
8487     default:
8488       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8489     }
8490   }
8491 
8492   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8493     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8494 
8495   if (const auto *BitField = E->getSourceBitField())
8496     return IntRange(BitField->getBitWidthValue(C),
8497                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8498 
8499   return IntRange::forValueOfType(C, GetExprType(E));
8500 }
8501 
8502 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8503   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8504 }
8505 
8506 /// Checks whether the given value, which currently has the given
8507 /// source semantics, has the same value when coerced through the
8508 /// target semantics.
8509 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8510                           const llvm::fltSemantics &Src,
8511                           const llvm::fltSemantics &Tgt) {
8512   llvm::APFloat truncated = value;
8513 
8514   bool ignored;
8515   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8516   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8517 
8518   return truncated.bitwiseIsEqual(value);
8519 }
8520 
8521 /// Checks whether the given value, which currently has the given
8522 /// source semantics, has the same value when coerced through the
8523 /// target semantics.
8524 ///
8525 /// The value might be a vector of floats (or a complex number).
8526 bool IsSameFloatAfterCast(const APValue &value,
8527                           const llvm::fltSemantics &Src,
8528                           const llvm::fltSemantics &Tgt) {
8529   if (value.isFloat())
8530     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8531 
8532   if (value.isVector()) {
8533     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8534       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8535         return false;
8536     return true;
8537   }
8538 
8539   assert(value.isComplexFloat());
8540   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8541           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8542 }
8543 
8544 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8545 
8546 bool IsZero(Sema &S, Expr *E) {
8547   // Suppress cases where we are comparing against an enum constant.
8548   if (const DeclRefExpr *DR =
8549       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8550     if (isa<EnumConstantDecl>(DR->getDecl()))
8551       return false;
8552 
8553   // Suppress cases where the '0' value is expanded from a macro.
8554   if (E->getLocStart().isMacroID())
8555     return false;
8556 
8557   llvm::APSInt Value;
8558   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8559 }
8560 
8561 bool HasEnumType(Expr *E) {
8562   // Strip off implicit integral promotions.
8563   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8564     if (ICE->getCastKind() != CK_IntegralCast &&
8565         ICE->getCastKind() != CK_NoOp)
8566       break;
8567     E = ICE->getSubExpr();
8568   }
8569 
8570   return E->getType()->isEnumeralType();
8571 }
8572 
8573 bool isNonBooleanUnsignedValue(Expr *E) {
8574   // We are checking that the expression is not known to have boolean value,
8575   // is an integer type; and is either unsigned after implicit casts,
8576   // or was unsigned before implicit casts.
8577   return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType() &&
8578          (!E->getType()->isSignedIntegerType() ||
8579           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8580 }
8581 
8582 bool CheckTautologicalComparisonWithZero(Sema &S, BinaryOperator *E) {
8583   // Disable warning in template instantiations.
8584   if (S.inTemplateInstantiation())
8585     return false;
8586 
8587   // bool values are handled by DiagnoseOutOfRangeComparison().
8588 
8589   BinaryOperatorKind Op = E->getOpcode();
8590   if (E->isValueDependent())
8591     return false;
8592 
8593   Expr *LHS = E->getLHS();
8594   Expr *RHS = E->getRHS();
8595 
8596   bool Match = true;
8597 
8598   if (Op == BO_LT && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
8599     S.Diag(E->getOperatorLoc(),
8600            HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8601                             : diag::warn_lunsigned_always_true_comparison)
8602         << "< 0" << false << LHS->getSourceRange() << RHS->getSourceRange();
8603   } else if (Op == BO_GE && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
8604     S.Diag(E->getOperatorLoc(),
8605            HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8606                             : diag::warn_lunsigned_always_true_comparison)
8607         << ">= 0" << true << LHS->getSourceRange() << RHS->getSourceRange();
8608   } else if (Op == BO_GT && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
8609     S.Diag(E->getOperatorLoc(),
8610            HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8611                             : diag::warn_runsigned_always_true_comparison)
8612         << "0 >" << false << LHS->getSourceRange() << RHS->getSourceRange();
8613   } else if (Op == BO_LE && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
8614     S.Diag(E->getOperatorLoc(),
8615            HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8616                             : diag::warn_runsigned_always_true_comparison)
8617         << "0 <=" << true << LHS->getSourceRange() << RHS->getSourceRange();
8618   } else
8619     Match = false;
8620 
8621   return Match;
8622 }
8623 
8624 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8625                                   Expr *Other, const llvm::APSInt &Value,
8626                                   bool RhsConstant) {
8627   // Disable warning in template instantiations.
8628   if (S.inTemplateInstantiation())
8629     return;
8630 
8631   // TODO: Investigate using GetExprRange() to get tighter bounds
8632   // on the bit ranges.
8633   QualType OtherT = Other->getType();
8634   if (const auto *AT = OtherT->getAs<AtomicType>())
8635     OtherT = AT->getValueType();
8636   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8637   unsigned OtherWidth = OtherRange.Width;
8638 
8639   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8640 
8641   // 0 values are handled later by CheckTautologicalComparisonWithZero().
8642   if ((Value == 0) && (!OtherIsBooleanType))
8643     return;
8644 
8645   BinaryOperatorKind op = E->getOpcode();
8646   bool IsTrue = true;
8647 
8648   // Used for diagnostic printout.
8649   enum {
8650     LiteralConstant = 0,
8651     CXXBoolLiteralTrue,
8652     CXXBoolLiteralFalse
8653   } LiteralOrBoolConstant = LiteralConstant;
8654 
8655   if (!OtherIsBooleanType) {
8656     QualType ConstantT = Constant->getType();
8657     QualType CommonT = E->getLHS()->getType();
8658 
8659     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8660       return;
8661     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8662            "comparison with non-integer type");
8663 
8664     bool ConstantSigned = ConstantT->isSignedIntegerType();
8665     bool CommonSigned = CommonT->isSignedIntegerType();
8666 
8667     bool EqualityOnly = false;
8668 
8669     if (CommonSigned) {
8670       // The common type is signed, therefore no signed to unsigned conversion.
8671       if (!OtherRange.NonNegative) {
8672         // Check that the constant is representable in type OtherT.
8673         if (ConstantSigned) {
8674           if (OtherWidth >= Value.getMinSignedBits())
8675             return;
8676         } else { // !ConstantSigned
8677           if (OtherWidth >= Value.getActiveBits() + 1)
8678             return;
8679         }
8680       } else { // !OtherSigned
8681                // Check that the constant is representable in type OtherT.
8682         // Negative values are out of range.
8683         if (ConstantSigned) {
8684           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8685             return;
8686         } else { // !ConstantSigned
8687           if (OtherWidth >= Value.getActiveBits())
8688             return;
8689         }
8690       }
8691     } else { // !CommonSigned
8692       if (OtherRange.NonNegative) {
8693         if (OtherWidth >= Value.getActiveBits())
8694           return;
8695       } else { // OtherSigned
8696         assert(!ConstantSigned &&
8697                "Two signed types converted to unsigned types.");
8698         // Check to see if the constant is representable in OtherT.
8699         if (OtherWidth > Value.getActiveBits())
8700           return;
8701         // Check to see if the constant is equivalent to a negative value
8702         // cast to CommonT.
8703         if (S.Context.getIntWidth(ConstantT) ==
8704                 S.Context.getIntWidth(CommonT) &&
8705             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8706           return;
8707         // The constant value rests between values that OtherT can represent
8708         // after conversion.  Relational comparison still works, but equality
8709         // comparisons will be tautological.
8710         EqualityOnly = true;
8711       }
8712     }
8713 
8714     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8715 
8716     if (op == BO_EQ || op == BO_NE) {
8717       IsTrue = op == BO_NE;
8718     } else if (EqualityOnly) {
8719       return;
8720     } else if (RhsConstant) {
8721       if (op == BO_GT || op == BO_GE)
8722         IsTrue = !PositiveConstant;
8723       else // op == BO_LT || op == BO_LE
8724         IsTrue = PositiveConstant;
8725     } else {
8726       if (op == BO_LT || op == BO_LE)
8727         IsTrue = !PositiveConstant;
8728       else // op == BO_GT || op == BO_GE
8729         IsTrue = PositiveConstant;
8730     }
8731   } else {
8732     // Other isKnownToHaveBooleanValue
8733     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8734     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8735     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8736 
8737     static const struct LinkedConditions {
8738       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8739       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8740       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8741       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8742       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8743       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8744 
8745     } TruthTable = {
8746         // Constant on LHS.              | Constant on RHS.              |
8747         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8748         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8749         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8750         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8751         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8752         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8753         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8754       };
8755 
8756     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8757 
8758     enum ConstantValue ConstVal = Zero;
8759     if (Value.isUnsigned() || Value.isNonNegative()) {
8760       if (Value == 0) {
8761         LiteralOrBoolConstant =
8762             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8763         ConstVal = Zero;
8764       } else if (Value == 1) {
8765         LiteralOrBoolConstant =
8766             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8767         ConstVal = One;
8768       } else {
8769         LiteralOrBoolConstant = LiteralConstant;
8770         ConstVal = GT_One;
8771       }
8772     } else {
8773       ConstVal = LT_Zero;
8774     }
8775 
8776     CompareBoolWithConstantResult CmpRes;
8777 
8778     switch (op) {
8779     case BO_LT:
8780       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8781       break;
8782     case BO_GT:
8783       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8784       break;
8785     case BO_LE:
8786       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8787       break;
8788     case BO_GE:
8789       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8790       break;
8791     case BO_EQ:
8792       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8793       break;
8794     case BO_NE:
8795       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8796       break;
8797     default:
8798       CmpRes = Unkwn;
8799       break;
8800     }
8801 
8802     if (CmpRes == AFals) {
8803       IsTrue = false;
8804     } else if (CmpRes == ATrue) {
8805       IsTrue = true;
8806     } else {
8807       return;
8808     }
8809   }
8810 
8811   // If this is a comparison to an enum constant, include that
8812   // constant in the diagnostic.
8813   const EnumConstantDecl *ED = nullptr;
8814   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8815     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8816 
8817   SmallString<64> PrettySourceValue;
8818   llvm::raw_svector_ostream OS(PrettySourceValue);
8819   if (ED)
8820     OS << '\'' << *ED << "' (" << Value << ")";
8821   else
8822     OS << Value;
8823 
8824   S.DiagRuntimeBehavior(
8825     E->getOperatorLoc(), E,
8826     S.PDiag(diag::warn_out_of_range_compare)
8827         << OS.str() << LiteralOrBoolConstant
8828         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8829         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8830 }
8831 
8832 /// Analyze the operands of the given comparison.  Implements the
8833 /// fallback case from AnalyzeComparison.
8834 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8835   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8836   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8837 }
8838 
8839 /// \brief Implements -Wsign-compare.
8840 ///
8841 /// \param E the binary operator to check for warnings
8842 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8843   // The type the comparison is being performed in.
8844   QualType T = E->getLHS()->getType();
8845 
8846   // Only analyze comparison operators where both sides have been converted to
8847   // the same type.
8848   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8849     return AnalyzeImpConvsInComparison(S, E);
8850 
8851   // Don't analyze value-dependent comparisons directly.
8852   if (E->isValueDependent())
8853     return AnalyzeImpConvsInComparison(S, E);
8854 
8855   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8856   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8857 
8858   bool IsComparisonConstant = false;
8859 
8860   // Check whether an integer constant comparison results in a value
8861   // of 'true' or 'false'.
8862   if (T->isIntegralType(S.Context)) {
8863     llvm::APSInt RHSValue;
8864     bool IsRHSIntegralLiteral =
8865       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8866     llvm::APSInt LHSValue;
8867     bool IsLHSIntegralLiteral =
8868       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8869     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8870         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8871     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8872       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8873     else
8874       IsComparisonConstant =
8875         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8876   } else if (!T->hasUnsignedIntegerRepresentation())
8877       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8878 
8879   // We don't care about value-dependent expressions or expressions
8880   // whose result is a constant.
8881   if (IsComparisonConstant)
8882     return AnalyzeImpConvsInComparison(S, E);
8883 
8884   // If this is a tautological comparison, suppress -Wsign-compare.
8885   if (CheckTautologicalComparisonWithZero(S, E))
8886     return AnalyzeImpConvsInComparison(S, E);
8887 
8888   // We don't do anything special if this isn't an unsigned integral
8889   // comparison:  we're only interested in integral comparisons, and
8890   // signed comparisons only happen in cases we don't care to warn about.
8891   if (!T->hasUnsignedIntegerRepresentation())
8892     return AnalyzeImpConvsInComparison(S, E);
8893 
8894   // Check to see if one of the (unmodified) operands is of different
8895   // signedness.
8896   Expr *signedOperand, *unsignedOperand;
8897   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8898     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8899            "unsigned comparison between two signed integer expressions?");
8900     signedOperand = LHS;
8901     unsignedOperand = RHS;
8902   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8903     signedOperand = RHS;
8904     unsignedOperand = LHS;
8905   } else {
8906     return AnalyzeImpConvsInComparison(S, E);
8907   }
8908 
8909   // Otherwise, calculate the effective range of the signed operand.
8910   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8911 
8912   // Go ahead and analyze implicit conversions in the operands.  Note
8913   // that we skip the implicit conversions on both sides.
8914   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8915   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8916 
8917   // If the signed range is non-negative, -Wsign-compare won't fire.
8918   if (signedRange.NonNegative)
8919     return;
8920 
8921   // For (in)equality comparisons, if the unsigned operand is a
8922   // constant which cannot collide with a overflowed signed operand,
8923   // then reinterpreting the signed operand as unsigned will not
8924   // change the result of the comparison.
8925   if (E->isEqualityOp()) {
8926     unsigned comparisonWidth = S.Context.getIntWidth(T);
8927     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8928 
8929     // We should never be unable to prove that the unsigned operand is
8930     // non-negative.
8931     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8932 
8933     if (unsignedRange.Width < comparisonWidth)
8934       return;
8935   }
8936 
8937   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8938     S.PDiag(diag::warn_mixed_sign_comparison)
8939       << LHS->getType() << RHS->getType()
8940       << LHS->getSourceRange() << RHS->getSourceRange());
8941 }
8942 
8943 /// Analyzes an attempt to assign the given value to a bitfield.
8944 ///
8945 /// Returns true if there was something fishy about the attempt.
8946 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8947                                SourceLocation InitLoc) {
8948   assert(Bitfield->isBitField());
8949   if (Bitfield->isInvalidDecl())
8950     return false;
8951 
8952   // White-list bool bitfields.
8953   QualType BitfieldType = Bitfield->getType();
8954   if (BitfieldType->isBooleanType())
8955      return false;
8956 
8957   if (BitfieldType->isEnumeralType()) {
8958     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8959     // If the underlying enum type was not explicitly specified as an unsigned
8960     // type and the enum contain only positive values, MSVC++ will cause an
8961     // inconsistency by storing this as a signed type.
8962     if (S.getLangOpts().CPlusPlus11 &&
8963         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8964         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8965         BitfieldEnumDecl->getNumNegativeBits() == 0) {
8966       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8967         << BitfieldEnumDecl->getNameAsString();
8968     }
8969   }
8970 
8971   if (Bitfield->getType()->isBooleanType())
8972     return false;
8973 
8974   // Ignore value- or type-dependent expressions.
8975   if (Bitfield->getBitWidth()->isValueDependent() ||
8976       Bitfield->getBitWidth()->isTypeDependent() ||
8977       Init->isValueDependent() ||
8978       Init->isTypeDependent())
8979     return false;
8980 
8981   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8982   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8983 
8984   llvm::APSInt Value;
8985   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8986                                    Expr::SE_AllowSideEffects)) {
8987     // The RHS is not constant.  If the RHS has an enum type, make sure the
8988     // bitfield is wide enough to hold all the values of the enum without
8989     // truncation.
8990     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
8991       EnumDecl *ED = EnumTy->getDecl();
8992       bool SignedBitfield = BitfieldType->isSignedIntegerType();
8993 
8994       // Enum types are implicitly signed on Windows, so check if there are any
8995       // negative enumerators to see if the enum was intended to be signed or
8996       // not.
8997       bool SignedEnum = ED->getNumNegativeBits() > 0;
8998 
8999       // Check for surprising sign changes when assigning enum values to a
9000       // bitfield of different signedness.  If the bitfield is signed and we
9001       // have exactly the right number of bits to store this unsigned enum,
9002       // suggest changing the enum to an unsigned type. This typically happens
9003       // on Windows where unfixed enums always use an underlying type of 'int'.
9004       unsigned DiagID = 0;
9005       if (SignedEnum && !SignedBitfield) {
9006         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9007       } else if (SignedBitfield && !SignedEnum &&
9008                  ED->getNumPositiveBits() == FieldWidth) {
9009         DiagID = diag::warn_signed_bitfield_enum_conversion;
9010       }
9011 
9012       if (DiagID) {
9013         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9014         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9015         SourceRange TypeRange =
9016             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9017         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9018             << SignedEnum << TypeRange;
9019       }
9020 
9021       // Compute the required bitwidth. If the enum has negative values, we need
9022       // one more bit than the normal number of positive bits to represent the
9023       // sign bit.
9024       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9025                                                   ED->getNumNegativeBits())
9026                                        : ED->getNumPositiveBits();
9027 
9028       // Check the bitwidth.
9029       if (BitsNeeded > FieldWidth) {
9030         Expr *WidthExpr = Bitfield->getBitWidth();
9031         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9032             << Bitfield << ED;
9033         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9034             << BitsNeeded << ED << WidthExpr->getSourceRange();
9035       }
9036     }
9037 
9038     return false;
9039   }
9040 
9041   unsigned OriginalWidth = Value.getBitWidth();
9042 
9043   if (!Value.isSigned() || Value.isNegative())
9044     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9045       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9046         OriginalWidth = Value.getMinSignedBits();
9047 
9048   if (OriginalWidth <= FieldWidth)
9049     return false;
9050 
9051   // Compute the value which the bitfield will contain.
9052   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9053   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9054 
9055   // Check whether the stored value is equal to the original value.
9056   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9057   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9058     return false;
9059 
9060   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9061   // therefore don't strictly fit into a signed bitfield of width 1.
9062   if (FieldWidth == 1 && Value == 1)
9063     return false;
9064 
9065   std::string PrettyValue = Value.toString(10);
9066   std::string PrettyTrunc = TruncatedValue.toString(10);
9067 
9068   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9069     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9070     << Init->getSourceRange();
9071 
9072   return true;
9073 }
9074 
9075 /// Analyze the given simple or compound assignment for warning-worthy
9076 /// operations.
9077 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9078   // Just recurse on the LHS.
9079   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9080 
9081   // We want to recurse on the RHS as normal unless we're assigning to
9082   // a bitfield.
9083   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9084     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9085                                   E->getOperatorLoc())) {
9086       // Recurse, ignoring any implicit conversions on the RHS.
9087       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9088                                         E->getOperatorLoc());
9089     }
9090   }
9091 
9092   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9093 }
9094 
9095 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9096 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9097                      SourceLocation CContext, unsigned diag,
9098                      bool pruneControlFlow = false) {
9099   if (pruneControlFlow) {
9100     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9101                           S.PDiag(diag)
9102                             << SourceType << T << E->getSourceRange()
9103                             << SourceRange(CContext));
9104     return;
9105   }
9106   S.Diag(E->getExprLoc(), diag)
9107     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9108 }
9109 
9110 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9111 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9112                      unsigned diag, bool pruneControlFlow = false) {
9113   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9114 }
9115 
9116 
9117 /// Diagnose an implicit cast from a floating point value to an integer value.
9118 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9119 
9120                              SourceLocation CContext) {
9121   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9122   const bool PruneWarnings = S.inTemplateInstantiation();
9123 
9124   Expr *InnerE = E->IgnoreParenImpCasts();
9125   // We also want to warn on, e.g., "int i = -1.234"
9126   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9127     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9128       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9129 
9130   const bool IsLiteral =
9131       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9132 
9133   llvm::APFloat Value(0.0);
9134   bool IsConstant =
9135     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9136   if (!IsConstant) {
9137     return DiagnoseImpCast(S, E, T, CContext,
9138                            diag::warn_impcast_float_integer, PruneWarnings);
9139   }
9140 
9141   bool isExact = false;
9142 
9143   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9144                             T->hasUnsignedIntegerRepresentation());
9145   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9146                              &isExact) == llvm::APFloat::opOK &&
9147       isExact) {
9148     if (IsLiteral) return;
9149     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9150                            PruneWarnings);
9151   }
9152 
9153   unsigned DiagID = 0;
9154   if (IsLiteral) {
9155     // Warn on floating point literal to integer.
9156     DiagID = diag::warn_impcast_literal_float_to_integer;
9157   } else if (IntegerValue == 0) {
9158     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9159       return DiagnoseImpCast(S, E, T, CContext,
9160                              diag::warn_impcast_float_integer, PruneWarnings);
9161     }
9162     // Warn on non-zero to zero conversion.
9163     DiagID = diag::warn_impcast_float_to_integer_zero;
9164   } else {
9165     if (IntegerValue.isUnsigned()) {
9166       if (!IntegerValue.isMaxValue()) {
9167         return DiagnoseImpCast(S, E, T, CContext,
9168                                diag::warn_impcast_float_integer, PruneWarnings);
9169       }
9170     } else {  // IntegerValue.isSigned()
9171       if (!IntegerValue.isMaxSignedValue() &&
9172           !IntegerValue.isMinSignedValue()) {
9173         return DiagnoseImpCast(S, E, T, CContext,
9174                                diag::warn_impcast_float_integer, PruneWarnings);
9175       }
9176     }
9177     // Warn on evaluatable floating point expression to integer conversion.
9178     DiagID = diag::warn_impcast_float_to_integer;
9179   }
9180 
9181   // FIXME: Force the precision of the source value down so we don't print
9182   // digits which are usually useless (we don't really care here if we
9183   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9184   // would automatically print the shortest representation, but it's a bit
9185   // tricky to implement.
9186   SmallString<16> PrettySourceValue;
9187   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9188   precision = (precision * 59 + 195) / 196;
9189   Value.toString(PrettySourceValue, precision);
9190 
9191   SmallString<16> PrettyTargetValue;
9192   if (IsBool)
9193     PrettyTargetValue = Value.isZero() ? "false" : "true";
9194   else
9195     IntegerValue.toString(PrettyTargetValue);
9196 
9197   if (PruneWarnings) {
9198     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9199                           S.PDiag(DiagID)
9200                               << E->getType() << T.getUnqualifiedType()
9201                               << PrettySourceValue << PrettyTargetValue
9202                               << E->getSourceRange() << SourceRange(CContext));
9203   } else {
9204     S.Diag(E->getExprLoc(), DiagID)
9205         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9206         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9207   }
9208 }
9209 
9210 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9211   if (!Range.Width) return "0";
9212 
9213   llvm::APSInt ValueInRange = Value;
9214   ValueInRange.setIsSigned(!Range.NonNegative);
9215   ValueInRange = ValueInRange.trunc(Range.Width);
9216   return ValueInRange.toString(10);
9217 }
9218 
9219 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9220   if (!isa<ImplicitCastExpr>(Ex))
9221     return false;
9222 
9223   Expr *InnerE = Ex->IgnoreParenImpCasts();
9224   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9225   const Type *Source =
9226     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9227   if (Target->isDependentType())
9228     return false;
9229 
9230   const BuiltinType *FloatCandidateBT =
9231     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9232   const Type *BoolCandidateType = ToBool ? Target : Source;
9233 
9234   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9235           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9236 }
9237 
9238 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9239                                       SourceLocation CC) {
9240   unsigned NumArgs = TheCall->getNumArgs();
9241   for (unsigned i = 0; i < NumArgs; ++i) {
9242     Expr *CurrA = TheCall->getArg(i);
9243     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9244       continue;
9245 
9246     bool IsSwapped = ((i > 0) &&
9247         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9248     IsSwapped |= ((i < (NumArgs - 1)) &&
9249         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9250     if (IsSwapped) {
9251       // Warn on this floating-point to bool conversion.
9252       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9253                       CurrA->getType(), CC,
9254                       diag::warn_impcast_floating_point_to_bool);
9255     }
9256   }
9257 }
9258 
9259 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9260   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9261                         E->getExprLoc()))
9262     return;
9263 
9264   // Don't warn on functions which have return type nullptr_t.
9265   if (isa<CallExpr>(E))
9266     return;
9267 
9268   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9269   const Expr::NullPointerConstantKind NullKind =
9270       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9271   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9272     return;
9273 
9274   // Return if target type is a safe conversion.
9275   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9276       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9277     return;
9278 
9279   SourceLocation Loc = E->getSourceRange().getBegin();
9280 
9281   // Venture through the macro stacks to get to the source of macro arguments.
9282   // The new location is a better location than the complete location that was
9283   // passed in.
9284   while (S.SourceMgr.isMacroArgExpansion(Loc))
9285     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9286 
9287   while (S.SourceMgr.isMacroArgExpansion(CC))
9288     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9289 
9290   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9291   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9292     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9293         Loc, S.SourceMgr, S.getLangOpts());
9294     if (MacroName == "NULL")
9295       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9296   }
9297 
9298   // Only warn if the null and context location are in the same macro expansion.
9299   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9300     return;
9301 
9302   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9303       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9304       << FixItHint::CreateReplacement(Loc,
9305                                       S.getFixItZeroLiteralForType(T, Loc));
9306 }
9307 
9308 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9309                            ObjCArrayLiteral *ArrayLiteral);
9310 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9311                                 ObjCDictionaryLiteral *DictionaryLiteral);
9312 
9313 /// Check a single element within a collection literal against the
9314 /// target element type.
9315 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9316                                        Expr *Element, unsigned ElementKind) {
9317   // Skip a bitcast to 'id' or qualified 'id'.
9318   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9319     if (ICE->getCastKind() == CK_BitCast &&
9320         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9321       Element = ICE->getSubExpr();
9322   }
9323 
9324   QualType ElementType = Element->getType();
9325   ExprResult ElementResult(Element);
9326   if (ElementType->getAs<ObjCObjectPointerType>() &&
9327       S.CheckSingleAssignmentConstraints(TargetElementType,
9328                                          ElementResult,
9329                                          false, false)
9330         != Sema::Compatible) {
9331     S.Diag(Element->getLocStart(),
9332            diag::warn_objc_collection_literal_element)
9333       << ElementType << ElementKind << TargetElementType
9334       << Element->getSourceRange();
9335   }
9336 
9337   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9338     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9339   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9340     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9341 }
9342 
9343 /// Check an Objective-C array literal being converted to the given
9344 /// target type.
9345 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9346                            ObjCArrayLiteral *ArrayLiteral) {
9347   if (!S.NSArrayDecl)
9348     return;
9349 
9350   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9351   if (!TargetObjCPtr)
9352     return;
9353 
9354   if (TargetObjCPtr->isUnspecialized() ||
9355       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9356         != S.NSArrayDecl->getCanonicalDecl())
9357     return;
9358 
9359   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9360   if (TypeArgs.size() != 1)
9361     return;
9362 
9363   QualType TargetElementType = TypeArgs[0];
9364   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9365     checkObjCCollectionLiteralElement(S, TargetElementType,
9366                                       ArrayLiteral->getElement(I),
9367                                       0);
9368   }
9369 }
9370 
9371 /// Check an Objective-C dictionary literal being converted to the given
9372 /// target type.
9373 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9374                                 ObjCDictionaryLiteral *DictionaryLiteral) {
9375   if (!S.NSDictionaryDecl)
9376     return;
9377 
9378   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9379   if (!TargetObjCPtr)
9380     return;
9381 
9382   if (TargetObjCPtr->isUnspecialized() ||
9383       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9384         != S.NSDictionaryDecl->getCanonicalDecl())
9385     return;
9386 
9387   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9388   if (TypeArgs.size() != 2)
9389     return;
9390 
9391   QualType TargetKeyType = TypeArgs[0];
9392   QualType TargetObjectType = TypeArgs[1];
9393   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9394     auto Element = DictionaryLiteral->getKeyValueElement(I);
9395     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9396     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9397   }
9398 }
9399 
9400 // Helper function to filter out cases for constant width constant conversion.
9401 // Don't warn on char array initialization or for non-decimal values.
9402 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9403                                    SourceLocation CC) {
9404   // If initializing from a constant, and the constant starts with '0',
9405   // then it is a binary, octal, or hexadecimal.  Allow these constants
9406   // to fill all the bits, even if there is a sign change.
9407   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9408     const char FirstLiteralCharacter =
9409         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9410     if (FirstLiteralCharacter == '0')
9411       return false;
9412   }
9413 
9414   // If the CC location points to a '{', and the type is char, then assume
9415   // assume it is an array initialization.
9416   if (CC.isValid() && T->isCharType()) {
9417     const char FirstContextCharacter =
9418         S.getSourceManager().getCharacterData(CC)[0];
9419     if (FirstContextCharacter == '{')
9420       return false;
9421   }
9422 
9423   return true;
9424 }
9425 
9426 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9427                              SourceLocation CC, bool *ICContext = nullptr) {
9428   if (E->isTypeDependent() || E->isValueDependent()) return;
9429 
9430   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9431   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9432   if (Source == Target) return;
9433   if (Target->isDependentType()) return;
9434 
9435   // If the conversion context location is invalid don't complain. We also
9436   // don't want to emit a warning if the issue occurs from the expansion of
9437   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9438   // delay this check as long as possible. Once we detect we are in that
9439   // scenario, we just return.
9440   if (CC.isInvalid())
9441     return;
9442 
9443   // Diagnose implicit casts to bool.
9444   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9445     if (isa<StringLiteral>(E))
9446       // Warn on string literal to bool.  Checks for string literals in logical
9447       // and expressions, for instance, assert(0 && "error here"), are
9448       // prevented by a check in AnalyzeImplicitConversions().
9449       return DiagnoseImpCast(S, E, T, CC,
9450                              diag::warn_impcast_string_literal_to_bool);
9451     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9452         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9453       // This covers the literal expressions that evaluate to Objective-C
9454       // objects.
9455       return DiagnoseImpCast(S, E, T, CC,
9456                              diag::warn_impcast_objective_c_literal_to_bool);
9457     }
9458     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9459       // Warn on pointer to bool conversion that is always true.
9460       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9461                                      SourceRange(CC));
9462     }
9463   }
9464 
9465   // Check implicit casts from Objective-C collection literals to specialized
9466   // collection types, e.g., NSArray<NSString *> *.
9467   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9468     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9469   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9470     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9471 
9472   // Strip vector types.
9473   if (isa<VectorType>(Source)) {
9474     if (!isa<VectorType>(Target)) {
9475       if (S.SourceMgr.isInSystemMacro(CC))
9476         return;
9477       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9478     }
9479 
9480     // If the vector cast is cast between two vectors of the same size, it is
9481     // a bitcast, not a conversion.
9482     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9483       return;
9484 
9485     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9486     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9487   }
9488   if (auto VecTy = dyn_cast<VectorType>(Target))
9489     Target = VecTy->getElementType().getTypePtr();
9490 
9491   // Strip complex types.
9492   if (isa<ComplexType>(Source)) {
9493     if (!isa<ComplexType>(Target)) {
9494       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9495         return;
9496 
9497       return DiagnoseImpCast(S, E, T, CC,
9498                              S.getLangOpts().CPlusPlus
9499                                  ? diag::err_impcast_complex_scalar
9500                                  : diag::warn_impcast_complex_scalar);
9501     }
9502 
9503     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9504     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9505   }
9506 
9507   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9508   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9509 
9510   // If the source is floating point...
9511   if (SourceBT && SourceBT->isFloatingPoint()) {
9512     // ...and the target is floating point...
9513     if (TargetBT && TargetBT->isFloatingPoint()) {
9514       // ...then warn if we're dropping FP rank.
9515 
9516       // Builtin FP kinds are ordered by increasing FP rank.
9517       if (SourceBT->getKind() > TargetBT->getKind()) {
9518         // Don't warn about float constants that are precisely
9519         // representable in the target type.
9520         Expr::EvalResult result;
9521         if (E->EvaluateAsRValue(result, S.Context)) {
9522           // Value might be a float, a float vector, or a float complex.
9523           if (IsSameFloatAfterCast(result.Val,
9524                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9525                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9526             return;
9527         }
9528 
9529         if (S.SourceMgr.isInSystemMacro(CC))
9530           return;
9531 
9532         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9533       }
9534       // ... or possibly if we're increasing rank, too
9535       else if (TargetBT->getKind() > SourceBT->getKind()) {
9536         if (S.SourceMgr.isInSystemMacro(CC))
9537           return;
9538 
9539         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9540       }
9541       return;
9542     }
9543 
9544     // If the target is integral, always warn.
9545     if (TargetBT && TargetBT->isInteger()) {
9546       if (S.SourceMgr.isInSystemMacro(CC))
9547         return;
9548 
9549       DiagnoseFloatingImpCast(S, E, T, CC);
9550     }
9551 
9552     // Detect the case where a call result is converted from floating-point to
9553     // to bool, and the final argument to the call is converted from bool, to
9554     // discover this typo:
9555     //
9556     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9557     //
9558     // FIXME: This is an incredibly special case; is there some more general
9559     // way to detect this class of misplaced-parentheses bug?
9560     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9561       // Check last argument of function call to see if it is an
9562       // implicit cast from a type matching the type the result
9563       // is being cast to.
9564       CallExpr *CEx = cast<CallExpr>(E);
9565       if (unsigned NumArgs = CEx->getNumArgs()) {
9566         Expr *LastA = CEx->getArg(NumArgs - 1);
9567         Expr *InnerE = LastA->IgnoreParenImpCasts();
9568         if (isa<ImplicitCastExpr>(LastA) &&
9569             InnerE->getType()->isBooleanType()) {
9570           // Warn on this floating-point to bool conversion
9571           DiagnoseImpCast(S, E, T, CC,
9572                           diag::warn_impcast_floating_point_to_bool);
9573         }
9574       }
9575     }
9576     return;
9577   }
9578 
9579   DiagnoseNullConversion(S, E, T, CC);
9580 
9581   S.DiscardMisalignedMemberAddress(Target, E);
9582 
9583   if (!Source->isIntegerType() || !Target->isIntegerType())
9584     return;
9585 
9586   // TODO: remove this early return once the false positives for constant->bool
9587   // in templates, macros, etc, are reduced or removed.
9588   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9589     return;
9590 
9591   IntRange SourceRange = GetExprRange(S.Context, E);
9592   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9593 
9594   if (SourceRange.Width > TargetRange.Width) {
9595     // If the source is a constant, use a default-on diagnostic.
9596     // TODO: this should happen for bitfield stores, too.
9597     llvm::APSInt Value(32);
9598     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9599       if (S.SourceMgr.isInSystemMacro(CC))
9600         return;
9601 
9602       std::string PrettySourceValue = Value.toString(10);
9603       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9604 
9605       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9606         S.PDiag(diag::warn_impcast_integer_precision_constant)
9607             << PrettySourceValue << PrettyTargetValue
9608             << E->getType() << T << E->getSourceRange()
9609             << clang::SourceRange(CC));
9610       return;
9611     }
9612 
9613     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9614     if (S.SourceMgr.isInSystemMacro(CC))
9615       return;
9616 
9617     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9618       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9619                              /* pruneControlFlow */ true);
9620     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9621   }
9622 
9623   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9624       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9625     // Warn when doing a signed to signed conversion, warn if the positive
9626     // source value is exactly the width of the target type, which will
9627     // cause a negative value to be stored.
9628 
9629     llvm::APSInt Value;
9630     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9631         !S.SourceMgr.isInSystemMacro(CC)) {
9632       if (isSameWidthConstantConversion(S, E, T, CC)) {
9633         std::string PrettySourceValue = Value.toString(10);
9634         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9635 
9636         S.DiagRuntimeBehavior(
9637             E->getExprLoc(), E,
9638             S.PDiag(diag::warn_impcast_integer_precision_constant)
9639                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9640                 << E->getSourceRange() << clang::SourceRange(CC));
9641         return;
9642       }
9643     }
9644 
9645     // Fall through for non-constants to give a sign conversion warning.
9646   }
9647 
9648   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9649       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9650        SourceRange.Width == TargetRange.Width)) {
9651     if (S.SourceMgr.isInSystemMacro(CC))
9652       return;
9653 
9654     unsigned DiagID = diag::warn_impcast_integer_sign;
9655 
9656     // Traditionally, gcc has warned about this under -Wsign-compare.
9657     // We also want to warn about it in -Wconversion.
9658     // So if -Wconversion is off, use a completely identical diagnostic
9659     // in the sign-compare group.
9660     // The conditional-checking code will
9661     if (ICContext) {
9662       DiagID = diag::warn_impcast_integer_sign_conditional;
9663       *ICContext = true;
9664     }
9665 
9666     return DiagnoseImpCast(S, E, T, CC, DiagID);
9667   }
9668 
9669   // Diagnose conversions between different enumeration types.
9670   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9671   // type, to give us better diagnostics.
9672   QualType SourceType = E->getType();
9673   if (!S.getLangOpts().CPlusPlus) {
9674     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9675       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9676         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9677         SourceType = S.Context.getTypeDeclType(Enum);
9678         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9679       }
9680   }
9681 
9682   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9683     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9684       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9685           TargetEnum->getDecl()->hasNameForLinkage() &&
9686           SourceEnum != TargetEnum) {
9687         if (S.SourceMgr.isInSystemMacro(CC))
9688           return;
9689 
9690         return DiagnoseImpCast(S, E, SourceType, T, CC,
9691                                diag::warn_impcast_different_enum_types);
9692       }
9693 }
9694 
9695 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9696                               SourceLocation CC, QualType T);
9697 
9698 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9699                              SourceLocation CC, bool &ICContext) {
9700   E = E->IgnoreParenImpCasts();
9701 
9702   if (isa<ConditionalOperator>(E))
9703     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9704 
9705   AnalyzeImplicitConversions(S, E, CC);
9706   if (E->getType() != T)
9707     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9708 }
9709 
9710 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9711                               SourceLocation CC, QualType T) {
9712   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9713 
9714   bool Suspicious = false;
9715   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9716   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9717 
9718   // If -Wconversion would have warned about either of the candidates
9719   // for a signedness conversion to the context type...
9720   if (!Suspicious) return;
9721 
9722   // ...but it's currently ignored...
9723   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9724     return;
9725 
9726   // ...then check whether it would have warned about either of the
9727   // candidates for a signedness conversion to the condition type.
9728   if (E->getType() == T) return;
9729 
9730   Suspicious = false;
9731   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9732                           E->getType(), CC, &Suspicious);
9733   if (!Suspicious)
9734     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9735                             E->getType(), CC, &Suspicious);
9736 }
9737 
9738 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9739 /// Input argument E is a logical expression.
9740 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9741   if (S.getLangOpts().Bool)
9742     return;
9743   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9744 }
9745 
9746 /// AnalyzeImplicitConversions - Find and report any interesting
9747 /// implicit conversions in the given expression.  There are a couple
9748 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9749 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9750   QualType T = OrigE->getType();
9751   Expr *E = OrigE->IgnoreParenImpCasts();
9752 
9753   if (E->isTypeDependent() || E->isValueDependent())
9754     return;
9755 
9756   // For conditional operators, we analyze the arguments as if they
9757   // were being fed directly into the output.
9758   if (isa<ConditionalOperator>(E)) {
9759     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9760     CheckConditionalOperator(S, CO, CC, T);
9761     return;
9762   }
9763 
9764   // Check implicit argument conversions for function calls.
9765   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9766     CheckImplicitArgumentConversions(S, Call, CC);
9767 
9768   // Go ahead and check any implicit conversions we might have skipped.
9769   // The non-canonical typecheck is just an optimization;
9770   // CheckImplicitConversion will filter out dead implicit conversions.
9771   if (E->getType() != T)
9772     CheckImplicitConversion(S, E, T, CC);
9773 
9774   // Now continue drilling into this expression.
9775 
9776   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9777     // The bound subexpressions in a PseudoObjectExpr are not reachable
9778     // as transitive children.
9779     // FIXME: Use a more uniform representation for this.
9780     for (auto *SE : POE->semantics())
9781       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9782         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9783   }
9784 
9785   // Skip past explicit casts.
9786   if (isa<ExplicitCastExpr>(E)) {
9787     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9788     return AnalyzeImplicitConversions(S, E, CC);
9789   }
9790 
9791   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9792     // Do a somewhat different check with comparison operators.
9793     if (BO->isComparisonOp())
9794       return AnalyzeComparison(S, BO);
9795 
9796     // And with simple assignments.
9797     if (BO->getOpcode() == BO_Assign)
9798       return AnalyzeAssignment(S, BO);
9799   }
9800 
9801   // These break the otherwise-useful invariant below.  Fortunately,
9802   // we don't really need to recurse into them, because any internal
9803   // expressions should have been analyzed already when they were
9804   // built into statements.
9805   if (isa<StmtExpr>(E)) return;
9806 
9807   // Don't descend into unevaluated contexts.
9808   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9809 
9810   // Now just recurse over the expression's children.
9811   CC = E->getExprLoc();
9812   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9813   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9814   for (Stmt *SubStmt : E->children()) {
9815     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9816     if (!ChildExpr)
9817       continue;
9818 
9819     if (IsLogicalAndOperator &&
9820         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9821       // Ignore checking string literals that are in logical and operators.
9822       // This is a common pattern for asserts.
9823       continue;
9824     AnalyzeImplicitConversions(S, ChildExpr, CC);
9825   }
9826 
9827   if (BO && BO->isLogicalOp()) {
9828     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9829     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9830       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9831 
9832     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9833     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9834       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9835   }
9836 
9837   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9838     if (U->getOpcode() == UO_LNot)
9839       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9840 }
9841 
9842 } // end anonymous namespace
9843 
9844 /// Diagnose integer type and any valid implicit convertion to it.
9845 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9846   // Taking into account implicit conversions,
9847   // allow any integer.
9848   if (!E->getType()->isIntegerType()) {
9849     S.Diag(E->getLocStart(),
9850            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9851     return true;
9852   }
9853   // Potentially emit standard warnings for implicit conversions if enabled
9854   // using -Wconversion.
9855   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9856   return false;
9857 }
9858 
9859 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9860 // Returns true when emitting a warning about taking the address of a reference.
9861 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9862                               const PartialDiagnostic &PD) {
9863   E = E->IgnoreParenImpCasts();
9864 
9865   const FunctionDecl *FD = nullptr;
9866 
9867   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9868     if (!DRE->getDecl()->getType()->isReferenceType())
9869       return false;
9870   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9871     if (!M->getMemberDecl()->getType()->isReferenceType())
9872       return false;
9873   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9874     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9875       return false;
9876     FD = Call->getDirectCallee();
9877   } else {
9878     return false;
9879   }
9880 
9881   SemaRef.Diag(E->getExprLoc(), PD);
9882 
9883   // If possible, point to location of function.
9884   if (FD) {
9885     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9886   }
9887 
9888   return true;
9889 }
9890 
9891 // Returns true if the SourceLocation is expanded from any macro body.
9892 // Returns false if the SourceLocation is invalid, is from not in a macro
9893 // expansion, or is from expanded from a top-level macro argument.
9894 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9895   if (Loc.isInvalid())
9896     return false;
9897 
9898   while (Loc.isMacroID()) {
9899     if (SM.isMacroBodyExpansion(Loc))
9900       return true;
9901     Loc = SM.getImmediateMacroCallerLoc(Loc);
9902   }
9903 
9904   return false;
9905 }
9906 
9907 /// \brief Diagnose pointers that are always non-null.
9908 /// \param E the expression containing the pointer
9909 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9910 /// compared to a null pointer
9911 /// \param IsEqual True when the comparison is equal to a null pointer
9912 /// \param Range Extra SourceRange to highlight in the diagnostic
9913 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9914                                         Expr::NullPointerConstantKind NullKind,
9915                                         bool IsEqual, SourceRange Range) {
9916   if (!E)
9917     return;
9918 
9919   // Don't warn inside macros.
9920   if (E->getExprLoc().isMacroID()) {
9921     const SourceManager &SM = getSourceManager();
9922     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9923         IsInAnyMacroBody(SM, Range.getBegin()))
9924       return;
9925   }
9926   E = E->IgnoreImpCasts();
9927 
9928   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9929 
9930   if (isa<CXXThisExpr>(E)) {
9931     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9932                                 : diag::warn_this_bool_conversion;
9933     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9934     return;
9935   }
9936 
9937   bool IsAddressOf = false;
9938 
9939   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9940     if (UO->getOpcode() != UO_AddrOf)
9941       return;
9942     IsAddressOf = true;
9943     E = UO->getSubExpr();
9944   }
9945 
9946   if (IsAddressOf) {
9947     unsigned DiagID = IsCompare
9948                           ? diag::warn_address_of_reference_null_compare
9949                           : diag::warn_address_of_reference_bool_conversion;
9950     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9951                                          << IsEqual;
9952     if (CheckForReference(*this, E, PD)) {
9953       return;
9954     }
9955   }
9956 
9957   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9958     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9959     std::string Str;
9960     llvm::raw_string_ostream S(Str);
9961     E->printPretty(S, nullptr, getPrintingPolicy());
9962     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9963                                 : diag::warn_cast_nonnull_to_bool;
9964     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9965       << E->getSourceRange() << Range << IsEqual;
9966     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9967   };
9968 
9969   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9970   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9971     if (auto *Callee = Call->getDirectCallee()) {
9972       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9973         ComplainAboutNonnullParamOrCall(A);
9974         return;
9975       }
9976     }
9977   }
9978 
9979   // Expect to find a single Decl.  Skip anything more complicated.
9980   ValueDecl *D = nullptr;
9981   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9982     D = R->getDecl();
9983   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9984     D = M->getMemberDecl();
9985   }
9986 
9987   // Weak Decls can be null.
9988   if (!D || D->isWeak())
9989     return;
9990 
9991   // Check for parameter decl with nonnull attribute
9992   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9993     if (getCurFunction() &&
9994         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9995       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
9996         ComplainAboutNonnullParamOrCall(A);
9997         return;
9998       }
9999 
10000       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10001         auto ParamIter = llvm::find(FD->parameters(), PV);
10002         assert(ParamIter != FD->param_end());
10003         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10004 
10005         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10006           if (!NonNull->args_size()) {
10007               ComplainAboutNonnullParamOrCall(NonNull);
10008               return;
10009           }
10010 
10011           for (unsigned ArgNo : NonNull->args()) {
10012             if (ArgNo == ParamNo) {
10013               ComplainAboutNonnullParamOrCall(NonNull);
10014               return;
10015             }
10016           }
10017         }
10018       }
10019     }
10020   }
10021 
10022   QualType T = D->getType();
10023   const bool IsArray = T->isArrayType();
10024   const bool IsFunction = T->isFunctionType();
10025 
10026   // Address of function is used to silence the function warning.
10027   if (IsAddressOf && IsFunction) {
10028     return;
10029   }
10030 
10031   // Found nothing.
10032   if (!IsAddressOf && !IsFunction && !IsArray)
10033     return;
10034 
10035   // Pretty print the expression for the diagnostic.
10036   std::string Str;
10037   llvm::raw_string_ostream S(Str);
10038   E->printPretty(S, nullptr, getPrintingPolicy());
10039 
10040   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10041                               : diag::warn_impcast_pointer_to_bool;
10042   enum {
10043     AddressOf,
10044     FunctionPointer,
10045     ArrayPointer
10046   } DiagType;
10047   if (IsAddressOf)
10048     DiagType = AddressOf;
10049   else if (IsFunction)
10050     DiagType = FunctionPointer;
10051   else if (IsArray)
10052     DiagType = ArrayPointer;
10053   else
10054     llvm_unreachable("Could not determine diagnostic.");
10055   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10056                                 << Range << IsEqual;
10057 
10058   if (!IsFunction)
10059     return;
10060 
10061   // Suggest '&' to silence the function warning.
10062   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10063       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10064 
10065   // Check to see if '()' fixit should be emitted.
10066   QualType ReturnType;
10067   UnresolvedSet<4> NonTemplateOverloads;
10068   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10069   if (ReturnType.isNull())
10070     return;
10071 
10072   if (IsCompare) {
10073     // There are two cases here.  If there is null constant, the only suggest
10074     // for a pointer return type.  If the null is 0, then suggest if the return
10075     // type is a pointer or an integer type.
10076     if (!ReturnType->isPointerType()) {
10077       if (NullKind == Expr::NPCK_ZeroExpression ||
10078           NullKind == Expr::NPCK_ZeroLiteral) {
10079         if (!ReturnType->isIntegerType())
10080           return;
10081       } else {
10082         return;
10083       }
10084     }
10085   } else { // !IsCompare
10086     // For function to bool, only suggest if the function pointer has bool
10087     // return type.
10088     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10089       return;
10090   }
10091   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10092       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10093 }
10094 
10095 /// Diagnoses "dangerous" implicit conversions within the given
10096 /// expression (which is a full expression).  Implements -Wconversion
10097 /// and -Wsign-compare.
10098 ///
10099 /// \param CC the "context" location of the implicit conversion, i.e.
10100 ///   the most location of the syntactic entity requiring the implicit
10101 ///   conversion
10102 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10103   // Don't diagnose in unevaluated contexts.
10104   if (isUnevaluatedContext())
10105     return;
10106 
10107   // Don't diagnose for value- or type-dependent expressions.
10108   if (E->isTypeDependent() || E->isValueDependent())
10109     return;
10110 
10111   // Check for array bounds violations in cases where the check isn't triggered
10112   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10113   // ArraySubscriptExpr is on the RHS of a variable initialization.
10114   CheckArrayAccess(E);
10115 
10116   // This is not the right CC for (e.g.) a variable initialization.
10117   AnalyzeImplicitConversions(*this, E, CC);
10118 }
10119 
10120 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10121 /// Input argument E is a logical expression.
10122 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10123   ::CheckBoolLikeConversion(*this, E, CC);
10124 }
10125 
10126 /// Diagnose when expression is an integer constant expression and its evaluation
10127 /// results in integer overflow
10128 void Sema::CheckForIntOverflow (Expr *E) {
10129   // Use a work list to deal with nested struct initializers.
10130   SmallVector<Expr *, 2> Exprs(1, E);
10131 
10132   do {
10133     Expr *E = Exprs.pop_back_val();
10134 
10135     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10136       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10137       continue;
10138     }
10139 
10140     if (auto InitList = dyn_cast<InitListExpr>(E))
10141       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10142 
10143     if (isa<ObjCBoxedExpr>(E))
10144       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10145   } while (!Exprs.empty());
10146 }
10147 
10148 namespace {
10149 /// \brief Visitor for expressions which looks for unsequenced operations on the
10150 /// same object.
10151 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10152   typedef EvaluatedExprVisitor<SequenceChecker> Base;
10153 
10154   /// \brief A tree of sequenced regions within an expression. Two regions are
10155   /// unsequenced if one is an ancestor or a descendent of the other. When we
10156   /// finish processing an expression with sequencing, such as a comma
10157   /// expression, we fold its tree nodes into its parent, since they are
10158   /// unsequenced with respect to nodes we will visit later.
10159   class SequenceTree {
10160     struct Value {
10161       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10162       unsigned Parent : 31;
10163       unsigned Merged : 1;
10164     };
10165     SmallVector<Value, 8> Values;
10166 
10167   public:
10168     /// \brief A region within an expression which may be sequenced with respect
10169     /// to some other region.
10170     class Seq {
10171       explicit Seq(unsigned N) : Index(N) {}
10172       unsigned Index;
10173       friend class SequenceTree;
10174     public:
10175       Seq() : Index(0) {}
10176     };
10177 
10178     SequenceTree() { Values.push_back(Value(0)); }
10179     Seq root() const { return Seq(0); }
10180 
10181     /// \brief Create a new sequence of operations, which is an unsequenced
10182     /// subset of \p Parent. This sequence of operations is sequenced with
10183     /// respect to other children of \p Parent.
10184     Seq allocate(Seq Parent) {
10185       Values.push_back(Value(Parent.Index));
10186       return Seq(Values.size() - 1);
10187     }
10188 
10189     /// \brief Merge a sequence of operations into its parent.
10190     void merge(Seq S) {
10191       Values[S.Index].Merged = true;
10192     }
10193 
10194     /// \brief Determine whether two operations are unsequenced. This operation
10195     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10196     /// should have been merged into its parent as appropriate.
10197     bool isUnsequenced(Seq Cur, Seq Old) {
10198       unsigned C = representative(Cur.Index);
10199       unsigned Target = representative(Old.Index);
10200       while (C >= Target) {
10201         if (C == Target)
10202           return true;
10203         C = Values[C].Parent;
10204       }
10205       return false;
10206     }
10207 
10208   private:
10209     /// \brief Pick a representative for a sequence.
10210     unsigned representative(unsigned K) {
10211       if (Values[K].Merged)
10212         // Perform path compression as we go.
10213         return Values[K].Parent = representative(Values[K].Parent);
10214       return K;
10215     }
10216   };
10217 
10218   /// An object for which we can track unsequenced uses.
10219   typedef NamedDecl *Object;
10220 
10221   /// Different flavors of object usage which we track. We only track the
10222   /// least-sequenced usage of each kind.
10223   enum UsageKind {
10224     /// A read of an object. Multiple unsequenced reads are OK.
10225     UK_Use,
10226     /// A modification of an object which is sequenced before the value
10227     /// computation of the expression, such as ++n in C++.
10228     UK_ModAsValue,
10229     /// A modification of an object which is not sequenced before the value
10230     /// computation of the expression, such as n++.
10231     UK_ModAsSideEffect,
10232 
10233     UK_Count = UK_ModAsSideEffect + 1
10234   };
10235 
10236   struct Usage {
10237     Usage() : Use(nullptr), Seq() {}
10238     Expr *Use;
10239     SequenceTree::Seq Seq;
10240   };
10241 
10242   struct UsageInfo {
10243     UsageInfo() : Diagnosed(false) {}
10244     Usage Uses[UK_Count];
10245     /// Have we issued a diagnostic for this variable already?
10246     bool Diagnosed;
10247   };
10248   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10249 
10250   Sema &SemaRef;
10251   /// Sequenced regions within the expression.
10252   SequenceTree Tree;
10253   /// Declaration modifications and references which we have seen.
10254   UsageInfoMap UsageMap;
10255   /// The region we are currently within.
10256   SequenceTree::Seq Region;
10257   /// Filled in with declarations which were modified as a side-effect
10258   /// (that is, post-increment operations).
10259   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10260   /// Expressions to check later. We defer checking these to reduce
10261   /// stack usage.
10262   SmallVectorImpl<Expr *> &WorkList;
10263 
10264   /// RAII object wrapping the visitation of a sequenced subexpression of an
10265   /// expression. At the end of this process, the side-effects of the evaluation
10266   /// become sequenced with respect to the value computation of the result, so
10267   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10268   /// UK_ModAsValue.
10269   struct SequencedSubexpression {
10270     SequencedSubexpression(SequenceChecker &Self)
10271       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10272       Self.ModAsSideEffect = &ModAsSideEffect;
10273     }
10274     ~SequencedSubexpression() {
10275       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10276         UsageInfo &U = Self.UsageMap[M.first];
10277         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10278         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10279         SideEffectUsage = M.second;
10280       }
10281       Self.ModAsSideEffect = OldModAsSideEffect;
10282     }
10283 
10284     SequenceChecker &Self;
10285     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10286     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10287   };
10288 
10289   /// RAII object wrapping the visitation of a subexpression which we might
10290   /// choose to evaluate as a constant. If any subexpression is evaluated and
10291   /// found to be non-constant, this allows us to suppress the evaluation of
10292   /// the outer expression.
10293   class EvaluationTracker {
10294   public:
10295     EvaluationTracker(SequenceChecker &Self)
10296         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10297       Self.EvalTracker = this;
10298     }
10299     ~EvaluationTracker() {
10300       Self.EvalTracker = Prev;
10301       if (Prev)
10302         Prev->EvalOK &= EvalOK;
10303     }
10304 
10305     bool evaluate(const Expr *E, bool &Result) {
10306       if (!EvalOK || E->isValueDependent())
10307         return false;
10308       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10309       return EvalOK;
10310     }
10311 
10312   private:
10313     SequenceChecker &Self;
10314     EvaluationTracker *Prev;
10315     bool EvalOK;
10316   } *EvalTracker;
10317 
10318   /// \brief Find the object which is produced by the specified expression,
10319   /// if any.
10320   Object getObject(Expr *E, bool Mod) const {
10321     E = E->IgnoreParenCasts();
10322     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10323       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10324         return getObject(UO->getSubExpr(), Mod);
10325     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10326       if (BO->getOpcode() == BO_Comma)
10327         return getObject(BO->getRHS(), Mod);
10328       if (Mod && BO->isAssignmentOp())
10329         return getObject(BO->getLHS(), Mod);
10330     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10331       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10332       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10333         return ME->getMemberDecl();
10334     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10335       // FIXME: If this is a reference, map through to its value.
10336       return DRE->getDecl();
10337     return nullptr;
10338   }
10339 
10340   /// \brief Note that an object was modified or used by an expression.
10341   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10342     Usage &U = UI.Uses[UK];
10343     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10344       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10345         ModAsSideEffect->push_back(std::make_pair(O, U));
10346       U.Use = Ref;
10347       U.Seq = Region;
10348     }
10349   }
10350   /// \brief Check whether a modification or use conflicts with a prior usage.
10351   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10352                   bool IsModMod) {
10353     if (UI.Diagnosed)
10354       return;
10355 
10356     const Usage &U = UI.Uses[OtherKind];
10357     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10358       return;
10359 
10360     Expr *Mod = U.Use;
10361     Expr *ModOrUse = Ref;
10362     if (OtherKind == UK_Use)
10363       std::swap(Mod, ModOrUse);
10364 
10365     SemaRef.Diag(Mod->getExprLoc(),
10366                  IsModMod ? diag::warn_unsequenced_mod_mod
10367                           : diag::warn_unsequenced_mod_use)
10368       << O << SourceRange(ModOrUse->getExprLoc());
10369     UI.Diagnosed = true;
10370   }
10371 
10372   void notePreUse(Object O, Expr *Use) {
10373     UsageInfo &U = UsageMap[O];
10374     // Uses conflict with other modifications.
10375     checkUsage(O, U, Use, UK_ModAsValue, false);
10376   }
10377   void notePostUse(Object O, Expr *Use) {
10378     UsageInfo &U = UsageMap[O];
10379     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10380     addUsage(U, O, Use, UK_Use);
10381   }
10382 
10383   void notePreMod(Object O, Expr *Mod) {
10384     UsageInfo &U = UsageMap[O];
10385     // Modifications conflict with other modifications and with uses.
10386     checkUsage(O, U, Mod, UK_ModAsValue, true);
10387     checkUsage(O, U, Mod, UK_Use, false);
10388   }
10389   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10390     UsageInfo &U = UsageMap[O];
10391     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10392     addUsage(U, O, Use, UK);
10393   }
10394 
10395 public:
10396   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10397       : Base(S.Context), SemaRef(S), Region(Tree.root()),
10398         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10399     Visit(E);
10400   }
10401 
10402   void VisitStmt(Stmt *S) {
10403     // Skip all statements which aren't expressions for now.
10404   }
10405 
10406   void VisitExpr(Expr *E) {
10407     // By default, just recurse to evaluated subexpressions.
10408     Base::VisitStmt(E);
10409   }
10410 
10411   void VisitCastExpr(CastExpr *E) {
10412     Object O = Object();
10413     if (E->getCastKind() == CK_LValueToRValue)
10414       O = getObject(E->getSubExpr(), false);
10415 
10416     if (O)
10417       notePreUse(O, E);
10418     VisitExpr(E);
10419     if (O)
10420       notePostUse(O, E);
10421   }
10422 
10423   void VisitBinComma(BinaryOperator *BO) {
10424     // C++11 [expr.comma]p1:
10425     //   Every value computation and side effect associated with the left
10426     //   expression is sequenced before every value computation and side
10427     //   effect associated with the right expression.
10428     SequenceTree::Seq LHS = Tree.allocate(Region);
10429     SequenceTree::Seq RHS = Tree.allocate(Region);
10430     SequenceTree::Seq OldRegion = Region;
10431 
10432     {
10433       SequencedSubexpression SeqLHS(*this);
10434       Region = LHS;
10435       Visit(BO->getLHS());
10436     }
10437 
10438     Region = RHS;
10439     Visit(BO->getRHS());
10440 
10441     Region = OldRegion;
10442 
10443     // Forget that LHS and RHS are sequenced. They are both unsequenced
10444     // with respect to other stuff.
10445     Tree.merge(LHS);
10446     Tree.merge(RHS);
10447   }
10448 
10449   void VisitBinAssign(BinaryOperator *BO) {
10450     // The modification is sequenced after the value computation of the LHS
10451     // and RHS, so check it before inspecting the operands and update the
10452     // map afterwards.
10453     Object O = getObject(BO->getLHS(), true);
10454     if (!O)
10455       return VisitExpr(BO);
10456 
10457     notePreMod(O, BO);
10458 
10459     // C++11 [expr.ass]p7:
10460     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10461     //   only once.
10462     //
10463     // Therefore, for a compound assignment operator, O is considered used
10464     // everywhere except within the evaluation of E1 itself.
10465     if (isa<CompoundAssignOperator>(BO))
10466       notePreUse(O, BO);
10467 
10468     Visit(BO->getLHS());
10469 
10470     if (isa<CompoundAssignOperator>(BO))
10471       notePostUse(O, BO);
10472 
10473     Visit(BO->getRHS());
10474 
10475     // C++11 [expr.ass]p1:
10476     //   the assignment is sequenced [...] before the value computation of the
10477     //   assignment expression.
10478     // C11 6.5.16/3 has no such rule.
10479     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10480                                                        : UK_ModAsSideEffect);
10481   }
10482 
10483   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10484     VisitBinAssign(CAO);
10485   }
10486 
10487   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10488   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10489   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10490     Object O = getObject(UO->getSubExpr(), true);
10491     if (!O)
10492       return VisitExpr(UO);
10493 
10494     notePreMod(O, UO);
10495     Visit(UO->getSubExpr());
10496     // C++11 [expr.pre.incr]p1:
10497     //   the expression ++x is equivalent to x+=1
10498     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10499                                                        : UK_ModAsSideEffect);
10500   }
10501 
10502   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10503   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10504   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10505     Object O = getObject(UO->getSubExpr(), true);
10506     if (!O)
10507       return VisitExpr(UO);
10508 
10509     notePreMod(O, UO);
10510     Visit(UO->getSubExpr());
10511     notePostMod(O, UO, UK_ModAsSideEffect);
10512   }
10513 
10514   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10515   void VisitBinLOr(BinaryOperator *BO) {
10516     // The side-effects of the LHS of an '&&' are sequenced before the
10517     // value computation of the RHS, and hence before the value computation
10518     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10519     // as if they were unconditionally sequenced.
10520     EvaluationTracker Eval(*this);
10521     {
10522       SequencedSubexpression Sequenced(*this);
10523       Visit(BO->getLHS());
10524     }
10525 
10526     bool Result;
10527     if (Eval.evaluate(BO->getLHS(), Result)) {
10528       if (!Result)
10529         Visit(BO->getRHS());
10530     } else {
10531       // Check for unsequenced operations in the RHS, treating it as an
10532       // entirely separate evaluation.
10533       //
10534       // FIXME: If there are operations in the RHS which are unsequenced
10535       // with respect to operations outside the RHS, and those operations
10536       // are unconditionally evaluated, diagnose them.
10537       WorkList.push_back(BO->getRHS());
10538     }
10539   }
10540   void VisitBinLAnd(BinaryOperator *BO) {
10541     EvaluationTracker Eval(*this);
10542     {
10543       SequencedSubexpression Sequenced(*this);
10544       Visit(BO->getLHS());
10545     }
10546 
10547     bool Result;
10548     if (Eval.evaluate(BO->getLHS(), Result)) {
10549       if (Result)
10550         Visit(BO->getRHS());
10551     } else {
10552       WorkList.push_back(BO->getRHS());
10553     }
10554   }
10555 
10556   // Only visit the condition, unless we can be sure which subexpression will
10557   // be chosen.
10558   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10559     EvaluationTracker Eval(*this);
10560     {
10561       SequencedSubexpression Sequenced(*this);
10562       Visit(CO->getCond());
10563     }
10564 
10565     bool Result;
10566     if (Eval.evaluate(CO->getCond(), Result))
10567       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10568     else {
10569       WorkList.push_back(CO->getTrueExpr());
10570       WorkList.push_back(CO->getFalseExpr());
10571     }
10572   }
10573 
10574   void VisitCallExpr(CallExpr *CE) {
10575     // C++11 [intro.execution]p15:
10576     //   When calling a function [...], every value computation and side effect
10577     //   associated with any argument expression, or with the postfix expression
10578     //   designating the called function, is sequenced before execution of every
10579     //   expression or statement in the body of the function [and thus before
10580     //   the value computation of its result].
10581     SequencedSubexpression Sequenced(*this);
10582     Base::VisitCallExpr(CE);
10583 
10584     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10585   }
10586 
10587   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10588     // This is a call, so all subexpressions are sequenced before the result.
10589     SequencedSubexpression Sequenced(*this);
10590 
10591     if (!CCE->isListInitialization())
10592       return VisitExpr(CCE);
10593 
10594     // In C++11, list initializations are sequenced.
10595     SmallVector<SequenceTree::Seq, 32> Elts;
10596     SequenceTree::Seq Parent = Region;
10597     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10598                                         E = CCE->arg_end();
10599          I != E; ++I) {
10600       Region = Tree.allocate(Parent);
10601       Elts.push_back(Region);
10602       Visit(*I);
10603     }
10604 
10605     // Forget that the initializers are sequenced.
10606     Region = Parent;
10607     for (unsigned I = 0; I < Elts.size(); ++I)
10608       Tree.merge(Elts[I]);
10609   }
10610 
10611   void VisitInitListExpr(InitListExpr *ILE) {
10612     if (!SemaRef.getLangOpts().CPlusPlus11)
10613       return VisitExpr(ILE);
10614 
10615     // In C++11, list initializations are sequenced.
10616     SmallVector<SequenceTree::Seq, 32> Elts;
10617     SequenceTree::Seq Parent = Region;
10618     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10619       Expr *E = ILE->getInit(I);
10620       if (!E) continue;
10621       Region = Tree.allocate(Parent);
10622       Elts.push_back(Region);
10623       Visit(E);
10624     }
10625 
10626     // Forget that the initializers are sequenced.
10627     Region = Parent;
10628     for (unsigned I = 0; I < Elts.size(); ++I)
10629       Tree.merge(Elts[I]);
10630   }
10631 };
10632 } // end anonymous namespace
10633 
10634 void Sema::CheckUnsequencedOperations(Expr *E) {
10635   SmallVector<Expr *, 8> WorkList;
10636   WorkList.push_back(E);
10637   while (!WorkList.empty()) {
10638     Expr *Item = WorkList.pop_back_val();
10639     SequenceChecker(*this, Item, WorkList);
10640   }
10641 }
10642 
10643 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10644                               bool IsConstexpr) {
10645   CheckImplicitConversions(E, CheckLoc);
10646   if (!E->isInstantiationDependent())
10647     CheckUnsequencedOperations(E);
10648   if (!IsConstexpr && !E->isValueDependent())
10649     CheckForIntOverflow(E);
10650   DiagnoseMisalignedMembers();
10651 }
10652 
10653 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10654                                        FieldDecl *BitField,
10655                                        Expr *Init) {
10656   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10657 }
10658 
10659 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10660                                          SourceLocation Loc) {
10661   if (!PType->isVariablyModifiedType())
10662     return;
10663   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10664     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10665     return;
10666   }
10667   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10668     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10669     return;
10670   }
10671   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10672     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10673     return;
10674   }
10675 
10676   const ArrayType *AT = S.Context.getAsArrayType(PType);
10677   if (!AT)
10678     return;
10679 
10680   if (AT->getSizeModifier() != ArrayType::Star) {
10681     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10682     return;
10683   }
10684 
10685   S.Diag(Loc, diag::err_array_star_in_function_definition);
10686 }
10687 
10688 /// CheckParmsForFunctionDef - Check that the parameters of the given
10689 /// function are appropriate for the definition of a function. This
10690 /// takes care of any checks that cannot be performed on the
10691 /// declaration itself, e.g., that the types of each of the function
10692 /// parameters are complete.
10693 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10694                                     bool CheckParameterNames) {
10695   bool HasInvalidParm = false;
10696   for (ParmVarDecl *Param : Parameters) {
10697     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10698     // function declarator that is part of a function definition of
10699     // that function shall not have incomplete type.
10700     //
10701     // This is also C++ [dcl.fct]p6.
10702     if (!Param->isInvalidDecl() &&
10703         RequireCompleteType(Param->getLocation(), Param->getType(),
10704                             diag::err_typecheck_decl_incomplete_type)) {
10705       Param->setInvalidDecl();
10706       HasInvalidParm = true;
10707     }
10708 
10709     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10710     // declaration of each parameter shall include an identifier.
10711     if (CheckParameterNames &&
10712         Param->getIdentifier() == nullptr &&
10713         !Param->isImplicit() &&
10714         !getLangOpts().CPlusPlus)
10715       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10716 
10717     // C99 6.7.5.3p12:
10718     //   If the function declarator is not part of a definition of that
10719     //   function, parameters may have incomplete type and may use the [*]
10720     //   notation in their sequences of declarator specifiers to specify
10721     //   variable length array types.
10722     QualType PType = Param->getOriginalType();
10723     // FIXME: This diagnostic should point the '[*]' if source-location
10724     // information is added for it.
10725     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10726 
10727     // MSVC destroys objects passed by value in the callee.  Therefore a
10728     // function definition which takes such a parameter must be able to call the
10729     // object's destructor.  However, we don't perform any direct access check
10730     // on the dtor.
10731     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10732                                        .getCXXABI()
10733                                        .areArgsDestroyedLeftToRightInCallee()) {
10734       if (!Param->isInvalidDecl()) {
10735         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10736           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10737           if (!ClassDecl->isInvalidDecl() &&
10738               !ClassDecl->hasIrrelevantDestructor() &&
10739               !ClassDecl->isDependentContext()) {
10740             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10741             MarkFunctionReferenced(Param->getLocation(), Destructor);
10742             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10743           }
10744         }
10745       }
10746     }
10747 
10748     // Parameters with the pass_object_size attribute only need to be marked
10749     // constant at function definitions. Because we lack information about
10750     // whether we're on a declaration or definition when we're instantiating the
10751     // attribute, we need to check for constness here.
10752     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10753       if (!Param->getType().isConstQualified())
10754         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10755             << Attr->getSpelling() << 1;
10756   }
10757 
10758   return HasInvalidParm;
10759 }
10760 
10761 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10762 /// or MemberExpr.
10763 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10764                               ASTContext &Context) {
10765   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10766     return Context.getDeclAlign(DRE->getDecl());
10767 
10768   if (const auto *ME = dyn_cast<MemberExpr>(E))
10769     return Context.getDeclAlign(ME->getMemberDecl());
10770 
10771   return TypeAlign;
10772 }
10773 
10774 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10775 /// pointer cast increases the alignment requirements.
10776 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10777   // This is actually a lot of work to potentially be doing on every
10778   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10779   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10780     return;
10781 
10782   // Ignore dependent types.
10783   if (T->isDependentType() || Op->getType()->isDependentType())
10784     return;
10785 
10786   // Require that the destination be a pointer type.
10787   const PointerType *DestPtr = T->getAs<PointerType>();
10788   if (!DestPtr) return;
10789 
10790   // If the destination has alignment 1, we're done.
10791   QualType DestPointee = DestPtr->getPointeeType();
10792   if (DestPointee->isIncompleteType()) return;
10793   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10794   if (DestAlign.isOne()) return;
10795 
10796   // Require that the source be a pointer type.
10797   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10798   if (!SrcPtr) return;
10799   QualType SrcPointee = SrcPtr->getPointeeType();
10800 
10801   // Whitelist casts from cv void*.  We already implicitly
10802   // whitelisted casts to cv void*, since they have alignment 1.
10803   // Also whitelist casts involving incomplete types, which implicitly
10804   // includes 'void'.
10805   if (SrcPointee->isIncompleteType()) return;
10806 
10807   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10808 
10809   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10810     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10811       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10812   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10813     if (UO->getOpcode() == UO_AddrOf)
10814       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10815   }
10816 
10817   if (SrcAlign >= DestAlign) return;
10818 
10819   Diag(TRange.getBegin(), diag::warn_cast_align)
10820     << Op->getType() << T
10821     << static_cast<unsigned>(SrcAlign.getQuantity())
10822     << static_cast<unsigned>(DestAlign.getQuantity())
10823     << TRange << Op->getSourceRange();
10824 }
10825 
10826 /// \brief Check whether this array fits the idiom of a size-one tail padded
10827 /// array member of a struct.
10828 ///
10829 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10830 /// commonly used to emulate flexible arrays in C89 code.
10831 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10832                                     const NamedDecl *ND) {
10833   if (Size != 1 || !ND) return false;
10834 
10835   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10836   if (!FD) return false;
10837 
10838   // Don't consider sizes resulting from macro expansions or template argument
10839   // substitution to form C89 tail-padded arrays.
10840 
10841   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10842   while (TInfo) {
10843     TypeLoc TL = TInfo->getTypeLoc();
10844     // Look through typedefs.
10845     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10846       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10847       TInfo = TDL->getTypeSourceInfo();
10848       continue;
10849     }
10850     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10851       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10852       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10853         return false;
10854     }
10855     break;
10856   }
10857 
10858   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10859   if (!RD) return false;
10860   if (RD->isUnion()) return false;
10861   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10862     if (!CRD->isStandardLayout()) return false;
10863   }
10864 
10865   // See if this is the last field decl in the record.
10866   const Decl *D = FD;
10867   while ((D = D->getNextDeclInContext()))
10868     if (isa<FieldDecl>(D))
10869       return false;
10870   return true;
10871 }
10872 
10873 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10874                             const ArraySubscriptExpr *ASE,
10875                             bool AllowOnePastEnd, bool IndexNegated) {
10876   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10877   if (IndexExpr->isValueDependent())
10878     return;
10879 
10880   const Type *EffectiveType =
10881       BaseExpr->getType()->getPointeeOrArrayElementType();
10882   BaseExpr = BaseExpr->IgnoreParenCasts();
10883   const ConstantArrayType *ArrayTy =
10884     Context.getAsConstantArrayType(BaseExpr->getType());
10885   if (!ArrayTy)
10886     return;
10887 
10888   llvm::APSInt index;
10889   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10890     return;
10891   if (IndexNegated)
10892     index = -index;
10893 
10894   const NamedDecl *ND = nullptr;
10895   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10896     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10897   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10898     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10899 
10900   if (index.isUnsigned() || !index.isNegative()) {
10901     llvm::APInt size = ArrayTy->getSize();
10902     if (!size.isStrictlyPositive())
10903       return;
10904 
10905     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10906     if (BaseType != EffectiveType) {
10907       // Make sure we're comparing apples to apples when comparing index to size
10908       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10909       uint64_t array_typesize = Context.getTypeSize(BaseType);
10910       // Handle ptrarith_typesize being zero, such as when casting to void*
10911       if (!ptrarith_typesize) ptrarith_typesize = 1;
10912       if (ptrarith_typesize != array_typesize) {
10913         // There's a cast to a different size type involved
10914         uint64_t ratio = array_typesize / ptrarith_typesize;
10915         // TODO: Be smarter about handling cases where array_typesize is not a
10916         // multiple of ptrarith_typesize
10917         if (ptrarith_typesize * ratio == array_typesize)
10918           size *= llvm::APInt(size.getBitWidth(), ratio);
10919       }
10920     }
10921 
10922     if (size.getBitWidth() > index.getBitWidth())
10923       index = index.zext(size.getBitWidth());
10924     else if (size.getBitWidth() < index.getBitWidth())
10925       size = size.zext(index.getBitWidth());
10926 
10927     // For array subscripting the index must be less than size, but for pointer
10928     // arithmetic also allow the index (offset) to be equal to size since
10929     // computing the next address after the end of the array is legal and
10930     // commonly done e.g. in C++ iterators and range-based for loops.
10931     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10932       return;
10933 
10934     // Also don't warn for arrays of size 1 which are members of some
10935     // structure. These are often used to approximate flexible arrays in C89
10936     // code.
10937     if (IsTailPaddedMemberArray(*this, size, ND))
10938       return;
10939 
10940     // Suppress the warning if the subscript expression (as identified by the
10941     // ']' location) and the index expression are both from macro expansions
10942     // within a system header.
10943     if (ASE) {
10944       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10945           ASE->getRBracketLoc());
10946       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10947         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10948             IndexExpr->getLocStart());
10949         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10950           return;
10951       }
10952     }
10953 
10954     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10955     if (ASE)
10956       DiagID = diag::warn_array_index_exceeds_bounds;
10957 
10958     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10959                         PDiag(DiagID) << index.toString(10, true)
10960                           << size.toString(10, true)
10961                           << (unsigned)size.getLimitedValue(~0U)
10962                           << IndexExpr->getSourceRange());
10963   } else {
10964     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10965     if (!ASE) {
10966       DiagID = diag::warn_ptr_arith_precedes_bounds;
10967       if (index.isNegative()) index = -index;
10968     }
10969 
10970     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10971                         PDiag(DiagID) << index.toString(10, true)
10972                           << IndexExpr->getSourceRange());
10973   }
10974 
10975   if (!ND) {
10976     // Try harder to find a NamedDecl to point at in the note.
10977     while (const ArraySubscriptExpr *ASE =
10978            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10979       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10980     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10981       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10982     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10983       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10984   }
10985 
10986   if (ND)
10987     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10988                         PDiag(diag::note_array_index_out_of_bounds)
10989                           << ND->getDeclName());
10990 }
10991 
10992 void Sema::CheckArrayAccess(const Expr *expr) {
10993   int AllowOnePastEnd = 0;
10994   while (expr) {
10995     expr = expr->IgnoreParenImpCasts();
10996     switch (expr->getStmtClass()) {
10997       case Stmt::ArraySubscriptExprClass: {
10998         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
10999         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11000                          AllowOnePastEnd > 0);
11001         return;
11002       }
11003       case Stmt::OMPArraySectionExprClass: {
11004         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11005         if (ASE->getLowerBound())
11006           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11007                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11008         return;
11009       }
11010       case Stmt::UnaryOperatorClass: {
11011         // Only unwrap the * and & unary operators
11012         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11013         expr = UO->getSubExpr();
11014         switch (UO->getOpcode()) {
11015           case UO_AddrOf:
11016             AllowOnePastEnd++;
11017             break;
11018           case UO_Deref:
11019             AllowOnePastEnd--;
11020             break;
11021           default:
11022             return;
11023         }
11024         break;
11025       }
11026       case Stmt::ConditionalOperatorClass: {
11027         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11028         if (const Expr *lhs = cond->getLHS())
11029           CheckArrayAccess(lhs);
11030         if (const Expr *rhs = cond->getRHS())
11031           CheckArrayAccess(rhs);
11032         return;
11033       }
11034       case Stmt::CXXOperatorCallExprClass: {
11035         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11036         for (const auto *Arg : OCE->arguments())
11037           CheckArrayAccess(Arg);
11038         return;
11039       }
11040       default:
11041         return;
11042     }
11043   }
11044 }
11045 
11046 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11047 
11048 namespace {
11049   struct RetainCycleOwner {
11050     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
11051     VarDecl *Variable;
11052     SourceRange Range;
11053     SourceLocation Loc;
11054     bool Indirect;
11055 
11056     void setLocsFrom(Expr *e) {
11057       Loc = e->getExprLoc();
11058       Range = e->getSourceRange();
11059     }
11060   };
11061 } // end anonymous namespace
11062 
11063 /// Consider whether capturing the given variable can possibly lead to
11064 /// a retain cycle.
11065 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11066   // In ARC, it's captured strongly iff the variable has __strong
11067   // lifetime.  In MRR, it's captured strongly if the variable is
11068   // __block and has an appropriate type.
11069   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11070     return false;
11071 
11072   owner.Variable = var;
11073   if (ref)
11074     owner.setLocsFrom(ref);
11075   return true;
11076 }
11077 
11078 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11079   while (true) {
11080     e = e->IgnoreParens();
11081     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11082       switch (cast->getCastKind()) {
11083       case CK_BitCast:
11084       case CK_LValueBitCast:
11085       case CK_LValueToRValue:
11086       case CK_ARCReclaimReturnedObject:
11087         e = cast->getSubExpr();
11088         continue;
11089 
11090       default:
11091         return false;
11092       }
11093     }
11094 
11095     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11096       ObjCIvarDecl *ivar = ref->getDecl();
11097       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11098         return false;
11099 
11100       // Try to find a retain cycle in the base.
11101       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11102         return false;
11103 
11104       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11105       owner.Indirect = true;
11106       return true;
11107     }
11108 
11109     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11110       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11111       if (!var) return false;
11112       return considerVariable(var, ref, owner);
11113     }
11114 
11115     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11116       if (member->isArrow()) return false;
11117 
11118       // Don't count this as an indirect ownership.
11119       e = member->getBase();
11120       continue;
11121     }
11122 
11123     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11124       // Only pay attention to pseudo-objects on property references.
11125       ObjCPropertyRefExpr *pre
11126         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11127                                               ->IgnoreParens());
11128       if (!pre) return false;
11129       if (pre->isImplicitProperty()) return false;
11130       ObjCPropertyDecl *property = pre->getExplicitProperty();
11131       if (!property->isRetaining() &&
11132           !(property->getPropertyIvarDecl() &&
11133             property->getPropertyIvarDecl()->getType()
11134               .getObjCLifetime() == Qualifiers::OCL_Strong))
11135           return false;
11136 
11137       owner.Indirect = true;
11138       if (pre->isSuperReceiver()) {
11139         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11140         if (!owner.Variable)
11141           return false;
11142         owner.Loc = pre->getLocation();
11143         owner.Range = pre->getSourceRange();
11144         return true;
11145       }
11146       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11147                               ->getSourceExpr());
11148       continue;
11149     }
11150 
11151     // Array ivars?
11152 
11153     return false;
11154   }
11155 }
11156 
11157 namespace {
11158   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11159     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11160       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11161         Context(Context), Variable(variable), Capturer(nullptr),
11162         VarWillBeReased(false) {}
11163     ASTContext &Context;
11164     VarDecl *Variable;
11165     Expr *Capturer;
11166     bool VarWillBeReased;
11167 
11168     void VisitDeclRefExpr(DeclRefExpr *ref) {
11169       if (ref->getDecl() == Variable && !Capturer)
11170         Capturer = ref;
11171     }
11172 
11173     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11174       if (Capturer) return;
11175       Visit(ref->getBase());
11176       if (Capturer && ref->isFreeIvar())
11177         Capturer = ref;
11178     }
11179 
11180     void VisitBlockExpr(BlockExpr *block) {
11181       // Look inside nested blocks
11182       if (block->getBlockDecl()->capturesVariable(Variable))
11183         Visit(block->getBlockDecl()->getBody());
11184     }
11185 
11186     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11187       if (Capturer) return;
11188       if (OVE->getSourceExpr())
11189         Visit(OVE->getSourceExpr());
11190     }
11191     void VisitBinaryOperator(BinaryOperator *BinOp) {
11192       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11193         return;
11194       Expr *LHS = BinOp->getLHS();
11195       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11196         if (DRE->getDecl() != Variable)
11197           return;
11198         if (Expr *RHS = BinOp->getRHS()) {
11199           RHS = RHS->IgnoreParenCasts();
11200           llvm::APSInt Value;
11201           VarWillBeReased =
11202             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11203         }
11204       }
11205     }
11206   };
11207 } // end anonymous namespace
11208 
11209 /// Check whether the given argument is a block which captures a
11210 /// variable.
11211 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11212   assert(owner.Variable && owner.Loc.isValid());
11213 
11214   e = e->IgnoreParenCasts();
11215 
11216   // Look through [^{...} copy] and Block_copy(^{...}).
11217   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11218     Selector Cmd = ME->getSelector();
11219     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11220       e = ME->getInstanceReceiver();
11221       if (!e)
11222         return nullptr;
11223       e = e->IgnoreParenCasts();
11224     }
11225   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11226     if (CE->getNumArgs() == 1) {
11227       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11228       if (Fn) {
11229         const IdentifierInfo *FnI = Fn->getIdentifier();
11230         if (FnI && FnI->isStr("_Block_copy")) {
11231           e = CE->getArg(0)->IgnoreParenCasts();
11232         }
11233       }
11234     }
11235   }
11236 
11237   BlockExpr *block = dyn_cast<BlockExpr>(e);
11238   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11239     return nullptr;
11240 
11241   FindCaptureVisitor visitor(S.Context, owner.Variable);
11242   visitor.Visit(block->getBlockDecl()->getBody());
11243   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11244 }
11245 
11246 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11247                                 RetainCycleOwner &owner) {
11248   assert(capturer);
11249   assert(owner.Variable && owner.Loc.isValid());
11250 
11251   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11252     << owner.Variable << capturer->getSourceRange();
11253   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11254     << owner.Indirect << owner.Range;
11255 }
11256 
11257 /// Check for a keyword selector that starts with the word 'add' or
11258 /// 'set'.
11259 static bool isSetterLikeSelector(Selector sel) {
11260   if (sel.isUnarySelector()) return false;
11261 
11262   StringRef str = sel.getNameForSlot(0);
11263   while (!str.empty() && str.front() == '_') str = str.substr(1);
11264   if (str.startswith("set"))
11265     str = str.substr(3);
11266   else if (str.startswith("add")) {
11267     // Specially whitelist 'addOperationWithBlock:'.
11268     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11269       return false;
11270     str = str.substr(3);
11271   }
11272   else
11273     return false;
11274 
11275   if (str.empty()) return true;
11276   return !isLowercase(str.front());
11277 }
11278 
11279 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11280                                                     ObjCMessageExpr *Message) {
11281   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11282                                                 Message->getReceiverInterface(),
11283                                                 NSAPI::ClassId_NSMutableArray);
11284   if (!IsMutableArray) {
11285     return None;
11286   }
11287 
11288   Selector Sel = Message->getSelector();
11289 
11290   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11291     S.NSAPIObj->getNSArrayMethodKind(Sel);
11292   if (!MKOpt) {
11293     return None;
11294   }
11295 
11296   NSAPI::NSArrayMethodKind MK = *MKOpt;
11297 
11298   switch (MK) {
11299     case NSAPI::NSMutableArr_addObject:
11300     case NSAPI::NSMutableArr_insertObjectAtIndex:
11301     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11302       return 0;
11303     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11304       return 1;
11305 
11306     default:
11307       return None;
11308   }
11309 
11310   return None;
11311 }
11312 
11313 static
11314 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11315                                                   ObjCMessageExpr *Message) {
11316   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11317                                             Message->getReceiverInterface(),
11318                                             NSAPI::ClassId_NSMutableDictionary);
11319   if (!IsMutableDictionary) {
11320     return None;
11321   }
11322 
11323   Selector Sel = Message->getSelector();
11324 
11325   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11326     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11327   if (!MKOpt) {
11328     return None;
11329   }
11330 
11331   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11332 
11333   switch (MK) {
11334     case NSAPI::NSMutableDict_setObjectForKey:
11335     case NSAPI::NSMutableDict_setValueForKey:
11336     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11337       return 0;
11338 
11339     default:
11340       return None;
11341   }
11342 
11343   return None;
11344 }
11345 
11346 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11347   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11348                                                 Message->getReceiverInterface(),
11349                                                 NSAPI::ClassId_NSMutableSet);
11350 
11351   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11352                                             Message->getReceiverInterface(),
11353                                             NSAPI::ClassId_NSMutableOrderedSet);
11354   if (!IsMutableSet && !IsMutableOrderedSet) {
11355     return None;
11356   }
11357 
11358   Selector Sel = Message->getSelector();
11359 
11360   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11361   if (!MKOpt) {
11362     return None;
11363   }
11364 
11365   NSAPI::NSSetMethodKind MK = *MKOpt;
11366 
11367   switch (MK) {
11368     case NSAPI::NSMutableSet_addObject:
11369     case NSAPI::NSOrderedSet_setObjectAtIndex:
11370     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11371     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11372       return 0;
11373     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11374       return 1;
11375   }
11376 
11377   return None;
11378 }
11379 
11380 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11381   if (!Message->isInstanceMessage()) {
11382     return;
11383   }
11384 
11385   Optional<int> ArgOpt;
11386 
11387   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11388       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11389       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11390     return;
11391   }
11392 
11393   int ArgIndex = *ArgOpt;
11394 
11395   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11396   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11397     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11398   }
11399 
11400   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11401     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11402       if (ArgRE->isObjCSelfExpr()) {
11403         Diag(Message->getSourceRange().getBegin(),
11404              diag::warn_objc_circular_container)
11405           << ArgRE->getDecl()->getName() << StringRef("super");
11406       }
11407     }
11408   } else {
11409     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11410 
11411     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11412       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11413     }
11414 
11415     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11416       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11417         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11418           ValueDecl *Decl = ReceiverRE->getDecl();
11419           Diag(Message->getSourceRange().getBegin(),
11420                diag::warn_objc_circular_container)
11421             << Decl->getName() << Decl->getName();
11422           if (!ArgRE->isObjCSelfExpr()) {
11423             Diag(Decl->getLocation(),
11424                  diag::note_objc_circular_container_declared_here)
11425               << Decl->getName();
11426           }
11427         }
11428       }
11429     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11430       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11431         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11432           ObjCIvarDecl *Decl = IvarRE->getDecl();
11433           Diag(Message->getSourceRange().getBegin(),
11434                diag::warn_objc_circular_container)
11435             << Decl->getName() << Decl->getName();
11436           Diag(Decl->getLocation(),
11437                diag::note_objc_circular_container_declared_here)
11438             << Decl->getName();
11439         }
11440       }
11441     }
11442   }
11443 }
11444 
11445 /// Check a message send to see if it's likely to cause a retain cycle.
11446 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11447   // Only check instance methods whose selector looks like a setter.
11448   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11449     return;
11450 
11451   // Try to find a variable that the receiver is strongly owned by.
11452   RetainCycleOwner owner;
11453   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11454     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11455       return;
11456   } else {
11457     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11458     owner.Variable = getCurMethodDecl()->getSelfDecl();
11459     owner.Loc = msg->getSuperLoc();
11460     owner.Range = msg->getSuperLoc();
11461   }
11462 
11463   // Check whether the receiver is captured by any of the arguments.
11464   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11465     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11466       return diagnoseRetainCycle(*this, capturer, owner);
11467 }
11468 
11469 /// Check a property assign to see if it's likely to cause a retain cycle.
11470 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11471   RetainCycleOwner owner;
11472   if (!findRetainCycleOwner(*this, receiver, owner))
11473     return;
11474 
11475   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11476     diagnoseRetainCycle(*this, capturer, owner);
11477 }
11478 
11479 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11480   RetainCycleOwner Owner;
11481   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11482     return;
11483 
11484   // Because we don't have an expression for the variable, we have to set the
11485   // location explicitly here.
11486   Owner.Loc = Var->getLocation();
11487   Owner.Range = Var->getSourceRange();
11488 
11489   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11490     diagnoseRetainCycle(*this, Capturer, Owner);
11491 }
11492 
11493 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11494                                      Expr *RHS, bool isProperty) {
11495   // Check if RHS is an Objective-C object literal, which also can get
11496   // immediately zapped in a weak reference.  Note that we explicitly
11497   // allow ObjCStringLiterals, since those are designed to never really die.
11498   RHS = RHS->IgnoreParenImpCasts();
11499 
11500   // This enum needs to match with the 'select' in
11501   // warn_objc_arc_literal_assign (off-by-1).
11502   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11503   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11504     return false;
11505 
11506   S.Diag(Loc, diag::warn_arc_literal_assign)
11507     << (unsigned) Kind
11508     << (isProperty ? 0 : 1)
11509     << RHS->getSourceRange();
11510 
11511   return true;
11512 }
11513 
11514 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11515                                     Qualifiers::ObjCLifetime LT,
11516                                     Expr *RHS, bool isProperty) {
11517   // Strip off any implicit cast added to get to the one ARC-specific.
11518   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11519     if (cast->getCastKind() == CK_ARCConsumeObject) {
11520       S.Diag(Loc, diag::warn_arc_retained_assign)
11521         << (LT == Qualifiers::OCL_ExplicitNone)
11522         << (isProperty ? 0 : 1)
11523         << RHS->getSourceRange();
11524       return true;
11525     }
11526     RHS = cast->getSubExpr();
11527   }
11528 
11529   if (LT == Qualifiers::OCL_Weak &&
11530       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11531     return true;
11532 
11533   return false;
11534 }
11535 
11536 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11537                               QualType LHS, Expr *RHS) {
11538   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11539 
11540   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11541     return false;
11542 
11543   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11544     return true;
11545 
11546   return false;
11547 }
11548 
11549 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11550                               Expr *LHS, Expr *RHS) {
11551   QualType LHSType;
11552   // PropertyRef on LHS type need be directly obtained from
11553   // its declaration as it has a PseudoType.
11554   ObjCPropertyRefExpr *PRE
11555     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11556   if (PRE && !PRE->isImplicitProperty()) {
11557     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11558     if (PD)
11559       LHSType = PD->getType();
11560   }
11561 
11562   if (LHSType.isNull())
11563     LHSType = LHS->getType();
11564 
11565   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11566 
11567   if (LT == Qualifiers::OCL_Weak) {
11568     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11569       getCurFunction()->markSafeWeakUse(LHS);
11570   }
11571 
11572   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11573     return;
11574 
11575   // FIXME. Check for other life times.
11576   if (LT != Qualifiers::OCL_None)
11577     return;
11578 
11579   if (PRE) {
11580     if (PRE->isImplicitProperty())
11581       return;
11582     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11583     if (!PD)
11584       return;
11585 
11586     unsigned Attributes = PD->getPropertyAttributes();
11587     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11588       // when 'assign' attribute was not explicitly specified
11589       // by user, ignore it and rely on property type itself
11590       // for lifetime info.
11591       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11592       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11593           LHSType->isObjCRetainableType())
11594         return;
11595 
11596       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11597         if (cast->getCastKind() == CK_ARCConsumeObject) {
11598           Diag(Loc, diag::warn_arc_retained_property_assign)
11599           << RHS->getSourceRange();
11600           return;
11601         }
11602         RHS = cast->getSubExpr();
11603       }
11604     }
11605     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11606       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11607         return;
11608     }
11609   }
11610 }
11611 
11612 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11613 
11614 namespace {
11615 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11616                                  SourceLocation StmtLoc,
11617                                  const NullStmt *Body) {
11618   // Do not warn if the body is a macro that expands to nothing, e.g:
11619   //
11620   // #define CALL(x)
11621   // if (condition)
11622   //   CALL(0);
11623   //
11624   if (Body->hasLeadingEmptyMacro())
11625     return false;
11626 
11627   // Get line numbers of statement and body.
11628   bool StmtLineInvalid;
11629   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11630                                                       &StmtLineInvalid);
11631   if (StmtLineInvalid)
11632     return false;
11633 
11634   bool BodyLineInvalid;
11635   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11636                                                       &BodyLineInvalid);
11637   if (BodyLineInvalid)
11638     return false;
11639 
11640   // Warn if null statement and body are on the same line.
11641   if (StmtLine != BodyLine)
11642     return false;
11643 
11644   return true;
11645 }
11646 } // end anonymous namespace
11647 
11648 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11649                                  const Stmt *Body,
11650                                  unsigned DiagID) {
11651   // Since this is a syntactic check, don't emit diagnostic for template
11652   // instantiations, this just adds noise.
11653   if (CurrentInstantiationScope)
11654     return;
11655 
11656   // The body should be a null statement.
11657   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11658   if (!NBody)
11659     return;
11660 
11661   // Do the usual checks.
11662   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11663     return;
11664 
11665   Diag(NBody->getSemiLoc(), DiagID);
11666   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11667 }
11668 
11669 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11670                                  const Stmt *PossibleBody) {
11671   assert(!CurrentInstantiationScope); // Ensured by caller
11672 
11673   SourceLocation StmtLoc;
11674   const Stmt *Body;
11675   unsigned DiagID;
11676   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11677     StmtLoc = FS->getRParenLoc();
11678     Body = FS->getBody();
11679     DiagID = diag::warn_empty_for_body;
11680   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11681     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11682     Body = WS->getBody();
11683     DiagID = diag::warn_empty_while_body;
11684   } else
11685     return; // Neither `for' nor `while'.
11686 
11687   // The body should be a null statement.
11688   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11689   if (!NBody)
11690     return;
11691 
11692   // Skip expensive checks if diagnostic is disabled.
11693   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11694     return;
11695 
11696   // Do the usual checks.
11697   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11698     return;
11699 
11700   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11701   // noise level low, emit diagnostics only if for/while is followed by a
11702   // CompoundStmt, e.g.:
11703   //    for (int i = 0; i < n; i++);
11704   //    {
11705   //      a(i);
11706   //    }
11707   // or if for/while is followed by a statement with more indentation
11708   // than for/while itself:
11709   //    for (int i = 0; i < n; i++);
11710   //      a(i);
11711   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11712   if (!ProbableTypo) {
11713     bool BodyColInvalid;
11714     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11715                              PossibleBody->getLocStart(),
11716                              &BodyColInvalid);
11717     if (BodyColInvalid)
11718       return;
11719 
11720     bool StmtColInvalid;
11721     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11722                              S->getLocStart(),
11723                              &StmtColInvalid);
11724     if (StmtColInvalid)
11725       return;
11726 
11727     if (BodyCol > StmtCol)
11728       ProbableTypo = true;
11729   }
11730 
11731   if (ProbableTypo) {
11732     Diag(NBody->getSemiLoc(), DiagID);
11733     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11734   }
11735 }
11736 
11737 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11738 
11739 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11740 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11741                              SourceLocation OpLoc) {
11742   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11743     return;
11744 
11745   if (inTemplateInstantiation())
11746     return;
11747 
11748   // Strip parens and casts away.
11749   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11750   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11751 
11752   // Check for a call expression
11753   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11754   if (!CE || CE->getNumArgs() != 1)
11755     return;
11756 
11757   // Check for a call to std::move
11758   const FunctionDecl *FD = CE->getDirectCallee();
11759   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
11760       !FD->getIdentifier()->isStr("move"))
11761     return;
11762 
11763   // Get argument from std::move
11764   RHSExpr = CE->getArg(0);
11765 
11766   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11767   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11768 
11769   // Two DeclRefExpr's, check that the decls are the same.
11770   if (LHSDeclRef && RHSDeclRef) {
11771     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11772       return;
11773     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11774         RHSDeclRef->getDecl()->getCanonicalDecl())
11775       return;
11776 
11777     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11778                                         << LHSExpr->getSourceRange()
11779                                         << RHSExpr->getSourceRange();
11780     return;
11781   }
11782 
11783   // Member variables require a different approach to check for self moves.
11784   // MemberExpr's are the same if every nested MemberExpr refers to the same
11785   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11786   // the base Expr's are CXXThisExpr's.
11787   const Expr *LHSBase = LHSExpr;
11788   const Expr *RHSBase = RHSExpr;
11789   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11790   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11791   if (!LHSME || !RHSME)
11792     return;
11793 
11794   while (LHSME && RHSME) {
11795     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11796         RHSME->getMemberDecl()->getCanonicalDecl())
11797       return;
11798 
11799     LHSBase = LHSME->getBase();
11800     RHSBase = RHSME->getBase();
11801     LHSME = dyn_cast<MemberExpr>(LHSBase);
11802     RHSME = dyn_cast<MemberExpr>(RHSBase);
11803   }
11804 
11805   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11806   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11807   if (LHSDeclRef && RHSDeclRef) {
11808     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11809       return;
11810     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11811         RHSDeclRef->getDecl()->getCanonicalDecl())
11812       return;
11813 
11814     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11815                                         << LHSExpr->getSourceRange()
11816                                         << RHSExpr->getSourceRange();
11817     return;
11818   }
11819 
11820   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11821     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11822                                         << LHSExpr->getSourceRange()
11823                                         << RHSExpr->getSourceRange();
11824 }
11825 
11826 //===--- Layout compatibility ----------------------------------------------//
11827 
11828 namespace {
11829 
11830 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11831 
11832 /// \brief Check if two enumeration types are layout-compatible.
11833 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11834   // C++11 [dcl.enum] p8:
11835   // Two enumeration types are layout-compatible if they have the same
11836   // underlying type.
11837   return ED1->isComplete() && ED2->isComplete() &&
11838          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11839 }
11840 
11841 /// \brief Check if two fields are layout-compatible.
11842 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11843   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11844     return false;
11845 
11846   if (Field1->isBitField() != Field2->isBitField())
11847     return false;
11848 
11849   if (Field1->isBitField()) {
11850     // Make sure that the bit-fields are the same length.
11851     unsigned Bits1 = Field1->getBitWidthValue(C);
11852     unsigned Bits2 = Field2->getBitWidthValue(C);
11853 
11854     if (Bits1 != Bits2)
11855       return false;
11856   }
11857 
11858   return true;
11859 }
11860 
11861 /// \brief Check if two standard-layout structs are layout-compatible.
11862 /// (C++11 [class.mem] p17)
11863 bool isLayoutCompatibleStruct(ASTContext &C,
11864                               RecordDecl *RD1,
11865                               RecordDecl *RD2) {
11866   // If both records are C++ classes, check that base classes match.
11867   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11868     // If one of records is a CXXRecordDecl we are in C++ mode,
11869     // thus the other one is a CXXRecordDecl, too.
11870     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11871     // Check number of base classes.
11872     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11873       return false;
11874 
11875     // Check the base classes.
11876     for (CXXRecordDecl::base_class_const_iterator
11877                Base1 = D1CXX->bases_begin(),
11878            BaseEnd1 = D1CXX->bases_end(),
11879               Base2 = D2CXX->bases_begin();
11880          Base1 != BaseEnd1;
11881          ++Base1, ++Base2) {
11882       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11883         return false;
11884     }
11885   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11886     // If only RD2 is a C++ class, it should have zero base classes.
11887     if (D2CXX->getNumBases() > 0)
11888       return false;
11889   }
11890 
11891   // Check the fields.
11892   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11893                              Field2End = RD2->field_end(),
11894                              Field1 = RD1->field_begin(),
11895                              Field1End = RD1->field_end();
11896   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11897     if (!isLayoutCompatible(C, *Field1, *Field2))
11898       return false;
11899   }
11900   if (Field1 != Field1End || Field2 != Field2End)
11901     return false;
11902 
11903   return true;
11904 }
11905 
11906 /// \brief Check if two standard-layout unions are layout-compatible.
11907 /// (C++11 [class.mem] p18)
11908 bool isLayoutCompatibleUnion(ASTContext &C,
11909                              RecordDecl *RD1,
11910                              RecordDecl *RD2) {
11911   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11912   for (auto *Field2 : RD2->fields())
11913     UnmatchedFields.insert(Field2);
11914 
11915   for (auto *Field1 : RD1->fields()) {
11916     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11917         I = UnmatchedFields.begin(),
11918         E = UnmatchedFields.end();
11919 
11920     for ( ; I != E; ++I) {
11921       if (isLayoutCompatible(C, Field1, *I)) {
11922         bool Result = UnmatchedFields.erase(*I);
11923         (void) Result;
11924         assert(Result);
11925         break;
11926       }
11927     }
11928     if (I == E)
11929       return false;
11930   }
11931 
11932   return UnmatchedFields.empty();
11933 }
11934 
11935 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11936   if (RD1->isUnion() != RD2->isUnion())
11937     return false;
11938 
11939   if (RD1->isUnion())
11940     return isLayoutCompatibleUnion(C, RD1, RD2);
11941   else
11942     return isLayoutCompatibleStruct(C, RD1, RD2);
11943 }
11944 
11945 /// \brief Check if two types are layout-compatible in C++11 sense.
11946 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11947   if (T1.isNull() || T2.isNull())
11948     return false;
11949 
11950   // C++11 [basic.types] p11:
11951   // If two types T1 and T2 are the same type, then T1 and T2 are
11952   // layout-compatible types.
11953   if (C.hasSameType(T1, T2))
11954     return true;
11955 
11956   T1 = T1.getCanonicalType().getUnqualifiedType();
11957   T2 = T2.getCanonicalType().getUnqualifiedType();
11958 
11959   const Type::TypeClass TC1 = T1->getTypeClass();
11960   const Type::TypeClass TC2 = T2->getTypeClass();
11961 
11962   if (TC1 != TC2)
11963     return false;
11964 
11965   if (TC1 == Type::Enum) {
11966     return isLayoutCompatible(C,
11967                               cast<EnumType>(T1)->getDecl(),
11968                               cast<EnumType>(T2)->getDecl());
11969   } else if (TC1 == Type::Record) {
11970     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11971       return false;
11972 
11973     return isLayoutCompatible(C,
11974                               cast<RecordType>(T1)->getDecl(),
11975                               cast<RecordType>(T2)->getDecl());
11976   }
11977 
11978   return false;
11979 }
11980 } // end anonymous namespace
11981 
11982 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11983 
11984 namespace {
11985 /// \brief Given a type tag expression find the type tag itself.
11986 ///
11987 /// \param TypeExpr Type tag expression, as it appears in user's code.
11988 ///
11989 /// \param VD Declaration of an identifier that appears in a type tag.
11990 ///
11991 /// \param MagicValue Type tag magic value.
11992 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
11993                      const ValueDecl **VD, uint64_t *MagicValue) {
11994   while(true) {
11995     if (!TypeExpr)
11996       return false;
11997 
11998     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
11999 
12000     switch (TypeExpr->getStmtClass()) {
12001     case Stmt::UnaryOperatorClass: {
12002       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12003       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12004         TypeExpr = UO->getSubExpr();
12005         continue;
12006       }
12007       return false;
12008     }
12009 
12010     case Stmt::DeclRefExprClass: {
12011       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12012       *VD = DRE->getDecl();
12013       return true;
12014     }
12015 
12016     case Stmt::IntegerLiteralClass: {
12017       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12018       llvm::APInt MagicValueAPInt = IL->getValue();
12019       if (MagicValueAPInt.getActiveBits() <= 64) {
12020         *MagicValue = MagicValueAPInt.getZExtValue();
12021         return true;
12022       } else
12023         return false;
12024     }
12025 
12026     case Stmt::BinaryConditionalOperatorClass:
12027     case Stmt::ConditionalOperatorClass: {
12028       const AbstractConditionalOperator *ACO =
12029           cast<AbstractConditionalOperator>(TypeExpr);
12030       bool Result;
12031       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12032         if (Result)
12033           TypeExpr = ACO->getTrueExpr();
12034         else
12035           TypeExpr = ACO->getFalseExpr();
12036         continue;
12037       }
12038       return false;
12039     }
12040 
12041     case Stmt::BinaryOperatorClass: {
12042       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12043       if (BO->getOpcode() == BO_Comma) {
12044         TypeExpr = BO->getRHS();
12045         continue;
12046       }
12047       return false;
12048     }
12049 
12050     default:
12051       return false;
12052     }
12053   }
12054 }
12055 
12056 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12057 ///
12058 /// \param TypeExpr Expression that specifies a type tag.
12059 ///
12060 /// \param MagicValues Registered magic values.
12061 ///
12062 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12063 ///        kind.
12064 ///
12065 /// \param TypeInfo Information about the corresponding C type.
12066 ///
12067 /// \returns true if the corresponding C type was found.
12068 bool GetMatchingCType(
12069         const IdentifierInfo *ArgumentKind,
12070         const Expr *TypeExpr, const ASTContext &Ctx,
12071         const llvm::DenseMap<Sema::TypeTagMagicValue,
12072                              Sema::TypeTagData> *MagicValues,
12073         bool &FoundWrongKind,
12074         Sema::TypeTagData &TypeInfo) {
12075   FoundWrongKind = false;
12076 
12077   // Variable declaration that has type_tag_for_datatype attribute.
12078   const ValueDecl *VD = nullptr;
12079 
12080   uint64_t MagicValue;
12081 
12082   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12083     return false;
12084 
12085   if (VD) {
12086     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12087       if (I->getArgumentKind() != ArgumentKind) {
12088         FoundWrongKind = true;
12089         return false;
12090       }
12091       TypeInfo.Type = I->getMatchingCType();
12092       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12093       TypeInfo.MustBeNull = I->getMustBeNull();
12094       return true;
12095     }
12096     return false;
12097   }
12098 
12099   if (!MagicValues)
12100     return false;
12101 
12102   llvm::DenseMap<Sema::TypeTagMagicValue,
12103                  Sema::TypeTagData>::const_iterator I =
12104       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12105   if (I == MagicValues->end())
12106     return false;
12107 
12108   TypeInfo = I->second;
12109   return true;
12110 }
12111 } // end anonymous namespace
12112 
12113 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12114                                       uint64_t MagicValue, QualType Type,
12115                                       bool LayoutCompatible,
12116                                       bool MustBeNull) {
12117   if (!TypeTagForDatatypeMagicValues)
12118     TypeTagForDatatypeMagicValues.reset(
12119         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12120 
12121   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12122   (*TypeTagForDatatypeMagicValues)[Magic] =
12123       TypeTagData(Type, LayoutCompatible, MustBeNull);
12124 }
12125 
12126 namespace {
12127 bool IsSameCharType(QualType T1, QualType T2) {
12128   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12129   if (!BT1)
12130     return false;
12131 
12132   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12133   if (!BT2)
12134     return false;
12135 
12136   BuiltinType::Kind T1Kind = BT1->getKind();
12137   BuiltinType::Kind T2Kind = BT2->getKind();
12138 
12139   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12140          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12141          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12142          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12143 }
12144 } // end anonymous namespace
12145 
12146 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12147                                     const Expr * const *ExprArgs) {
12148   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12149   bool IsPointerAttr = Attr->getIsPointer();
12150 
12151   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12152   bool FoundWrongKind;
12153   TypeTagData TypeInfo;
12154   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12155                         TypeTagForDatatypeMagicValues.get(),
12156                         FoundWrongKind, TypeInfo)) {
12157     if (FoundWrongKind)
12158       Diag(TypeTagExpr->getExprLoc(),
12159            diag::warn_type_tag_for_datatype_wrong_kind)
12160         << TypeTagExpr->getSourceRange();
12161     return;
12162   }
12163 
12164   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12165   if (IsPointerAttr) {
12166     // Skip implicit cast of pointer to `void *' (as a function argument).
12167     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12168       if (ICE->getType()->isVoidPointerType() &&
12169           ICE->getCastKind() == CK_BitCast)
12170         ArgumentExpr = ICE->getSubExpr();
12171   }
12172   QualType ArgumentType = ArgumentExpr->getType();
12173 
12174   // Passing a `void*' pointer shouldn't trigger a warning.
12175   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12176     return;
12177 
12178   if (TypeInfo.MustBeNull) {
12179     // Type tag with matching void type requires a null pointer.
12180     if (!ArgumentExpr->isNullPointerConstant(Context,
12181                                              Expr::NPC_ValueDependentIsNotNull)) {
12182       Diag(ArgumentExpr->getExprLoc(),
12183            diag::warn_type_safety_null_pointer_required)
12184           << ArgumentKind->getName()
12185           << ArgumentExpr->getSourceRange()
12186           << TypeTagExpr->getSourceRange();
12187     }
12188     return;
12189   }
12190 
12191   QualType RequiredType = TypeInfo.Type;
12192   if (IsPointerAttr)
12193     RequiredType = Context.getPointerType(RequiredType);
12194 
12195   bool mismatch = false;
12196   if (!TypeInfo.LayoutCompatible) {
12197     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12198 
12199     // C++11 [basic.fundamental] p1:
12200     // Plain char, signed char, and unsigned char are three distinct types.
12201     //
12202     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12203     // char' depending on the current char signedness mode.
12204     if (mismatch)
12205       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12206                                            RequiredType->getPointeeType())) ||
12207           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12208         mismatch = false;
12209   } else
12210     if (IsPointerAttr)
12211       mismatch = !isLayoutCompatible(Context,
12212                                      ArgumentType->getPointeeType(),
12213                                      RequiredType->getPointeeType());
12214     else
12215       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12216 
12217   if (mismatch)
12218     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12219         << ArgumentType << ArgumentKind
12220         << TypeInfo.LayoutCompatible << RequiredType
12221         << ArgumentExpr->getSourceRange()
12222         << TypeTagExpr->getSourceRange();
12223 }
12224 
12225 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12226                                          CharUnits Alignment) {
12227   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12228 }
12229 
12230 void Sema::DiagnoseMisalignedMembers() {
12231   for (MisalignedMember &m : MisalignedMembers) {
12232     const NamedDecl *ND = m.RD;
12233     if (ND->getName().empty()) {
12234       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12235         ND = TD;
12236     }
12237     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12238         << m.MD << ND << m.E->getSourceRange();
12239   }
12240   MisalignedMembers.clear();
12241 }
12242 
12243 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12244   E = E->IgnoreParens();
12245   if (!T->isPointerType() && !T->isIntegerType())
12246     return;
12247   if (isa<UnaryOperator>(E) &&
12248       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12249     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12250     if (isa<MemberExpr>(Op)) {
12251       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12252                           MisalignedMember(Op));
12253       if (MA != MisalignedMembers.end() &&
12254           (T->isIntegerType() ||
12255            (T->isPointerType() &&
12256             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12257         MisalignedMembers.erase(MA);
12258     }
12259   }
12260 }
12261 
12262 void Sema::RefersToMemberWithReducedAlignment(
12263     Expr *E,
12264     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12265         Action) {
12266   const auto *ME = dyn_cast<MemberExpr>(E);
12267   if (!ME)
12268     return;
12269 
12270   // No need to check expressions with an __unaligned-qualified type.
12271   if (E->getType().getQualifiers().hasUnaligned())
12272     return;
12273 
12274   // For a chain of MemberExpr like "a.b.c.d" this list
12275   // will keep FieldDecl's like [d, c, b].
12276   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12277   const MemberExpr *TopME = nullptr;
12278   bool AnyIsPacked = false;
12279   do {
12280     QualType BaseType = ME->getBase()->getType();
12281     if (ME->isArrow())
12282       BaseType = BaseType->getPointeeType();
12283     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12284     if (RD->isInvalidDecl())
12285       return;
12286 
12287     ValueDecl *MD = ME->getMemberDecl();
12288     auto *FD = dyn_cast<FieldDecl>(MD);
12289     // We do not care about non-data members.
12290     if (!FD || FD->isInvalidDecl())
12291       return;
12292 
12293     AnyIsPacked =
12294         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12295     ReverseMemberChain.push_back(FD);
12296 
12297     TopME = ME;
12298     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12299   } while (ME);
12300   assert(TopME && "We did not compute a topmost MemberExpr!");
12301 
12302   // Not the scope of this diagnostic.
12303   if (!AnyIsPacked)
12304     return;
12305 
12306   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12307   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12308   // TODO: The innermost base of the member expression may be too complicated.
12309   // For now, just disregard these cases. This is left for future
12310   // improvement.
12311   if (!DRE && !isa<CXXThisExpr>(TopBase))
12312       return;
12313 
12314   // Alignment expected by the whole expression.
12315   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12316 
12317   // No need to do anything else with this case.
12318   if (ExpectedAlignment.isOne())
12319     return;
12320 
12321   // Synthesize offset of the whole access.
12322   CharUnits Offset;
12323   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12324        I++) {
12325     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12326   }
12327 
12328   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12329   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12330       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12331 
12332   // The base expression of the innermost MemberExpr may give
12333   // stronger guarantees than the class containing the member.
12334   if (DRE && !TopME->isArrow()) {
12335     const ValueDecl *VD = DRE->getDecl();
12336     if (!VD->getType()->isReferenceType())
12337       CompleteObjectAlignment =
12338           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12339   }
12340 
12341   // Check if the synthesized offset fulfills the alignment.
12342   if (Offset % ExpectedAlignment != 0 ||
12343       // It may fulfill the offset it but the effective alignment may still be
12344       // lower than the expected expression alignment.
12345       CompleteObjectAlignment < ExpectedAlignment) {
12346     // If this happens, we want to determine a sensible culprit of this.
12347     // Intuitively, watching the chain of member expressions from right to
12348     // left, we start with the required alignment (as required by the field
12349     // type) but some packed attribute in that chain has reduced the alignment.
12350     // It may happen that another packed structure increases it again. But if
12351     // we are here such increase has not been enough. So pointing the first
12352     // FieldDecl that either is packed or else its RecordDecl is,
12353     // seems reasonable.
12354     FieldDecl *FD = nullptr;
12355     CharUnits Alignment;
12356     for (FieldDecl *FDI : ReverseMemberChain) {
12357       if (FDI->hasAttr<PackedAttr>() ||
12358           FDI->getParent()->hasAttr<PackedAttr>()) {
12359         FD = FDI;
12360         Alignment = std::min(
12361             Context.getTypeAlignInChars(FD->getType()),
12362             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12363         break;
12364       }
12365     }
12366     assert(FD && "We did not find a packed FieldDecl!");
12367     Action(E, FD->getParent(), FD, Alignment);
12368   }
12369 }
12370 
12371 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12372   using namespace std::placeholders;
12373   RefersToMemberWithReducedAlignment(
12374       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12375                      _2, _3, _4));
12376 }
12377 
12378