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().getUnqualifiedType().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   case Builtin::BIto_private:
788     Qual.setAddressSpace(LangAS::opencl_private);
789     break;
790   default:
791     llvm_unreachable("Invalid builtin function");
792   }
793   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
794       RT.getUnqualifiedType(), Qual)));
795 
796   return false;
797 }
798 
799 ExprResult
800 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
801                                CallExpr *TheCall) {
802   ExprResult TheCallResult(TheCall);
803 
804   // Find out if any arguments are required to be integer constant expressions.
805   unsigned ICEArguments = 0;
806   ASTContext::GetBuiltinTypeError Error;
807   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
808   if (Error != ASTContext::GE_None)
809     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
810 
811   // If any arguments are required to be ICE's, check and diagnose.
812   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
813     // Skip arguments not required to be ICE's.
814     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
815 
816     llvm::APSInt Result;
817     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
818       return true;
819     ICEArguments &= ~(1 << ArgNo);
820   }
821 
822   switch (BuiltinID) {
823   case Builtin::BI__builtin___CFStringMakeConstantString:
824     assert(TheCall->getNumArgs() == 1 &&
825            "Wrong # arguments to builtin CFStringMakeConstantString");
826     if (CheckObjCString(TheCall->getArg(0)))
827       return ExprError();
828     break;
829   case Builtin::BI__builtin_ms_va_start:
830   case Builtin::BI__builtin_stdarg_start:
831   case Builtin::BI__builtin_va_start:
832     if (SemaBuiltinVAStart(BuiltinID, TheCall))
833       return ExprError();
834     break;
835   case Builtin::BI__va_start: {
836     switch (Context.getTargetInfo().getTriple().getArch()) {
837     case llvm::Triple::arm:
838     case llvm::Triple::thumb:
839       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
840         return ExprError();
841       break;
842     default:
843       if (SemaBuiltinVAStart(BuiltinID, TheCall))
844         return ExprError();
845       break;
846     }
847     break;
848   }
849   case Builtin::BI__builtin_isgreater:
850   case Builtin::BI__builtin_isgreaterequal:
851   case Builtin::BI__builtin_isless:
852   case Builtin::BI__builtin_islessequal:
853   case Builtin::BI__builtin_islessgreater:
854   case Builtin::BI__builtin_isunordered:
855     if (SemaBuiltinUnorderedCompare(TheCall))
856       return ExprError();
857     break;
858   case Builtin::BI__builtin_fpclassify:
859     if (SemaBuiltinFPClassification(TheCall, 6))
860       return ExprError();
861     break;
862   case Builtin::BI__builtin_isfinite:
863   case Builtin::BI__builtin_isinf:
864   case Builtin::BI__builtin_isinf_sign:
865   case Builtin::BI__builtin_isnan:
866   case Builtin::BI__builtin_isnormal:
867     if (SemaBuiltinFPClassification(TheCall, 1))
868       return ExprError();
869     break;
870   case Builtin::BI__builtin_shufflevector:
871     return SemaBuiltinShuffleVector(TheCall);
872     // TheCall will be freed by the smart pointer here, but that's fine, since
873     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
874   case Builtin::BI__builtin_prefetch:
875     if (SemaBuiltinPrefetch(TheCall))
876       return ExprError();
877     break;
878   case Builtin::BI__builtin_alloca_with_align:
879     if (SemaBuiltinAllocaWithAlign(TheCall))
880       return ExprError();
881     break;
882   case Builtin::BI__assume:
883   case Builtin::BI__builtin_assume:
884     if (SemaBuiltinAssume(TheCall))
885       return ExprError();
886     break;
887   case Builtin::BI__builtin_assume_aligned:
888     if (SemaBuiltinAssumeAligned(TheCall))
889       return ExprError();
890     break;
891   case Builtin::BI__builtin_object_size:
892     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
893       return ExprError();
894     break;
895   case Builtin::BI__builtin_longjmp:
896     if (SemaBuiltinLongjmp(TheCall))
897       return ExprError();
898     break;
899   case Builtin::BI__builtin_setjmp:
900     if (SemaBuiltinSetjmp(TheCall))
901       return ExprError();
902     break;
903   case Builtin::BI_setjmp:
904   case Builtin::BI_setjmpex:
905     if (checkArgCount(*this, TheCall, 1))
906       return true;
907     break;
908 
909   case Builtin::BI__builtin_classify_type:
910     if (checkArgCount(*this, TheCall, 1)) return true;
911     TheCall->setType(Context.IntTy);
912     break;
913   case Builtin::BI__builtin_constant_p:
914     if (checkArgCount(*this, TheCall, 1)) return true;
915     TheCall->setType(Context.IntTy);
916     break;
917   case Builtin::BI__sync_fetch_and_add:
918   case Builtin::BI__sync_fetch_and_add_1:
919   case Builtin::BI__sync_fetch_and_add_2:
920   case Builtin::BI__sync_fetch_and_add_4:
921   case Builtin::BI__sync_fetch_and_add_8:
922   case Builtin::BI__sync_fetch_and_add_16:
923   case Builtin::BI__sync_fetch_and_sub:
924   case Builtin::BI__sync_fetch_and_sub_1:
925   case Builtin::BI__sync_fetch_and_sub_2:
926   case Builtin::BI__sync_fetch_and_sub_4:
927   case Builtin::BI__sync_fetch_and_sub_8:
928   case Builtin::BI__sync_fetch_and_sub_16:
929   case Builtin::BI__sync_fetch_and_or:
930   case Builtin::BI__sync_fetch_and_or_1:
931   case Builtin::BI__sync_fetch_and_or_2:
932   case Builtin::BI__sync_fetch_and_or_4:
933   case Builtin::BI__sync_fetch_and_or_8:
934   case Builtin::BI__sync_fetch_and_or_16:
935   case Builtin::BI__sync_fetch_and_and:
936   case Builtin::BI__sync_fetch_and_and_1:
937   case Builtin::BI__sync_fetch_and_and_2:
938   case Builtin::BI__sync_fetch_and_and_4:
939   case Builtin::BI__sync_fetch_and_and_8:
940   case Builtin::BI__sync_fetch_and_and_16:
941   case Builtin::BI__sync_fetch_and_xor:
942   case Builtin::BI__sync_fetch_and_xor_1:
943   case Builtin::BI__sync_fetch_and_xor_2:
944   case Builtin::BI__sync_fetch_and_xor_4:
945   case Builtin::BI__sync_fetch_and_xor_8:
946   case Builtin::BI__sync_fetch_and_xor_16:
947   case Builtin::BI__sync_fetch_and_nand:
948   case Builtin::BI__sync_fetch_and_nand_1:
949   case Builtin::BI__sync_fetch_and_nand_2:
950   case Builtin::BI__sync_fetch_and_nand_4:
951   case Builtin::BI__sync_fetch_and_nand_8:
952   case Builtin::BI__sync_fetch_and_nand_16:
953   case Builtin::BI__sync_add_and_fetch:
954   case Builtin::BI__sync_add_and_fetch_1:
955   case Builtin::BI__sync_add_and_fetch_2:
956   case Builtin::BI__sync_add_and_fetch_4:
957   case Builtin::BI__sync_add_and_fetch_8:
958   case Builtin::BI__sync_add_and_fetch_16:
959   case Builtin::BI__sync_sub_and_fetch:
960   case Builtin::BI__sync_sub_and_fetch_1:
961   case Builtin::BI__sync_sub_and_fetch_2:
962   case Builtin::BI__sync_sub_and_fetch_4:
963   case Builtin::BI__sync_sub_and_fetch_8:
964   case Builtin::BI__sync_sub_and_fetch_16:
965   case Builtin::BI__sync_and_and_fetch:
966   case Builtin::BI__sync_and_and_fetch_1:
967   case Builtin::BI__sync_and_and_fetch_2:
968   case Builtin::BI__sync_and_and_fetch_4:
969   case Builtin::BI__sync_and_and_fetch_8:
970   case Builtin::BI__sync_and_and_fetch_16:
971   case Builtin::BI__sync_or_and_fetch:
972   case Builtin::BI__sync_or_and_fetch_1:
973   case Builtin::BI__sync_or_and_fetch_2:
974   case Builtin::BI__sync_or_and_fetch_4:
975   case Builtin::BI__sync_or_and_fetch_8:
976   case Builtin::BI__sync_or_and_fetch_16:
977   case Builtin::BI__sync_xor_and_fetch:
978   case Builtin::BI__sync_xor_and_fetch_1:
979   case Builtin::BI__sync_xor_and_fetch_2:
980   case Builtin::BI__sync_xor_and_fetch_4:
981   case Builtin::BI__sync_xor_and_fetch_8:
982   case Builtin::BI__sync_xor_and_fetch_16:
983   case Builtin::BI__sync_nand_and_fetch:
984   case Builtin::BI__sync_nand_and_fetch_1:
985   case Builtin::BI__sync_nand_and_fetch_2:
986   case Builtin::BI__sync_nand_and_fetch_4:
987   case Builtin::BI__sync_nand_and_fetch_8:
988   case Builtin::BI__sync_nand_and_fetch_16:
989   case Builtin::BI__sync_val_compare_and_swap:
990   case Builtin::BI__sync_val_compare_and_swap_1:
991   case Builtin::BI__sync_val_compare_and_swap_2:
992   case Builtin::BI__sync_val_compare_and_swap_4:
993   case Builtin::BI__sync_val_compare_and_swap_8:
994   case Builtin::BI__sync_val_compare_and_swap_16:
995   case Builtin::BI__sync_bool_compare_and_swap:
996   case Builtin::BI__sync_bool_compare_and_swap_1:
997   case Builtin::BI__sync_bool_compare_and_swap_2:
998   case Builtin::BI__sync_bool_compare_and_swap_4:
999   case Builtin::BI__sync_bool_compare_and_swap_8:
1000   case Builtin::BI__sync_bool_compare_and_swap_16:
1001   case Builtin::BI__sync_lock_test_and_set:
1002   case Builtin::BI__sync_lock_test_and_set_1:
1003   case Builtin::BI__sync_lock_test_and_set_2:
1004   case Builtin::BI__sync_lock_test_and_set_4:
1005   case Builtin::BI__sync_lock_test_and_set_8:
1006   case Builtin::BI__sync_lock_test_and_set_16:
1007   case Builtin::BI__sync_lock_release:
1008   case Builtin::BI__sync_lock_release_1:
1009   case Builtin::BI__sync_lock_release_2:
1010   case Builtin::BI__sync_lock_release_4:
1011   case Builtin::BI__sync_lock_release_8:
1012   case Builtin::BI__sync_lock_release_16:
1013   case Builtin::BI__sync_swap:
1014   case Builtin::BI__sync_swap_1:
1015   case Builtin::BI__sync_swap_2:
1016   case Builtin::BI__sync_swap_4:
1017   case Builtin::BI__sync_swap_8:
1018   case Builtin::BI__sync_swap_16:
1019     return SemaBuiltinAtomicOverloaded(TheCallResult);
1020   case Builtin::BI__builtin_nontemporal_load:
1021   case Builtin::BI__builtin_nontemporal_store:
1022     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1023 #define BUILTIN(ID, TYPE, ATTRS)
1024 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1025   case Builtin::BI##ID: \
1026     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1027 #include "clang/Basic/Builtins.def"
1028   case Builtin::BI__annotation:
1029     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1030       return ExprError();
1031     break;
1032   case Builtin::BI__builtin_annotation:
1033     if (SemaBuiltinAnnotation(*this, TheCall))
1034       return ExprError();
1035     break;
1036   case Builtin::BI__builtin_addressof:
1037     if (SemaBuiltinAddressof(*this, TheCall))
1038       return ExprError();
1039     break;
1040   case Builtin::BI__builtin_add_overflow:
1041   case Builtin::BI__builtin_sub_overflow:
1042   case Builtin::BI__builtin_mul_overflow:
1043     if (SemaBuiltinOverflow(*this, TheCall))
1044       return ExprError();
1045     break;
1046   case Builtin::BI__builtin_operator_new:
1047   case Builtin::BI__builtin_operator_delete:
1048     if (!getLangOpts().CPlusPlus) {
1049       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1050         << (BuiltinID == Builtin::BI__builtin_operator_new
1051                 ? "__builtin_operator_new"
1052                 : "__builtin_operator_delete")
1053         << "C++";
1054       return ExprError();
1055     }
1056     // CodeGen assumes it can find the global new and delete to call,
1057     // so ensure that they are declared.
1058     DeclareGlobalNewDelete();
1059     break;
1060 
1061   // check secure string manipulation functions where overflows
1062   // are detectable at compile time
1063   case Builtin::BI__builtin___memcpy_chk:
1064   case Builtin::BI__builtin___memmove_chk:
1065   case Builtin::BI__builtin___memset_chk:
1066   case Builtin::BI__builtin___strlcat_chk:
1067   case Builtin::BI__builtin___strlcpy_chk:
1068   case Builtin::BI__builtin___strncat_chk:
1069   case Builtin::BI__builtin___strncpy_chk:
1070   case Builtin::BI__builtin___stpncpy_chk:
1071     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1072     break;
1073   case Builtin::BI__builtin___memccpy_chk:
1074     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1075     break;
1076   case Builtin::BI__builtin___snprintf_chk:
1077   case Builtin::BI__builtin___vsnprintf_chk:
1078     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1079     break;
1080   case Builtin::BI__builtin_call_with_static_chain:
1081     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1082       return ExprError();
1083     break;
1084   case Builtin::BI__exception_code:
1085   case Builtin::BI_exception_code:
1086     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1087                                  diag::err_seh___except_block))
1088       return ExprError();
1089     break;
1090   case Builtin::BI__exception_info:
1091   case Builtin::BI_exception_info:
1092     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1093                                  diag::err_seh___except_filter))
1094       return ExprError();
1095     break;
1096   case Builtin::BI__GetExceptionInfo:
1097     if (checkArgCount(*this, TheCall, 1))
1098       return ExprError();
1099 
1100     if (CheckCXXThrowOperand(
1101             TheCall->getLocStart(),
1102             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1103             TheCall))
1104       return ExprError();
1105 
1106     TheCall->setType(Context.VoidPtrTy);
1107     break;
1108   // OpenCL v2.0, s6.13.16 - Pipe functions
1109   case Builtin::BIread_pipe:
1110   case Builtin::BIwrite_pipe:
1111     // Since those two functions are declared with var args, we need a semantic
1112     // check for the argument.
1113     if (SemaBuiltinRWPipe(*this, TheCall))
1114       return ExprError();
1115     TheCall->setType(Context.IntTy);
1116     break;
1117   case Builtin::BIreserve_read_pipe:
1118   case Builtin::BIreserve_write_pipe:
1119   case Builtin::BIwork_group_reserve_read_pipe:
1120   case Builtin::BIwork_group_reserve_write_pipe:
1121     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1122       return ExprError();
1123     break;
1124   case Builtin::BIsub_group_reserve_read_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1127         SemaBuiltinReserveRWPipe(*this, TheCall))
1128       return ExprError();
1129     break;
1130   case Builtin::BIcommit_read_pipe:
1131   case Builtin::BIcommit_write_pipe:
1132   case Builtin::BIwork_group_commit_read_pipe:
1133   case Builtin::BIwork_group_commit_write_pipe:
1134     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1135       return ExprError();
1136     break;
1137   case Builtin::BIsub_group_commit_read_pipe:
1138   case Builtin::BIsub_group_commit_write_pipe:
1139     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1140         SemaBuiltinCommitRWPipe(*this, TheCall))
1141       return ExprError();
1142     break;
1143   case Builtin::BIget_pipe_num_packets:
1144   case Builtin::BIget_pipe_max_packets:
1145     if (SemaBuiltinPipePackets(*this, TheCall))
1146       return ExprError();
1147     TheCall->setType(Context.UnsignedIntTy);
1148     break;
1149   case Builtin::BIto_global:
1150   case Builtin::BIto_local:
1151   case Builtin::BIto_private:
1152     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1153       return ExprError();
1154     break;
1155   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1156   case Builtin::BIenqueue_kernel:
1157     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1158       return ExprError();
1159     break;
1160   case Builtin::BIget_kernel_work_group_size:
1161   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1162     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1163       return ExprError();
1164     break;
1165     break;
1166   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1167   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1168     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1169       return ExprError();
1170     break;
1171   case Builtin::BI__builtin_os_log_format:
1172   case Builtin::BI__builtin_os_log_format_buffer_size:
1173     if (SemaBuiltinOSLogFormat(TheCall)) {
1174       return ExprError();
1175     }
1176     break;
1177   }
1178 
1179   // Since the target specific builtins for each arch overlap, only check those
1180   // of the arch we are compiling for.
1181   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1182     switch (Context.getTargetInfo().getTriple().getArch()) {
1183       case llvm::Triple::arm:
1184       case llvm::Triple::armeb:
1185       case llvm::Triple::thumb:
1186       case llvm::Triple::thumbeb:
1187         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1188           return ExprError();
1189         break;
1190       case llvm::Triple::aarch64:
1191       case llvm::Triple::aarch64_be:
1192         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1193           return ExprError();
1194         break;
1195       case llvm::Triple::mips:
1196       case llvm::Triple::mipsel:
1197       case llvm::Triple::mips64:
1198       case llvm::Triple::mips64el:
1199         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1200           return ExprError();
1201         break;
1202       case llvm::Triple::systemz:
1203         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1204           return ExprError();
1205         break;
1206       case llvm::Triple::x86:
1207       case llvm::Triple::x86_64:
1208         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1209           return ExprError();
1210         break;
1211       case llvm::Triple::ppc:
1212       case llvm::Triple::ppc64:
1213       case llvm::Triple::ppc64le:
1214         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1215           return ExprError();
1216         break;
1217       default:
1218         break;
1219     }
1220   }
1221 
1222   return TheCallResult;
1223 }
1224 
1225 // Get the valid immediate range for the specified NEON type code.
1226 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1227   NeonTypeFlags Type(t);
1228   int IsQuad = ForceQuad ? true : Type.isQuad();
1229   switch (Type.getEltType()) {
1230   case NeonTypeFlags::Int8:
1231   case NeonTypeFlags::Poly8:
1232     return shift ? 7 : (8 << IsQuad) - 1;
1233   case NeonTypeFlags::Int16:
1234   case NeonTypeFlags::Poly16:
1235     return shift ? 15 : (4 << IsQuad) - 1;
1236   case NeonTypeFlags::Int32:
1237     return shift ? 31 : (2 << IsQuad) - 1;
1238   case NeonTypeFlags::Int64:
1239   case NeonTypeFlags::Poly64:
1240     return shift ? 63 : (1 << IsQuad) - 1;
1241   case NeonTypeFlags::Poly128:
1242     return shift ? 127 : (1 << IsQuad) - 1;
1243   case NeonTypeFlags::Float16:
1244     assert(!shift && "cannot shift float types!");
1245     return (4 << IsQuad) - 1;
1246   case NeonTypeFlags::Float32:
1247     assert(!shift && "cannot shift float types!");
1248     return (2 << IsQuad) - 1;
1249   case NeonTypeFlags::Float64:
1250     assert(!shift && "cannot shift float types!");
1251     return (1 << IsQuad) - 1;
1252   }
1253   llvm_unreachable("Invalid NeonTypeFlag!");
1254 }
1255 
1256 /// getNeonEltType - Return the QualType corresponding to the elements of
1257 /// the vector type specified by the NeonTypeFlags.  This is used to check
1258 /// the pointer arguments for Neon load/store intrinsics.
1259 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1260                                bool IsPolyUnsigned, bool IsInt64Long) {
1261   switch (Flags.getEltType()) {
1262   case NeonTypeFlags::Int8:
1263     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1264   case NeonTypeFlags::Int16:
1265     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1266   case NeonTypeFlags::Int32:
1267     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1268   case NeonTypeFlags::Int64:
1269     if (IsInt64Long)
1270       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1271     else
1272       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1273                                 : Context.LongLongTy;
1274   case NeonTypeFlags::Poly8:
1275     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1276   case NeonTypeFlags::Poly16:
1277     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1278   case NeonTypeFlags::Poly64:
1279     if (IsInt64Long)
1280       return Context.UnsignedLongTy;
1281     else
1282       return Context.UnsignedLongLongTy;
1283   case NeonTypeFlags::Poly128:
1284     break;
1285   case NeonTypeFlags::Float16:
1286     return Context.HalfTy;
1287   case NeonTypeFlags::Float32:
1288     return Context.FloatTy;
1289   case NeonTypeFlags::Float64:
1290     return Context.DoubleTy;
1291   }
1292   llvm_unreachable("Invalid NeonTypeFlag!");
1293 }
1294 
1295 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1296   llvm::APSInt Result;
1297   uint64_t mask = 0;
1298   unsigned TV = 0;
1299   int PtrArgNum = -1;
1300   bool HasConstPtr = false;
1301   switch (BuiltinID) {
1302 #define GET_NEON_OVERLOAD_CHECK
1303 #include "clang/Basic/arm_neon.inc"
1304 #undef GET_NEON_OVERLOAD_CHECK
1305   }
1306 
1307   // For NEON intrinsics which are overloaded on vector element type, validate
1308   // the immediate which specifies which variant to emit.
1309   unsigned ImmArg = TheCall->getNumArgs()-1;
1310   if (mask) {
1311     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1312       return true;
1313 
1314     TV = Result.getLimitedValue(64);
1315     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1316       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1317         << TheCall->getArg(ImmArg)->getSourceRange();
1318   }
1319 
1320   if (PtrArgNum >= 0) {
1321     // Check that pointer arguments have the specified type.
1322     Expr *Arg = TheCall->getArg(PtrArgNum);
1323     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1324       Arg = ICE->getSubExpr();
1325     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1326     QualType RHSTy = RHS.get()->getType();
1327 
1328     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1329     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1330                           Arch == llvm::Triple::aarch64_be;
1331     bool IsInt64Long =
1332         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1333     QualType EltTy =
1334         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1335     if (HasConstPtr)
1336       EltTy = EltTy.withConst();
1337     QualType LHSTy = Context.getPointerType(EltTy);
1338     AssignConvertType ConvTy;
1339     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1340     if (RHS.isInvalid())
1341       return true;
1342     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1343                                  RHS.get(), AA_Assigning))
1344       return true;
1345   }
1346 
1347   // For NEON intrinsics which take an immediate value as part of the
1348   // instruction, range check them here.
1349   unsigned i = 0, l = 0, u = 0;
1350   switch (BuiltinID) {
1351   default:
1352     return false;
1353 #define GET_NEON_IMMEDIATE_CHECK
1354 #include "clang/Basic/arm_neon.inc"
1355 #undef GET_NEON_IMMEDIATE_CHECK
1356   }
1357 
1358   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1359 }
1360 
1361 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1362                                         unsigned MaxWidth) {
1363   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1364           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1365           BuiltinID == ARM::BI__builtin_arm_strex ||
1366           BuiltinID == ARM::BI__builtin_arm_stlex ||
1367           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1368           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1369           BuiltinID == AArch64::BI__builtin_arm_strex ||
1370           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1371          "unexpected ARM builtin");
1372   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1373                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1374                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1375                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1376 
1377   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1378 
1379   // Ensure that we have the proper number of arguments.
1380   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1381     return true;
1382 
1383   // Inspect the pointer argument of the atomic builtin.  This should always be
1384   // a pointer type, whose element is an integral scalar or pointer type.
1385   // Because it is a pointer type, we don't have to worry about any implicit
1386   // casts here.
1387   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1388   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1389   if (PointerArgRes.isInvalid())
1390     return true;
1391   PointerArg = PointerArgRes.get();
1392 
1393   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1394   if (!pointerType) {
1395     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1396       << PointerArg->getType() << PointerArg->getSourceRange();
1397     return true;
1398   }
1399 
1400   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1401   // task is to insert the appropriate casts into the AST. First work out just
1402   // what the appropriate type is.
1403   QualType ValType = pointerType->getPointeeType();
1404   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1405   if (IsLdrex)
1406     AddrType.addConst();
1407 
1408   // Issue a warning if the cast is dodgy.
1409   CastKind CastNeeded = CK_NoOp;
1410   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1411     CastNeeded = CK_BitCast;
1412     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1413       << PointerArg->getType()
1414       << Context.getPointerType(AddrType)
1415       << AA_Passing << PointerArg->getSourceRange();
1416   }
1417 
1418   // Finally, do the cast and replace the argument with the corrected version.
1419   AddrType = Context.getPointerType(AddrType);
1420   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1421   if (PointerArgRes.isInvalid())
1422     return true;
1423   PointerArg = PointerArgRes.get();
1424 
1425   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1426 
1427   // In general, we allow ints, floats and pointers to be loaded and stored.
1428   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1429       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1430     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1431       << PointerArg->getType() << PointerArg->getSourceRange();
1432     return true;
1433   }
1434 
1435   // But ARM doesn't have instructions to deal with 128-bit versions.
1436   if (Context.getTypeSize(ValType) > MaxWidth) {
1437     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1438     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1439       << PointerArg->getType() << PointerArg->getSourceRange();
1440     return true;
1441   }
1442 
1443   switch (ValType.getObjCLifetime()) {
1444   case Qualifiers::OCL_None:
1445   case Qualifiers::OCL_ExplicitNone:
1446     // okay
1447     break;
1448 
1449   case Qualifiers::OCL_Weak:
1450   case Qualifiers::OCL_Strong:
1451   case Qualifiers::OCL_Autoreleasing:
1452     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1453       << ValType << PointerArg->getSourceRange();
1454     return true;
1455   }
1456 
1457   if (IsLdrex) {
1458     TheCall->setType(ValType);
1459     return false;
1460   }
1461 
1462   // Initialize the argument to be stored.
1463   ExprResult ValArg = TheCall->getArg(0);
1464   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1465       Context, ValType, /*consume*/ false);
1466   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1467   if (ValArg.isInvalid())
1468     return true;
1469   TheCall->setArg(0, ValArg.get());
1470 
1471   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1472   // but the custom checker bypasses all default analysis.
1473   TheCall->setType(Context.IntTy);
1474   return false;
1475 }
1476 
1477 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1478   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1479       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1480       BuiltinID == ARM::BI__builtin_arm_strex ||
1481       BuiltinID == ARM::BI__builtin_arm_stlex) {
1482     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1483   }
1484 
1485   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1486     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1487       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1488   }
1489 
1490   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1491       BuiltinID == ARM::BI__builtin_arm_wsr64)
1492     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1493 
1494   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1495       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1496       BuiltinID == ARM::BI__builtin_arm_wsr ||
1497       BuiltinID == ARM::BI__builtin_arm_wsrp)
1498     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1499 
1500   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1501     return true;
1502 
1503   // For intrinsics which take an immediate value as part of the instruction,
1504   // range check them here.
1505   unsigned i = 0, l = 0, u = 0;
1506   switch (BuiltinID) {
1507   default: return false;
1508   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1509   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1510   case ARM::BI__builtin_arm_vcvtr_f:
1511   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1512   case ARM::BI__builtin_arm_dmb:
1513   case ARM::BI__builtin_arm_dsb:
1514   case ARM::BI__builtin_arm_isb:
1515   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1516   }
1517 
1518   // FIXME: VFP Intrinsics should error if VFP not present.
1519   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1520 }
1521 
1522 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1523                                          CallExpr *TheCall) {
1524   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1525       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1526       BuiltinID == AArch64::BI__builtin_arm_strex ||
1527       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1528     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1529   }
1530 
1531   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1532     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1533       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1534       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1535       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1536   }
1537 
1538   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1539       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1540     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1541 
1542   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1543       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1544       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1545       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1546     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1547 
1548   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1549     return true;
1550 
1551   // For intrinsics which take an immediate value as part of the instruction,
1552   // range check them here.
1553   unsigned i = 0, l = 0, u = 0;
1554   switch (BuiltinID) {
1555   default: return false;
1556   case AArch64::BI__builtin_arm_dmb:
1557   case AArch64::BI__builtin_arm_dsb:
1558   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1559   }
1560 
1561   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1562 }
1563 
1564 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1565 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1566 // ordering for DSP is unspecified. MSA is ordered by the data format used
1567 // by the underlying instruction i.e., df/m, df/n and then by size.
1568 //
1569 // FIXME: The size tests here should instead be tablegen'd along with the
1570 //        definitions from include/clang/Basic/BuiltinsMips.def.
1571 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1572 //        be too.
1573 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1574   unsigned i = 0, l = 0, u = 0, m = 0;
1575   switch (BuiltinID) {
1576   default: return false;
1577   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1578   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1579   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1580   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1581   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1582   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1583   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1584   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1585   // df/m field.
1586   // These intrinsics take an unsigned 3 bit immediate.
1587   case Mips::BI__builtin_msa_bclri_b:
1588   case Mips::BI__builtin_msa_bnegi_b:
1589   case Mips::BI__builtin_msa_bseti_b:
1590   case Mips::BI__builtin_msa_sat_s_b:
1591   case Mips::BI__builtin_msa_sat_u_b:
1592   case Mips::BI__builtin_msa_slli_b:
1593   case Mips::BI__builtin_msa_srai_b:
1594   case Mips::BI__builtin_msa_srari_b:
1595   case Mips::BI__builtin_msa_srli_b:
1596   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1597   case Mips::BI__builtin_msa_binsli_b:
1598   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1599   // These intrinsics take an unsigned 4 bit immediate.
1600   case Mips::BI__builtin_msa_bclri_h:
1601   case Mips::BI__builtin_msa_bnegi_h:
1602   case Mips::BI__builtin_msa_bseti_h:
1603   case Mips::BI__builtin_msa_sat_s_h:
1604   case Mips::BI__builtin_msa_sat_u_h:
1605   case Mips::BI__builtin_msa_slli_h:
1606   case Mips::BI__builtin_msa_srai_h:
1607   case Mips::BI__builtin_msa_srari_h:
1608   case Mips::BI__builtin_msa_srli_h:
1609   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1610   case Mips::BI__builtin_msa_binsli_h:
1611   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1612   // These intrinsics take an unsigned 5 bit immedate.
1613   // The first block of intrinsics actually have an unsigned 5 bit field,
1614   // not a df/n field.
1615   case Mips::BI__builtin_msa_clei_u_b:
1616   case Mips::BI__builtin_msa_clei_u_h:
1617   case Mips::BI__builtin_msa_clei_u_w:
1618   case Mips::BI__builtin_msa_clei_u_d:
1619   case Mips::BI__builtin_msa_clti_u_b:
1620   case Mips::BI__builtin_msa_clti_u_h:
1621   case Mips::BI__builtin_msa_clti_u_w:
1622   case Mips::BI__builtin_msa_clti_u_d:
1623   case Mips::BI__builtin_msa_maxi_u_b:
1624   case Mips::BI__builtin_msa_maxi_u_h:
1625   case Mips::BI__builtin_msa_maxi_u_w:
1626   case Mips::BI__builtin_msa_maxi_u_d:
1627   case Mips::BI__builtin_msa_mini_u_b:
1628   case Mips::BI__builtin_msa_mini_u_h:
1629   case Mips::BI__builtin_msa_mini_u_w:
1630   case Mips::BI__builtin_msa_mini_u_d:
1631   case Mips::BI__builtin_msa_addvi_b:
1632   case Mips::BI__builtin_msa_addvi_h:
1633   case Mips::BI__builtin_msa_addvi_w:
1634   case Mips::BI__builtin_msa_addvi_d:
1635   case Mips::BI__builtin_msa_bclri_w:
1636   case Mips::BI__builtin_msa_bnegi_w:
1637   case Mips::BI__builtin_msa_bseti_w:
1638   case Mips::BI__builtin_msa_sat_s_w:
1639   case Mips::BI__builtin_msa_sat_u_w:
1640   case Mips::BI__builtin_msa_slli_w:
1641   case Mips::BI__builtin_msa_srai_w:
1642   case Mips::BI__builtin_msa_srari_w:
1643   case Mips::BI__builtin_msa_srli_w:
1644   case Mips::BI__builtin_msa_srlri_w:
1645   case Mips::BI__builtin_msa_subvi_b:
1646   case Mips::BI__builtin_msa_subvi_h:
1647   case Mips::BI__builtin_msa_subvi_w:
1648   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1649   case Mips::BI__builtin_msa_binsli_w:
1650   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1651   // These intrinsics take an unsigned 6 bit immediate.
1652   case Mips::BI__builtin_msa_bclri_d:
1653   case Mips::BI__builtin_msa_bnegi_d:
1654   case Mips::BI__builtin_msa_bseti_d:
1655   case Mips::BI__builtin_msa_sat_s_d:
1656   case Mips::BI__builtin_msa_sat_u_d:
1657   case Mips::BI__builtin_msa_slli_d:
1658   case Mips::BI__builtin_msa_srai_d:
1659   case Mips::BI__builtin_msa_srari_d:
1660   case Mips::BI__builtin_msa_srli_d:
1661   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1662   case Mips::BI__builtin_msa_binsli_d:
1663   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1664   // These intrinsics take a signed 5 bit immediate.
1665   case Mips::BI__builtin_msa_ceqi_b:
1666   case Mips::BI__builtin_msa_ceqi_h:
1667   case Mips::BI__builtin_msa_ceqi_w:
1668   case Mips::BI__builtin_msa_ceqi_d:
1669   case Mips::BI__builtin_msa_clti_s_b:
1670   case Mips::BI__builtin_msa_clti_s_h:
1671   case Mips::BI__builtin_msa_clti_s_w:
1672   case Mips::BI__builtin_msa_clti_s_d:
1673   case Mips::BI__builtin_msa_clei_s_b:
1674   case Mips::BI__builtin_msa_clei_s_h:
1675   case Mips::BI__builtin_msa_clei_s_w:
1676   case Mips::BI__builtin_msa_clei_s_d:
1677   case Mips::BI__builtin_msa_maxi_s_b:
1678   case Mips::BI__builtin_msa_maxi_s_h:
1679   case Mips::BI__builtin_msa_maxi_s_w:
1680   case Mips::BI__builtin_msa_maxi_s_d:
1681   case Mips::BI__builtin_msa_mini_s_b:
1682   case Mips::BI__builtin_msa_mini_s_h:
1683   case Mips::BI__builtin_msa_mini_s_w:
1684   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1685   // These intrinsics take an unsigned 8 bit immediate.
1686   case Mips::BI__builtin_msa_andi_b:
1687   case Mips::BI__builtin_msa_nori_b:
1688   case Mips::BI__builtin_msa_ori_b:
1689   case Mips::BI__builtin_msa_shf_b:
1690   case Mips::BI__builtin_msa_shf_h:
1691   case Mips::BI__builtin_msa_shf_w:
1692   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1693   case Mips::BI__builtin_msa_bseli_b:
1694   case Mips::BI__builtin_msa_bmnzi_b:
1695   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1696   // df/n format
1697   // These intrinsics take an unsigned 4 bit immediate.
1698   case Mips::BI__builtin_msa_copy_s_b:
1699   case Mips::BI__builtin_msa_copy_u_b:
1700   case Mips::BI__builtin_msa_insve_b:
1701   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1702   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1703   // These intrinsics take an unsigned 3 bit immediate.
1704   case Mips::BI__builtin_msa_copy_s_h:
1705   case Mips::BI__builtin_msa_copy_u_h:
1706   case Mips::BI__builtin_msa_insve_h:
1707   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1708   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1709   // These intrinsics take an unsigned 2 bit immediate.
1710   case Mips::BI__builtin_msa_copy_s_w:
1711   case Mips::BI__builtin_msa_copy_u_w:
1712   case Mips::BI__builtin_msa_insve_w:
1713   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1714   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1715   // These intrinsics take an unsigned 1 bit immediate.
1716   case Mips::BI__builtin_msa_copy_s_d:
1717   case Mips::BI__builtin_msa_copy_u_d:
1718   case Mips::BI__builtin_msa_insve_d:
1719   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1720   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1721   // Memory offsets and immediate loads.
1722   // These intrinsics take a signed 10 bit immediate.
1723   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1724   case Mips::BI__builtin_msa_ldi_h:
1725   case Mips::BI__builtin_msa_ldi_w:
1726   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1727   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1728   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1729   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1730   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1731   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1732   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1733   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1734   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1735   }
1736 
1737   if (!m)
1738     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1739 
1740   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1741          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1742 }
1743 
1744 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1745   unsigned i = 0, l = 0, u = 0;
1746   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1747                       BuiltinID == PPC::BI__builtin_divdeu ||
1748                       BuiltinID == PPC::BI__builtin_bpermd;
1749   bool IsTarget64Bit = Context.getTargetInfo()
1750                               .getTypeWidth(Context
1751                                             .getTargetInfo()
1752                                             .getIntPtrType()) == 64;
1753   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1754                        BuiltinID == PPC::BI__builtin_divweu ||
1755                        BuiltinID == PPC::BI__builtin_divde ||
1756                        BuiltinID == PPC::BI__builtin_divdeu;
1757 
1758   if (Is64BitBltin && !IsTarget64Bit)
1759       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1760              << TheCall->getSourceRange();
1761 
1762   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1763       (BuiltinID == PPC::BI__builtin_bpermd &&
1764        !Context.getTargetInfo().hasFeature("bpermd")))
1765     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1766            << TheCall->getSourceRange();
1767 
1768   switch (BuiltinID) {
1769   default: return false;
1770   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1771   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1772     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1773            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1774   case PPC::BI__builtin_tbegin:
1775   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1776   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1777   case PPC::BI__builtin_tabortwc:
1778   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1779   case PPC::BI__builtin_tabortwci:
1780   case PPC::BI__builtin_tabortdci:
1781     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1782            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1783   case PPC::BI__builtin_vsx_xxpermdi:
1784   case PPC::BI__builtin_vsx_xxsldwi:
1785     return SemaBuiltinVSX(TheCall);
1786   }
1787   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1788 }
1789 
1790 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1791                                            CallExpr *TheCall) {
1792   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1793     Expr *Arg = TheCall->getArg(0);
1794     llvm::APSInt AbortCode(32);
1795     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1796         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1797       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1798              << Arg->getSourceRange();
1799   }
1800 
1801   // For intrinsics which take an immediate value as part of the instruction,
1802   // range check them here.
1803   unsigned i = 0, l = 0, u = 0;
1804   switch (BuiltinID) {
1805   default: return false;
1806   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1807   case SystemZ::BI__builtin_s390_verimb:
1808   case SystemZ::BI__builtin_s390_verimh:
1809   case SystemZ::BI__builtin_s390_verimf:
1810   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1811   case SystemZ::BI__builtin_s390_vfaeb:
1812   case SystemZ::BI__builtin_s390_vfaeh:
1813   case SystemZ::BI__builtin_s390_vfaef:
1814   case SystemZ::BI__builtin_s390_vfaebs:
1815   case SystemZ::BI__builtin_s390_vfaehs:
1816   case SystemZ::BI__builtin_s390_vfaefs:
1817   case SystemZ::BI__builtin_s390_vfaezb:
1818   case SystemZ::BI__builtin_s390_vfaezh:
1819   case SystemZ::BI__builtin_s390_vfaezf:
1820   case SystemZ::BI__builtin_s390_vfaezbs:
1821   case SystemZ::BI__builtin_s390_vfaezhs:
1822   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1823   case SystemZ::BI__builtin_s390_vfisb:
1824   case SystemZ::BI__builtin_s390_vfidb:
1825     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1826            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1827   case SystemZ::BI__builtin_s390_vftcisb:
1828   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1829   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1830   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1831   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1832   case SystemZ::BI__builtin_s390_vstrcb:
1833   case SystemZ::BI__builtin_s390_vstrch:
1834   case SystemZ::BI__builtin_s390_vstrcf:
1835   case SystemZ::BI__builtin_s390_vstrczb:
1836   case SystemZ::BI__builtin_s390_vstrczh:
1837   case SystemZ::BI__builtin_s390_vstrczf:
1838   case SystemZ::BI__builtin_s390_vstrcbs:
1839   case SystemZ::BI__builtin_s390_vstrchs:
1840   case SystemZ::BI__builtin_s390_vstrcfs:
1841   case SystemZ::BI__builtin_s390_vstrczbs:
1842   case SystemZ::BI__builtin_s390_vstrczhs:
1843   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1844   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1845   case SystemZ::BI__builtin_s390_vfminsb:
1846   case SystemZ::BI__builtin_s390_vfmaxsb:
1847   case SystemZ::BI__builtin_s390_vfmindb:
1848   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1849   }
1850   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1851 }
1852 
1853 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1854 /// This checks that the target supports __builtin_cpu_supports and
1855 /// that the string argument is constant and valid.
1856 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1857   Expr *Arg = TheCall->getArg(0);
1858 
1859   // Check if the argument is a string literal.
1860   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1861     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1862            << Arg->getSourceRange();
1863 
1864   // Check the contents of the string.
1865   StringRef Feature =
1866       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1867   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1868     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1869            << Arg->getSourceRange();
1870   return false;
1871 }
1872 
1873 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1874 /// This checks that the target supports __builtin_cpu_is and
1875 /// that the string argument is constant and valid.
1876 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1877   Expr *Arg = TheCall->getArg(0);
1878 
1879   // Check if the argument is a string literal.
1880   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1881     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1882            << Arg->getSourceRange();
1883 
1884   // Check the contents of the string.
1885   StringRef Feature =
1886       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1887   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1888     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1889            << Arg->getSourceRange();
1890   return false;
1891 }
1892 
1893 // Check if the rounding mode is legal.
1894 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1895   // Indicates if this instruction has rounding control or just SAE.
1896   bool HasRC = false;
1897 
1898   unsigned ArgNum = 0;
1899   switch (BuiltinID) {
1900   default:
1901     return false;
1902   case X86::BI__builtin_ia32_vcvttsd2si32:
1903   case X86::BI__builtin_ia32_vcvttsd2si64:
1904   case X86::BI__builtin_ia32_vcvttsd2usi32:
1905   case X86::BI__builtin_ia32_vcvttsd2usi64:
1906   case X86::BI__builtin_ia32_vcvttss2si32:
1907   case X86::BI__builtin_ia32_vcvttss2si64:
1908   case X86::BI__builtin_ia32_vcvttss2usi32:
1909   case X86::BI__builtin_ia32_vcvttss2usi64:
1910     ArgNum = 1;
1911     break;
1912   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1913   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1914   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1915   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1916   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1917   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1918   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1919   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1920   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1921   case X86::BI__builtin_ia32_exp2pd_mask:
1922   case X86::BI__builtin_ia32_exp2ps_mask:
1923   case X86::BI__builtin_ia32_getexppd512_mask:
1924   case X86::BI__builtin_ia32_getexpps512_mask:
1925   case X86::BI__builtin_ia32_rcp28pd_mask:
1926   case X86::BI__builtin_ia32_rcp28ps_mask:
1927   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1928   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1929   case X86::BI__builtin_ia32_vcomisd:
1930   case X86::BI__builtin_ia32_vcomiss:
1931   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1932     ArgNum = 3;
1933     break;
1934   case X86::BI__builtin_ia32_cmppd512_mask:
1935   case X86::BI__builtin_ia32_cmpps512_mask:
1936   case X86::BI__builtin_ia32_cmpsd_mask:
1937   case X86::BI__builtin_ia32_cmpss_mask:
1938   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1939   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1940   case X86::BI__builtin_ia32_getexpss128_round_mask:
1941   case X86::BI__builtin_ia32_maxpd512_mask:
1942   case X86::BI__builtin_ia32_maxps512_mask:
1943   case X86::BI__builtin_ia32_maxsd_round_mask:
1944   case X86::BI__builtin_ia32_maxss_round_mask:
1945   case X86::BI__builtin_ia32_minpd512_mask:
1946   case X86::BI__builtin_ia32_minps512_mask:
1947   case X86::BI__builtin_ia32_minsd_round_mask:
1948   case X86::BI__builtin_ia32_minss_round_mask:
1949   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1950   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1951   case X86::BI__builtin_ia32_reducepd512_mask:
1952   case X86::BI__builtin_ia32_reduceps512_mask:
1953   case X86::BI__builtin_ia32_rndscalepd_mask:
1954   case X86::BI__builtin_ia32_rndscaleps_mask:
1955   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1956   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1957     ArgNum = 4;
1958     break;
1959   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1960   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1961   case X86::BI__builtin_ia32_fixupimmps512_mask:
1962   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1963   case X86::BI__builtin_ia32_fixupimmsd_mask:
1964   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1965   case X86::BI__builtin_ia32_fixupimmss_mask:
1966   case X86::BI__builtin_ia32_fixupimmss_maskz:
1967   case X86::BI__builtin_ia32_rangepd512_mask:
1968   case X86::BI__builtin_ia32_rangeps512_mask:
1969   case X86::BI__builtin_ia32_rangesd128_round_mask:
1970   case X86::BI__builtin_ia32_rangess128_round_mask:
1971   case X86::BI__builtin_ia32_reducesd_mask:
1972   case X86::BI__builtin_ia32_reducess_mask:
1973   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1974   case X86::BI__builtin_ia32_rndscaless_round_mask:
1975     ArgNum = 5;
1976     break;
1977   case X86::BI__builtin_ia32_vcvtsd2si64:
1978   case X86::BI__builtin_ia32_vcvtsd2si32:
1979   case X86::BI__builtin_ia32_vcvtsd2usi32:
1980   case X86::BI__builtin_ia32_vcvtsd2usi64:
1981   case X86::BI__builtin_ia32_vcvtss2si32:
1982   case X86::BI__builtin_ia32_vcvtss2si64:
1983   case X86::BI__builtin_ia32_vcvtss2usi32:
1984   case X86::BI__builtin_ia32_vcvtss2usi64:
1985     ArgNum = 1;
1986     HasRC = true;
1987     break;
1988   case X86::BI__builtin_ia32_cvtsi2sd64:
1989   case X86::BI__builtin_ia32_cvtsi2ss32:
1990   case X86::BI__builtin_ia32_cvtsi2ss64:
1991   case X86::BI__builtin_ia32_cvtusi2sd64:
1992   case X86::BI__builtin_ia32_cvtusi2ss32:
1993   case X86::BI__builtin_ia32_cvtusi2ss64:
1994     ArgNum = 2;
1995     HasRC = true;
1996     break;
1997   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1998   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1999   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
2000   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
2001   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
2002   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2003   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2004   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2005   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2006   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2007   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2008   case X86::BI__builtin_ia32_sqrtpd512_mask:
2009   case X86::BI__builtin_ia32_sqrtps512_mask:
2010     ArgNum = 3;
2011     HasRC = true;
2012     break;
2013   case X86::BI__builtin_ia32_addpd512_mask:
2014   case X86::BI__builtin_ia32_addps512_mask:
2015   case X86::BI__builtin_ia32_divpd512_mask:
2016   case X86::BI__builtin_ia32_divps512_mask:
2017   case X86::BI__builtin_ia32_mulpd512_mask:
2018   case X86::BI__builtin_ia32_mulps512_mask:
2019   case X86::BI__builtin_ia32_subpd512_mask:
2020   case X86::BI__builtin_ia32_subps512_mask:
2021   case X86::BI__builtin_ia32_addss_round_mask:
2022   case X86::BI__builtin_ia32_addsd_round_mask:
2023   case X86::BI__builtin_ia32_divss_round_mask:
2024   case X86::BI__builtin_ia32_divsd_round_mask:
2025   case X86::BI__builtin_ia32_mulss_round_mask:
2026   case X86::BI__builtin_ia32_mulsd_round_mask:
2027   case X86::BI__builtin_ia32_subss_round_mask:
2028   case X86::BI__builtin_ia32_subsd_round_mask:
2029   case X86::BI__builtin_ia32_scalefpd512_mask:
2030   case X86::BI__builtin_ia32_scalefps512_mask:
2031   case X86::BI__builtin_ia32_scalefsd_round_mask:
2032   case X86::BI__builtin_ia32_scalefss_round_mask:
2033   case X86::BI__builtin_ia32_getmantpd512_mask:
2034   case X86::BI__builtin_ia32_getmantps512_mask:
2035   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2036   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2037   case X86::BI__builtin_ia32_sqrtss_round_mask:
2038   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2039   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2040   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2041   case X86::BI__builtin_ia32_vfmaddps512_mask:
2042   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2043   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2044   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2045   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2046   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2047   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2048   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2049   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2050   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2051   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2052   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2053   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2054   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2055   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2056   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2057   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2058   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2059   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2060   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2061   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2062   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2063   case X86::BI__builtin_ia32_vfmaddss3_mask:
2064   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2065   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2066     ArgNum = 4;
2067     HasRC = true;
2068     break;
2069   case X86::BI__builtin_ia32_getmantsd_round_mask:
2070   case X86::BI__builtin_ia32_getmantss_round_mask:
2071     ArgNum = 5;
2072     HasRC = true;
2073     break;
2074   }
2075 
2076   llvm::APSInt Result;
2077 
2078   // We can't check the value of a dependent argument.
2079   Expr *Arg = TheCall->getArg(ArgNum);
2080   if (Arg->isTypeDependent() || Arg->isValueDependent())
2081     return false;
2082 
2083   // Check constant-ness first.
2084   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2085     return true;
2086 
2087   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2088   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2089   // combined with ROUND_NO_EXC.
2090   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2091       Result == 8/*ROUND_NO_EXC*/ ||
2092       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2093     return false;
2094 
2095   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2096     << Arg->getSourceRange();
2097 }
2098 
2099 // Check if the gather/scatter scale is legal.
2100 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2101                                              CallExpr *TheCall) {
2102   unsigned ArgNum = 0;
2103   switch (BuiltinID) {
2104   default:
2105     return false;
2106   case X86::BI__builtin_ia32_gatherpfdpd:
2107   case X86::BI__builtin_ia32_gatherpfdps:
2108   case X86::BI__builtin_ia32_gatherpfqpd:
2109   case X86::BI__builtin_ia32_gatherpfqps:
2110   case X86::BI__builtin_ia32_scatterpfdpd:
2111   case X86::BI__builtin_ia32_scatterpfdps:
2112   case X86::BI__builtin_ia32_scatterpfqpd:
2113   case X86::BI__builtin_ia32_scatterpfqps:
2114     ArgNum = 3;
2115     break;
2116   case X86::BI__builtin_ia32_gatherd_pd:
2117   case X86::BI__builtin_ia32_gatherd_pd256:
2118   case X86::BI__builtin_ia32_gatherq_pd:
2119   case X86::BI__builtin_ia32_gatherq_pd256:
2120   case X86::BI__builtin_ia32_gatherd_ps:
2121   case X86::BI__builtin_ia32_gatherd_ps256:
2122   case X86::BI__builtin_ia32_gatherq_ps:
2123   case X86::BI__builtin_ia32_gatherq_ps256:
2124   case X86::BI__builtin_ia32_gatherd_q:
2125   case X86::BI__builtin_ia32_gatherd_q256:
2126   case X86::BI__builtin_ia32_gatherq_q:
2127   case X86::BI__builtin_ia32_gatherq_q256:
2128   case X86::BI__builtin_ia32_gatherd_d:
2129   case X86::BI__builtin_ia32_gatherd_d256:
2130   case X86::BI__builtin_ia32_gatherq_d:
2131   case X86::BI__builtin_ia32_gatherq_d256:
2132   case X86::BI__builtin_ia32_gather3div2df:
2133   case X86::BI__builtin_ia32_gather3div2di:
2134   case X86::BI__builtin_ia32_gather3div4df:
2135   case X86::BI__builtin_ia32_gather3div4di:
2136   case X86::BI__builtin_ia32_gather3div4sf:
2137   case X86::BI__builtin_ia32_gather3div4si:
2138   case X86::BI__builtin_ia32_gather3div8sf:
2139   case X86::BI__builtin_ia32_gather3div8si:
2140   case X86::BI__builtin_ia32_gather3siv2df:
2141   case X86::BI__builtin_ia32_gather3siv2di:
2142   case X86::BI__builtin_ia32_gather3siv4df:
2143   case X86::BI__builtin_ia32_gather3siv4di:
2144   case X86::BI__builtin_ia32_gather3siv4sf:
2145   case X86::BI__builtin_ia32_gather3siv4si:
2146   case X86::BI__builtin_ia32_gather3siv8sf:
2147   case X86::BI__builtin_ia32_gather3siv8si:
2148   case X86::BI__builtin_ia32_gathersiv8df:
2149   case X86::BI__builtin_ia32_gathersiv16sf:
2150   case X86::BI__builtin_ia32_gatherdiv8df:
2151   case X86::BI__builtin_ia32_gatherdiv16sf:
2152   case X86::BI__builtin_ia32_gathersiv8di:
2153   case X86::BI__builtin_ia32_gathersiv16si:
2154   case X86::BI__builtin_ia32_gatherdiv8di:
2155   case X86::BI__builtin_ia32_gatherdiv16si:
2156   case X86::BI__builtin_ia32_scatterdiv2df:
2157   case X86::BI__builtin_ia32_scatterdiv2di:
2158   case X86::BI__builtin_ia32_scatterdiv4df:
2159   case X86::BI__builtin_ia32_scatterdiv4di:
2160   case X86::BI__builtin_ia32_scatterdiv4sf:
2161   case X86::BI__builtin_ia32_scatterdiv4si:
2162   case X86::BI__builtin_ia32_scatterdiv8sf:
2163   case X86::BI__builtin_ia32_scatterdiv8si:
2164   case X86::BI__builtin_ia32_scattersiv2df:
2165   case X86::BI__builtin_ia32_scattersiv2di:
2166   case X86::BI__builtin_ia32_scattersiv4df:
2167   case X86::BI__builtin_ia32_scattersiv4di:
2168   case X86::BI__builtin_ia32_scattersiv4sf:
2169   case X86::BI__builtin_ia32_scattersiv4si:
2170   case X86::BI__builtin_ia32_scattersiv8sf:
2171   case X86::BI__builtin_ia32_scattersiv8si:
2172   case X86::BI__builtin_ia32_scattersiv8df:
2173   case X86::BI__builtin_ia32_scattersiv16sf:
2174   case X86::BI__builtin_ia32_scatterdiv8df:
2175   case X86::BI__builtin_ia32_scatterdiv16sf:
2176   case X86::BI__builtin_ia32_scattersiv8di:
2177   case X86::BI__builtin_ia32_scattersiv16si:
2178   case X86::BI__builtin_ia32_scatterdiv8di:
2179   case X86::BI__builtin_ia32_scatterdiv16si:
2180     ArgNum = 4;
2181     break;
2182   }
2183 
2184   llvm::APSInt Result;
2185 
2186   // We can't check the value of a dependent argument.
2187   Expr *Arg = TheCall->getArg(ArgNum);
2188   if (Arg->isTypeDependent() || Arg->isValueDependent())
2189     return false;
2190 
2191   // Check constant-ness first.
2192   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2193     return true;
2194 
2195   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2196     return false;
2197 
2198   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2199     << Arg->getSourceRange();
2200 }
2201 
2202 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2203   if (BuiltinID == X86::BI__builtin_cpu_supports)
2204     return SemaBuiltinCpuSupports(*this, TheCall);
2205 
2206   if (BuiltinID == X86::BI__builtin_cpu_is)
2207     return SemaBuiltinCpuIs(*this, TheCall);
2208 
2209   // If the intrinsic has rounding or SAE make sure its valid.
2210   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2211     return true;
2212 
2213   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2214   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2215     return true;
2216 
2217   // For intrinsics which take an immediate value as part of the instruction,
2218   // range check them here.
2219   int i = 0, l = 0, u = 0;
2220   switch (BuiltinID) {
2221   default:
2222     return false;
2223   case X86::BI_mm_prefetch:
2224     i = 1; l = 0; u = 3;
2225     break;
2226   case X86::BI__builtin_ia32_sha1rnds4:
2227   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2228   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2229   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2230   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2231     i = 2; l = 0; u = 3;
2232     break;
2233   case X86::BI__builtin_ia32_vpermil2pd:
2234   case X86::BI__builtin_ia32_vpermil2pd256:
2235   case X86::BI__builtin_ia32_vpermil2ps:
2236   case X86::BI__builtin_ia32_vpermil2ps256:
2237     i = 3; l = 0; u = 3;
2238     break;
2239   case X86::BI__builtin_ia32_cmpb128_mask:
2240   case X86::BI__builtin_ia32_cmpw128_mask:
2241   case X86::BI__builtin_ia32_cmpd128_mask:
2242   case X86::BI__builtin_ia32_cmpq128_mask:
2243   case X86::BI__builtin_ia32_cmpb256_mask:
2244   case X86::BI__builtin_ia32_cmpw256_mask:
2245   case X86::BI__builtin_ia32_cmpd256_mask:
2246   case X86::BI__builtin_ia32_cmpq256_mask:
2247   case X86::BI__builtin_ia32_cmpb512_mask:
2248   case X86::BI__builtin_ia32_cmpw512_mask:
2249   case X86::BI__builtin_ia32_cmpd512_mask:
2250   case X86::BI__builtin_ia32_cmpq512_mask:
2251   case X86::BI__builtin_ia32_ucmpb128_mask:
2252   case X86::BI__builtin_ia32_ucmpw128_mask:
2253   case X86::BI__builtin_ia32_ucmpd128_mask:
2254   case X86::BI__builtin_ia32_ucmpq128_mask:
2255   case X86::BI__builtin_ia32_ucmpb256_mask:
2256   case X86::BI__builtin_ia32_ucmpw256_mask:
2257   case X86::BI__builtin_ia32_ucmpd256_mask:
2258   case X86::BI__builtin_ia32_ucmpq256_mask:
2259   case X86::BI__builtin_ia32_ucmpb512_mask:
2260   case X86::BI__builtin_ia32_ucmpw512_mask:
2261   case X86::BI__builtin_ia32_ucmpd512_mask:
2262   case X86::BI__builtin_ia32_ucmpq512_mask:
2263   case X86::BI__builtin_ia32_vpcomub:
2264   case X86::BI__builtin_ia32_vpcomuw:
2265   case X86::BI__builtin_ia32_vpcomud:
2266   case X86::BI__builtin_ia32_vpcomuq:
2267   case X86::BI__builtin_ia32_vpcomb:
2268   case X86::BI__builtin_ia32_vpcomw:
2269   case X86::BI__builtin_ia32_vpcomd:
2270   case X86::BI__builtin_ia32_vpcomq:
2271     i = 2; l = 0; u = 7;
2272     break;
2273   case X86::BI__builtin_ia32_roundps:
2274   case X86::BI__builtin_ia32_roundpd:
2275   case X86::BI__builtin_ia32_roundps256:
2276   case X86::BI__builtin_ia32_roundpd256:
2277     i = 1; l = 0; u = 15;
2278     break;
2279   case X86::BI__builtin_ia32_roundss:
2280   case X86::BI__builtin_ia32_roundsd:
2281   case X86::BI__builtin_ia32_rangepd128_mask:
2282   case X86::BI__builtin_ia32_rangepd256_mask:
2283   case X86::BI__builtin_ia32_rangepd512_mask:
2284   case X86::BI__builtin_ia32_rangeps128_mask:
2285   case X86::BI__builtin_ia32_rangeps256_mask:
2286   case X86::BI__builtin_ia32_rangeps512_mask:
2287   case X86::BI__builtin_ia32_getmantsd_round_mask:
2288   case X86::BI__builtin_ia32_getmantss_round_mask:
2289     i = 2; l = 0; u = 15;
2290     break;
2291   case X86::BI__builtin_ia32_cmpps:
2292   case X86::BI__builtin_ia32_cmpss:
2293   case X86::BI__builtin_ia32_cmppd:
2294   case X86::BI__builtin_ia32_cmpsd:
2295   case X86::BI__builtin_ia32_cmpps256:
2296   case X86::BI__builtin_ia32_cmppd256:
2297   case X86::BI__builtin_ia32_cmpps128_mask:
2298   case X86::BI__builtin_ia32_cmppd128_mask:
2299   case X86::BI__builtin_ia32_cmpps256_mask:
2300   case X86::BI__builtin_ia32_cmppd256_mask:
2301   case X86::BI__builtin_ia32_cmpps512_mask:
2302   case X86::BI__builtin_ia32_cmppd512_mask:
2303   case X86::BI__builtin_ia32_cmpsd_mask:
2304   case X86::BI__builtin_ia32_cmpss_mask:
2305     i = 2; l = 0; u = 31;
2306     break;
2307   case X86::BI__builtin_ia32_xabort:
2308     i = 0; l = -128; u = 255;
2309     break;
2310   case X86::BI__builtin_ia32_pshufw:
2311   case X86::BI__builtin_ia32_aeskeygenassist128:
2312     i = 1; l = -128; u = 255;
2313     break;
2314   case X86::BI__builtin_ia32_vcvtps2ph:
2315   case X86::BI__builtin_ia32_vcvtps2ph_mask:
2316   case X86::BI__builtin_ia32_vcvtps2ph256:
2317   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
2318   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
2319   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2320   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2321   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2322   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2323   case X86::BI__builtin_ia32_rndscaleps_mask:
2324   case X86::BI__builtin_ia32_rndscalepd_mask:
2325   case X86::BI__builtin_ia32_reducepd128_mask:
2326   case X86::BI__builtin_ia32_reducepd256_mask:
2327   case X86::BI__builtin_ia32_reducepd512_mask:
2328   case X86::BI__builtin_ia32_reduceps128_mask:
2329   case X86::BI__builtin_ia32_reduceps256_mask:
2330   case X86::BI__builtin_ia32_reduceps512_mask:
2331   case X86::BI__builtin_ia32_prold512_mask:
2332   case X86::BI__builtin_ia32_prolq512_mask:
2333   case X86::BI__builtin_ia32_prold128_mask:
2334   case X86::BI__builtin_ia32_prold256_mask:
2335   case X86::BI__builtin_ia32_prolq128_mask:
2336   case X86::BI__builtin_ia32_prolq256_mask:
2337   case X86::BI__builtin_ia32_prord128_mask:
2338   case X86::BI__builtin_ia32_prord256_mask:
2339   case X86::BI__builtin_ia32_prorq128_mask:
2340   case X86::BI__builtin_ia32_prorq256_mask:
2341   case X86::BI__builtin_ia32_fpclasspd128_mask:
2342   case X86::BI__builtin_ia32_fpclasspd256_mask:
2343   case X86::BI__builtin_ia32_fpclassps128_mask:
2344   case X86::BI__builtin_ia32_fpclassps256_mask:
2345   case X86::BI__builtin_ia32_fpclassps512_mask:
2346   case X86::BI__builtin_ia32_fpclasspd512_mask:
2347   case X86::BI__builtin_ia32_fpclasssd_mask:
2348   case X86::BI__builtin_ia32_fpclassss_mask:
2349     i = 1; l = 0; u = 255;
2350     break;
2351   case X86::BI__builtin_ia32_palignr:
2352   case X86::BI__builtin_ia32_insertps128:
2353   case X86::BI__builtin_ia32_dpps:
2354   case X86::BI__builtin_ia32_dppd:
2355   case X86::BI__builtin_ia32_dpps256:
2356   case X86::BI__builtin_ia32_mpsadbw128:
2357   case X86::BI__builtin_ia32_mpsadbw256:
2358   case X86::BI__builtin_ia32_pcmpistrm128:
2359   case X86::BI__builtin_ia32_pcmpistri128:
2360   case X86::BI__builtin_ia32_pcmpistria128:
2361   case X86::BI__builtin_ia32_pcmpistric128:
2362   case X86::BI__builtin_ia32_pcmpistrio128:
2363   case X86::BI__builtin_ia32_pcmpistris128:
2364   case X86::BI__builtin_ia32_pcmpistriz128:
2365   case X86::BI__builtin_ia32_pclmulqdq128:
2366   case X86::BI__builtin_ia32_vperm2f128_pd256:
2367   case X86::BI__builtin_ia32_vperm2f128_ps256:
2368   case X86::BI__builtin_ia32_vperm2f128_si256:
2369   case X86::BI__builtin_ia32_permti256:
2370     i = 2; l = -128; u = 255;
2371     break;
2372   case X86::BI__builtin_ia32_palignr128:
2373   case X86::BI__builtin_ia32_palignr256:
2374   case X86::BI__builtin_ia32_palignr512_mask:
2375   case X86::BI__builtin_ia32_vcomisd:
2376   case X86::BI__builtin_ia32_vcomiss:
2377   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2378   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2379   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2380   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2381   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2382   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2383   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2384     i = 2; l = 0; u = 255;
2385     break;
2386   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2387   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2388   case X86::BI__builtin_ia32_fixupimmps512_mask:
2389   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2390   case X86::BI__builtin_ia32_fixupimmsd_mask:
2391   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2392   case X86::BI__builtin_ia32_fixupimmss_mask:
2393   case X86::BI__builtin_ia32_fixupimmss_maskz:
2394   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2395   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2396   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2397   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2398   case X86::BI__builtin_ia32_fixupimmps128_mask:
2399   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2400   case X86::BI__builtin_ia32_fixupimmps256_mask:
2401   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2402   case X86::BI__builtin_ia32_pternlogd512_mask:
2403   case X86::BI__builtin_ia32_pternlogd512_maskz:
2404   case X86::BI__builtin_ia32_pternlogq512_mask:
2405   case X86::BI__builtin_ia32_pternlogq512_maskz:
2406   case X86::BI__builtin_ia32_pternlogd128_mask:
2407   case X86::BI__builtin_ia32_pternlogd128_maskz:
2408   case X86::BI__builtin_ia32_pternlogd256_mask:
2409   case X86::BI__builtin_ia32_pternlogd256_maskz:
2410   case X86::BI__builtin_ia32_pternlogq128_mask:
2411   case X86::BI__builtin_ia32_pternlogq128_maskz:
2412   case X86::BI__builtin_ia32_pternlogq256_mask:
2413   case X86::BI__builtin_ia32_pternlogq256_maskz:
2414     i = 3; l = 0; u = 255;
2415     break;
2416   case X86::BI__builtin_ia32_gatherpfdpd:
2417   case X86::BI__builtin_ia32_gatherpfdps:
2418   case X86::BI__builtin_ia32_gatherpfqpd:
2419   case X86::BI__builtin_ia32_gatherpfqps:
2420   case X86::BI__builtin_ia32_scatterpfdpd:
2421   case X86::BI__builtin_ia32_scatterpfdps:
2422   case X86::BI__builtin_ia32_scatterpfqpd:
2423   case X86::BI__builtin_ia32_scatterpfqps:
2424     i = 4; l = 2; u = 3;
2425     break;
2426   case X86::BI__builtin_ia32_pcmpestrm128:
2427   case X86::BI__builtin_ia32_pcmpestri128:
2428   case X86::BI__builtin_ia32_pcmpestria128:
2429   case X86::BI__builtin_ia32_pcmpestric128:
2430   case X86::BI__builtin_ia32_pcmpestrio128:
2431   case X86::BI__builtin_ia32_pcmpestris128:
2432   case X86::BI__builtin_ia32_pcmpestriz128:
2433     i = 4; l = -128; u = 255;
2434     break;
2435   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2436   case X86::BI__builtin_ia32_rndscaless_round_mask:
2437     i = 4; l = 0; u = 255;
2438     break;
2439   }
2440   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2441 }
2442 
2443 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2444 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2445 /// Returns true when the format fits the function and the FormatStringInfo has
2446 /// been populated.
2447 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2448                                FormatStringInfo *FSI) {
2449   FSI->HasVAListArg = Format->getFirstArg() == 0;
2450   FSI->FormatIdx = Format->getFormatIdx() - 1;
2451   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2452 
2453   // The way the format attribute works in GCC, the implicit this argument
2454   // of member functions is counted. However, it doesn't appear in our own
2455   // lists, so decrement format_idx in that case.
2456   if (IsCXXMember) {
2457     if(FSI->FormatIdx == 0)
2458       return false;
2459     --FSI->FormatIdx;
2460     if (FSI->FirstDataArg != 0)
2461       --FSI->FirstDataArg;
2462   }
2463   return true;
2464 }
2465 
2466 /// Checks if a the given expression evaluates to null.
2467 ///
2468 /// \brief Returns true if the value evaluates to null.
2469 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2470   // If the expression has non-null type, it doesn't evaluate to null.
2471   if (auto nullability
2472         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2473     if (*nullability == NullabilityKind::NonNull)
2474       return false;
2475   }
2476 
2477   // As a special case, transparent unions initialized with zero are
2478   // considered null for the purposes of the nonnull attribute.
2479   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2480     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2481       if (const CompoundLiteralExpr *CLE =
2482           dyn_cast<CompoundLiteralExpr>(Expr))
2483         if (const InitListExpr *ILE =
2484             dyn_cast<InitListExpr>(CLE->getInitializer()))
2485           Expr = ILE->getInit(0);
2486   }
2487 
2488   bool Result;
2489   return (!Expr->isValueDependent() &&
2490           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2491           !Result);
2492 }
2493 
2494 static void CheckNonNullArgument(Sema &S,
2495                                  const Expr *ArgExpr,
2496                                  SourceLocation CallSiteLoc) {
2497   if (CheckNonNullExpr(S, ArgExpr))
2498     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2499            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2500 }
2501 
2502 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2503   FormatStringInfo FSI;
2504   if ((GetFormatStringType(Format) == FST_NSString) &&
2505       getFormatStringInfo(Format, false, &FSI)) {
2506     Idx = FSI.FormatIdx;
2507     return true;
2508   }
2509   return false;
2510 }
2511 /// \brief Diagnose use of %s directive in an NSString which is being passed
2512 /// as formatting string to formatting method.
2513 static void
2514 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2515                                         const NamedDecl *FDecl,
2516                                         Expr **Args,
2517                                         unsigned NumArgs) {
2518   unsigned Idx = 0;
2519   bool Format = false;
2520   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2521   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2522     Idx = 2;
2523     Format = true;
2524   }
2525   else
2526     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2527       if (S.GetFormatNSStringIdx(I, Idx)) {
2528         Format = true;
2529         break;
2530       }
2531     }
2532   if (!Format || NumArgs <= Idx)
2533     return;
2534   const Expr *FormatExpr = Args[Idx];
2535   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2536     FormatExpr = CSCE->getSubExpr();
2537   const StringLiteral *FormatString;
2538   if (const ObjCStringLiteral *OSL =
2539       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2540     FormatString = OSL->getString();
2541   else
2542     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2543   if (!FormatString)
2544     return;
2545   if (S.FormatStringHasSArg(FormatString)) {
2546     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2547       << "%s" << 1 << 1;
2548     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2549       << FDecl->getDeclName();
2550   }
2551 }
2552 
2553 /// Determine whether the given type has a non-null nullability annotation.
2554 static bool isNonNullType(ASTContext &ctx, QualType type) {
2555   if (auto nullability = type->getNullability(ctx))
2556     return *nullability == NullabilityKind::NonNull;
2557 
2558   return false;
2559 }
2560 
2561 static void CheckNonNullArguments(Sema &S,
2562                                   const NamedDecl *FDecl,
2563                                   const FunctionProtoType *Proto,
2564                                   ArrayRef<const Expr *> Args,
2565                                   SourceLocation CallSiteLoc) {
2566   assert((FDecl || Proto) && "Need a function declaration or prototype");
2567 
2568   // Check the attributes attached to the method/function itself.
2569   llvm::SmallBitVector NonNullArgs;
2570   if (FDecl) {
2571     // Handle the nonnull attribute on the function/method declaration itself.
2572     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2573       if (!NonNull->args_size()) {
2574         // Easy case: all pointer arguments are nonnull.
2575         for (const auto *Arg : Args)
2576           if (S.isValidPointerAttrType(Arg->getType()))
2577             CheckNonNullArgument(S, Arg, CallSiteLoc);
2578         return;
2579       }
2580 
2581       for (unsigned Val : NonNull->args()) {
2582         if (Val >= Args.size())
2583           continue;
2584         if (NonNullArgs.empty())
2585           NonNullArgs.resize(Args.size());
2586         NonNullArgs.set(Val);
2587       }
2588     }
2589   }
2590 
2591   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2592     // Handle the nonnull attribute on the parameters of the
2593     // function/method.
2594     ArrayRef<ParmVarDecl*> parms;
2595     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2596       parms = FD->parameters();
2597     else
2598       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2599 
2600     unsigned ParamIndex = 0;
2601     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2602          I != E; ++I, ++ParamIndex) {
2603       const ParmVarDecl *PVD = *I;
2604       if (PVD->hasAttr<NonNullAttr>() ||
2605           isNonNullType(S.Context, PVD->getType())) {
2606         if (NonNullArgs.empty())
2607           NonNullArgs.resize(Args.size());
2608 
2609         NonNullArgs.set(ParamIndex);
2610       }
2611     }
2612   } else {
2613     // If we have a non-function, non-method declaration but no
2614     // function prototype, try to dig out the function prototype.
2615     if (!Proto) {
2616       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2617         QualType type = VD->getType().getNonReferenceType();
2618         if (auto pointerType = type->getAs<PointerType>())
2619           type = pointerType->getPointeeType();
2620         else if (auto blockType = type->getAs<BlockPointerType>())
2621           type = blockType->getPointeeType();
2622         // FIXME: data member pointers?
2623 
2624         // Dig out the function prototype, if there is one.
2625         Proto = type->getAs<FunctionProtoType>();
2626       }
2627     }
2628 
2629     // Fill in non-null argument information from the nullability
2630     // information on the parameter types (if we have them).
2631     if (Proto) {
2632       unsigned Index = 0;
2633       for (auto paramType : Proto->getParamTypes()) {
2634         if (isNonNullType(S.Context, paramType)) {
2635           if (NonNullArgs.empty())
2636             NonNullArgs.resize(Args.size());
2637 
2638           NonNullArgs.set(Index);
2639         }
2640 
2641         ++Index;
2642       }
2643     }
2644   }
2645 
2646   // Check for non-null arguments.
2647   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2648        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2649     if (NonNullArgs[ArgIndex])
2650       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2651   }
2652 }
2653 
2654 /// Handles the checks for format strings, non-POD arguments to vararg
2655 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2656 /// attributes.
2657 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2658                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2659                      bool IsMemberFunction, SourceLocation Loc,
2660                      SourceRange Range, VariadicCallType CallType) {
2661   // FIXME: We should check as much as we can in the template definition.
2662   if (CurContext->isDependentContext())
2663     return;
2664 
2665   // Printf and scanf checking.
2666   llvm::SmallBitVector CheckedVarArgs;
2667   if (FDecl) {
2668     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2669       // Only create vector if there are format attributes.
2670       CheckedVarArgs.resize(Args.size());
2671 
2672       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2673                            CheckedVarArgs);
2674     }
2675   }
2676 
2677   // Refuse POD arguments that weren't caught by the format string
2678   // checks above.
2679   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2680   if (CallType != VariadicDoesNotApply &&
2681       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2682     unsigned NumParams = Proto ? Proto->getNumParams()
2683                        : FDecl && isa<FunctionDecl>(FDecl)
2684                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2685                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2686                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2687                        : 0;
2688 
2689     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2690       // Args[ArgIdx] can be null in malformed code.
2691       if (const Expr *Arg = Args[ArgIdx]) {
2692         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2693           checkVariadicArgument(Arg, CallType);
2694       }
2695     }
2696   }
2697 
2698   if (FDecl || Proto) {
2699     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2700 
2701     // Type safety checking.
2702     if (FDecl) {
2703       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2704         CheckArgumentWithTypeTag(I, Args.data());
2705     }
2706   }
2707 
2708   if (FD)
2709     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2710 }
2711 
2712 /// CheckConstructorCall - Check a constructor call for correctness and safety
2713 /// properties not enforced by the C type system.
2714 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2715                                 ArrayRef<const Expr *> Args,
2716                                 const FunctionProtoType *Proto,
2717                                 SourceLocation Loc) {
2718   VariadicCallType CallType =
2719     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2720   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2721             Loc, SourceRange(), CallType);
2722 }
2723 
2724 /// CheckFunctionCall - Check a direct function call for various correctness
2725 /// and safety properties not strictly enforced by the C type system.
2726 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2727                              const FunctionProtoType *Proto) {
2728   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2729                               isa<CXXMethodDecl>(FDecl);
2730   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2731                           IsMemberOperatorCall;
2732   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2733                                                   TheCall->getCallee());
2734   Expr** Args = TheCall->getArgs();
2735   unsigned NumArgs = TheCall->getNumArgs();
2736 
2737   Expr *ImplicitThis = nullptr;
2738   if (IsMemberOperatorCall) {
2739     // If this is a call to a member operator, hide the first argument
2740     // from checkCall.
2741     // FIXME: Our choice of AST representation here is less than ideal.
2742     ImplicitThis = Args[0];
2743     ++Args;
2744     --NumArgs;
2745   } else if (IsMemberFunction)
2746     ImplicitThis =
2747         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2748 
2749   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2750             IsMemberFunction, TheCall->getRParenLoc(),
2751             TheCall->getCallee()->getSourceRange(), CallType);
2752 
2753   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2754   // None of the checks below are needed for functions that don't have
2755   // simple names (e.g., C++ conversion functions).
2756   if (!FnInfo)
2757     return false;
2758 
2759   CheckAbsoluteValueFunction(TheCall, FDecl);
2760   CheckMaxUnsignedZero(TheCall, FDecl);
2761 
2762   if (getLangOpts().ObjC1)
2763     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2764 
2765   unsigned CMId = FDecl->getMemoryFunctionKind();
2766   if (CMId == 0)
2767     return false;
2768 
2769   // Handle memory setting and copying functions.
2770   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2771     CheckStrlcpycatArguments(TheCall, FnInfo);
2772   else if (CMId == Builtin::BIstrncat)
2773     CheckStrncatArguments(TheCall, FnInfo);
2774   else
2775     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2776 
2777   return false;
2778 }
2779 
2780 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2781                                ArrayRef<const Expr *> Args) {
2782   VariadicCallType CallType =
2783       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2784 
2785   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2786             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2787             CallType);
2788 
2789   return false;
2790 }
2791 
2792 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2793                             const FunctionProtoType *Proto) {
2794   QualType Ty;
2795   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2796     Ty = V->getType().getNonReferenceType();
2797   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2798     Ty = F->getType().getNonReferenceType();
2799   else
2800     return false;
2801 
2802   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2803       !Ty->isFunctionProtoType())
2804     return false;
2805 
2806   VariadicCallType CallType;
2807   if (!Proto || !Proto->isVariadic()) {
2808     CallType = VariadicDoesNotApply;
2809   } else if (Ty->isBlockPointerType()) {
2810     CallType = VariadicBlock;
2811   } else { // Ty->isFunctionPointerType()
2812     CallType = VariadicFunction;
2813   }
2814 
2815   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2816             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2817             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2818             TheCall->getCallee()->getSourceRange(), CallType);
2819 
2820   return false;
2821 }
2822 
2823 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2824 /// such as function pointers returned from functions.
2825 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2826   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2827                                                   TheCall->getCallee());
2828   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2829             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2830             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2831             TheCall->getCallee()->getSourceRange(), CallType);
2832 
2833   return false;
2834 }
2835 
2836 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2837   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2838     return false;
2839 
2840   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2841   switch (Op) {
2842   case AtomicExpr::AO__c11_atomic_init:
2843   case AtomicExpr::AO__opencl_atomic_init:
2844     llvm_unreachable("There is no ordering argument for an init");
2845 
2846   case AtomicExpr::AO__c11_atomic_load:
2847   case AtomicExpr::AO__opencl_atomic_load:
2848   case AtomicExpr::AO__atomic_load_n:
2849   case AtomicExpr::AO__atomic_load:
2850     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2851            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2852 
2853   case AtomicExpr::AO__c11_atomic_store:
2854   case AtomicExpr::AO__opencl_atomic_store:
2855   case AtomicExpr::AO__atomic_store:
2856   case AtomicExpr::AO__atomic_store_n:
2857     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2858            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2859            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2860 
2861   default:
2862     return true;
2863   }
2864 }
2865 
2866 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2867                                          AtomicExpr::AtomicOp Op) {
2868   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2869   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2870 
2871   // All the non-OpenCL operations take one of the following forms.
2872   // The OpenCL operations take the __c11 forms with one extra argument for
2873   // synchronization scope.
2874   enum {
2875     // C    __c11_atomic_init(A *, C)
2876     Init,
2877     // C    __c11_atomic_load(A *, int)
2878     Load,
2879     // void __atomic_load(A *, CP, int)
2880     LoadCopy,
2881     // void __atomic_store(A *, CP, int)
2882     Copy,
2883     // C    __c11_atomic_add(A *, M, int)
2884     Arithmetic,
2885     // C    __atomic_exchange_n(A *, CP, int)
2886     Xchg,
2887     // void __atomic_exchange(A *, C *, CP, int)
2888     GNUXchg,
2889     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2890     C11CmpXchg,
2891     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2892     GNUCmpXchg
2893   } Form = Init;
2894   const unsigned NumForm = GNUCmpXchg + 1;
2895   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2896   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2897   // where:
2898   //   C is an appropriate type,
2899   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2900   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2901   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2902   //   the int parameters are for orderings.
2903 
2904   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2905       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2906       "need to update code for modified forms");
2907   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2908                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2909                         AtomicExpr::AO__atomic_load,
2910                 "need to update code for modified C11 atomics");
2911   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2912                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2913   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2914                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2915                IsOpenCL;
2916   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2917              Op == AtomicExpr::AO__atomic_store_n ||
2918              Op == AtomicExpr::AO__atomic_exchange_n ||
2919              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2920   bool IsAddSub = false;
2921 
2922   switch (Op) {
2923   case AtomicExpr::AO__c11_atomic_init:
2924   case AtomicExpr::AO__opencl_atomic_init:
2925     Form = Init;
2926     break;
2927 
2928   case AtomicExpr::AO__c11_atomic_load:
2929   case AtomicExpr::AO__opencl_atomic_load:
2930   case AtomicExpr::AO__atomic_load_n:
2931     Form = Load;
2932     break;
2933 
2934   case AtomicExpr::AO__atomic_load:
2935     Form = LoadCopy;
2936     break;
2937 
2938   case AtomicExpr::AO__c11_atomic_store:
2939   case AtomicExpr::AO__opencl_atomic_store:
2940   case AtomicExpr::AO__atomic_store:
2941   case AtomicExpr::AO__atomic_store_n:
2942     Form = Copy;
2943     break;
2944 
2945   case AtomicExpr::AO__c11_atomic_fetch_add:
2946   case AtomicExpr::AO__c11_atomic_fetch_sub:
2947   case AtomicExpr::AO__opencl_atomic_fetch_add:
2948   case AtomicExpr::AO__opencl_atomic_fetch_sub:
2949   case AtomicExpr::AO__opencl_atomic_fetch_min:
2950   case AtomicExpr::AO__opencl_atomic_fetch_max:
2951   case AtomicExpr::AO__atomic_fetch_add:
2952   case AtomicExpr::AO__atomic_fetch_sub:
2953   case AtomicExpr::AO__atomic_add_fetch:
2954   case AtomicExpr::AO__atomic_sub_fetch:
2955     IsAddSub = true;
2956     // Fall through.
2957   case AtomicExpr::AO__c11_atomic_fetch_and:
2958   case AtomicExpr::AO__c11_atomic_fetch_or:
2959   case AtomicExpr::AO__c11_atomic_fetch_xor:
2960   case AtomicExpr::AO__opencl_atomic_fetch_and:
2961   case AtomicExpr::AO__opencl_atomic_fetch_or:
2962   case AtomicExpr::AO__opencl_atomic_fetch_xor:
2963   case AtomicExpr::AO__atomic_fetch_and:
2964   case AtomicExpr::AO__atomic_fetch_or:
2965   case AtomicExpr::AO__atomic_fetch_xor:
2966   case AtomicExpr::AO__atomic_fetch_nand:
2967   case AtomicExpr::AO__atomic_and_fetch:
2968   case AtomicExpr::AO__atomic_or_fetch:
2969   case AtomicExpr::AO__atomic_xor_fetch:
2970   case AtomicExpr::AO__atomic_nand_fetch:
2971     Form = Arithmetic;
2972     break;
2973 
2974   case AtomicExpr::AO__c11_atomic_exchange:
2975   case AtomicExpr::AO__opencl_atomic_exchange:
2976   case AtomicExpr::AO__atomic_exchange_n:
2977     Form = Xchg;
2978     break;
2979 
2980   case AtomicExpr::AO__atomic_exchange:
2981     Form = GNUXchg;
2982     break;
2983 
2984   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2985   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2986   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2987   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
2988     Form = C11CmpXchg;
2989     break;
2990 
2991   case AtomicExpr::AO__atomic_compare_exchange:
2992   case AtomicExpr::AO__atomic_compare_exchange_n:
2993     Form = GNUCmpXchg;
2994     break;
2995   }
2996 
2997   unsigned AdjustedNumArgs = NumArgs[Form];
2998   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2999     ++AdjustedNumArgs;
3000   // Check we have the right number of arguments.
3001   if (TheCall->getNumArgs() < AdjustedNumArgs) {
3002     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3003       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3004       << TheCall->getCallee()->getSourceRange();
3005     return ExprError();
3006   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3007     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3008          diag::err_typecheck_call_too_many_args)
3009       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3010       << TheCall->getCallee()->getSourceRange();
3011     return ExprError();
3012   }
3013 
3014   // Inspect the first argument of the atomic operation.
3015   Expr *Ptr = TheCall->getArg(0);
3016   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3017   if (ConvertedPtr.isInvalid())
3018     return ExprError();
3019 
3020   Ptr = ConvertedPtr.get();
3021   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3022   if (!pointerType) {
3023     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3024       << Ptr->getType() << Ptr->getSourceRange();
3025     return ExprError();
3026   }
3027 
3028   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3029   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3030   QualType ValType = AtomTy; // 'C'
3031   if (IsC11) {
3032     if (!AtomTy->isAtomicType()) {
3033       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3034         << Ptr->getType() << Ptr->getSourceRange();
3035       return ExprError();
3036     }
3037     if (AtomTy.isConstQualified() ||
3038         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3039       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3040           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3041           << Ptr->getSourceRange();
3042       return ExprError();
3043     }
3044     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3045   } else if (Form != Load && Form != LoadCopy) {
3046     if (ValType.isConstQualified()) {
3047       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3048         << Ptr->getType() << Ptr->getSourceRange();
3049       return ExprError();
3050     }
3051   }
3052 
3053   // For an arithmetic operation, the implied arithmetic must be well-formed.
3054   if (Form == Arithmetic) {
3055     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3056     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3057       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3058         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3059       return ExprError();
3060     }
3061     if (!IsAddSub && !ValType->isIntegerType()) {
3062       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3063         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3064       return ExprError();
3065     }
3066     if (IsC11 && ValType->isPointerType() &&
3067         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3068                             diag::err_incomplete_type)) {
3069       return ExprError();
3070     }
3071   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3072     // For __atomic_*_n operations, the value type must be a scalar integral or
3073     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3074     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3075       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3076     return ExprError();
3077   }
3078 
3079   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3080       !AtomTy->isScalarType()) {
3081     // For GNU atomics, require a trivially-copyable type. This is not part of
3082     // the GNU atomics specification, but we enforce it for sanity.
3083     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3084       << Ptr->getType() << Ptr->getSourceRange();
3085     return ExprError();
3086   }
3087 
3088   switch (ValType.getObjCLifetime()) {
3089   case Qualifiers::OCL_None:
3090   case Qualifiers::OCL_ExplicitNone:
3091     // okay
3092     break;
3093 
3094   case Qualifiers::OCL_Weak:
3095   case Qualifiers::OCL_Strong:
3096   case Qualifiers::OCL_Autoreleasing:
3097     // FIXME: Can this happen? By this point, ValType should be known
3098     // to be trivially copyable.
3099     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3100       << ValType << Ptr->getSourceRange();
3101     return ExprError();
3102   }
3103 
3104   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3105   // volatile-ness of the pointee-type inject itself into the result or the
3106   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3107   ValType.removeLocalVolatile();
3108   ValType.removeLocalConst();
3109   QualType ResultType = ValType;
3110   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3111       Form == Init)
3112     ResultType = Context.VoidTy;
3113   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3114     ResultType = Context.BoolTy;
3115 
3116   // The type of a parameter passed 'by value'. In the GNU atomics, such
3117   // arguments are actually passed as pointers.
3118   QualType ByValType = ValType; // 'CP'
3119   if (!IsC11 && !IsN)
3120     ByValType = Ptr->getType();
3121 
3122   // The first argument --- the pointer --- has a fixed type; we
3123   // deduce the types of the rest of the arguments accordingly.  Walk
3124   // the remaining arguments, converting them to the deduced value type.
3125   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3126     QualType Ty;
3127     if (i < NumVals[Form] + 1) {
3128       switch (i) {
3129       case 1:
3130         // The second argument is the non-atomic operand. For arithmetic, this
3131         // is always passed by value, and for a compare_exchange it is always
3132         // passed by address. For the rest, GNU uses by-address and C11 uses
3133         // by-value.
3134         assert(Form != Load);
3135         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3136           Ty = ValType;
3137         else if (Form == Copy || Form == Xchg)
3138           Ty = ByValType;
3139         else if (Form == Arithmetic)
3140           Ty = Context.getPointerDiffType();
3141         else {
3142           Expr *ValArg = TheCall->getArg(i);
3143           // Treat this argument as _Nonnull as we want to show a warning if
3144           // NULL is passed into it.
3145           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3146           LangAS AS = LangAS::Default;
3147           // Keep address space of non-atomic pointer type.
3148           if (const PointerType *PtrTy =
3149                   ValArg->getType()->getAs<PointerType>()) {
3150             AS = PtrTy->getPointeeType().getAddressSpace();
3151           }
3152           Ty = Context.getPointerType(
3153               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3154         }
3155         break;
3156       case 2:
3157         // The third argument to compare_exchange / GNU exchange is a
3158         // (pointer to a) desired value.
3159         Ty = ByValType;
3160         break;
3161       case 3:
3162         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3163         Ty = Context.BoolTy;
3164         break;
3165       }
3166     } else {
3167       // The order(s) and scope are always converted to int.
3168       Ty = Context.IntTy;
3169     }
3170 
3171     InitializedEntity Entity =
3172         InitializedEntity::InitializeParameter(Context, Ty, false);
3173     ExprResult Arg = TheCall->getArg(i);
3174     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3175     if (Arg.isInvalid())
3176       return true;
3177     TheCall->setArg(i, Arg.get());
3178   }
3179 
3180   // Permute the arguments into a 'consistent' order.
3181   SmallVector<Expr*, 5> SubExprs;
3182   SubExprs.push_back(Ptr);
3183   switch (Form) {
3184   case Init:
3185     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3186     SubExprs.push_back(TheCall->getArg(1)); // Val1
3187     break;
3188   case Load:
3189     SubExprs.push_back(TheCall->getArg(1)); // Order
3190     break;
3191   case LoadCopy:
3192   case Copy:
3193   case Arithmetic:
3194   case Xchg:
3195     SubExprs.push_back(TheCall->getArg(2)); // Order
3196     SubExprs.push_back(TheCall->getArg(1)); // Val1
3197     break;
3198   case GNUXchg:
3199     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3200     SubExprs.push_back(TheCall->getArg(3)); // Order
3201     SubExprs.push_back(TheCall->getArg(1)); // Val1
3202     SubExprs.push_back(TheCall->getArg(2)); // Val2
3203     break;
3204   case C11CmpXchg:
3205     SubExprs.push_back(TheCall->getArg(3)); // Order
3206     SubExprs.push_back(TheCall->getArg(1)); // Val1
3207     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3208     SubExprs.push_back(TheCall->getArg(2)); // Val2
3209     break;
3210   case GNUCmpXchg:
3211     SubExprs.push_back(TheCall->getArg(4)); // Order
3212     SubExprs.push_back(TheCall->getArg(1)); // Val1
3213     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3214     SubExprs.push_back(TheCall->getArg(2)); // Val2
3215     SubExprs.push_back(TheCall->getArg(3)); // Weak
3216     break;
3217   }
3218 
3219   if (SubExprs.size() >= 2 && Form != Init) {
3220     llvm::APSInt Result(32);
3221     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3222         !isValidOrderingForOp(Result.getSExtValue(), Op))
3223       Diag(SubExprs[1]->getLocStart(),
3224            diag::warn_atomic_op_has_invalid_memory_order)
3225           << SubExprs[1]->getSourceRange();
3226   }
3227 
3228   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3229     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3230     llvm::APSInt Result(32);
3231     if (Scope->isIntegerConstantExpr(Result, Context) &&
3232         !ScopeModel->isValid(Result.getZExtValue())) {
3233       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3234           << Scope->getSourceRange();
3235     }
3236     SubExprs.push_back(Scope);
3237   }
3238 
3239   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3240                                             SubExprs, ResultType, Op,
3241                                             TheCall->getRParenLoc());
3242 
3243   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3244        Op == AtomicExpr::AO__c11_atomic_store ||
3245        Op == AtomicExpr::AO__opencl_atomic_load ||
3246        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3247       Context.AtomicUsesUnsupportedLibcall(AE))
3248     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3249         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3250             Op == AtomicExpr::AO__opencl_atomic_load)
3251                 ? 0 : 1);
3252 
3253   return AE;
3254 }
3255 
3256 /// checkBuiltinArgument - Given a call to a builtin function, perform
3257 /// normal type-checking on the given argument, updating the call in
3258 /// place.  This is useful when a builtin function requires custom
3259 /// type-checking for some of its arguments but not necessarily all of
3260 /// them.
3261 ///
3262 /// Returns true on error.
3263 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3264   FunctionDecl *Fn = E->getDirectCallee();
3265   assert(Fn && "builtin call without direct callee!");
3266 
3267   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3268   InitializedEntity Entity =
3269     InitializedEntity::InitializeParameter(S.Context, Param);
3270 
3271   ExprResult Arg = E->getArg(0);
3272   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3273   if (Arg.isInvalid())
3274     return true;
3275 
3276   E->setArg(ArgIndex, Arg.get());
3277   return false;
3278 }
3279 
3280 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3281 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3282 /// type of its first argument.  The main ActOnCallExpr routines have already
3283 /// promoted the types of arguments because all of these calls are prototyped as
3284 /// void(...).
3285 ///
3286 /// This function goes through and does final semantic checking for these
3287 /// builtins,
3288 ExprResult
3289 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3290   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3291   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3292   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3293 
3294   // Ensure that we have at least one argument to do type inference from.
3295   if (TheCall->getNumArgs() < 1) {
3296     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3297       << 0 << 1 << TheCall->getNumArgs()
3298       << TheCall->getCallee()->getSourceRange();
3299     return ExprError();
3300   }
3301 
3302   // Inspect the first argument of the atomic builtin.  This should always be
3303   // a pointer type, whose element is an integral scalar or pointer type.
3304   // Because it is a pointer type, we don't have to worry about any implicit
3305   // casts here.
3306   // FIXME: We don't allow floating point scalars as input.
3307   Expr *FirstArg = TheCall->getArg(0);
3308   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3309   if (FirstArgResult.isInvalid())
3310     return ExprError();
3311   FirstArg = FirstArgResult.get();
3312   TheCall->setArg(0, FirstArg);
3313 
3314   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3315   if (!pointerType) {
3316     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3317       << FirstArg->getType() << FirstArg->getSourceRange();
3318     return ExprError();
3319   }
3320 
3321   QualType ValType = pointerType->getPointeeType();
3322   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3323       !ValType->isBlockPointerType()) {
3324     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3325       << FirstArg->getType() << FirstArg->getSourceRange();
3326     return ExprError();
3327   }
3328 
3329   switch (ValType.getObjCLifetime()) {
3330   case Qualifiers::OCL_None:
3331   case Qualifiers::OCL_ExplicitNone:
3332     // okay
3333     break;
3334 
3335   case Qualifiers::OCL_Weak:
3336   case Qualifiers::OCL_Strong:
3337   case Qualifiers::OCL_Autoreleasing:
3338     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3339       << ValType << FirstArg->getSourceRange();
3340     return ExprError();
3341   }
3342 
3343   // Strip any qualifiers off ValType.
3344   ValType = ValType.getUnqualifiedType();
3345 
3346   // The majority of builtins return a value, but a few have special return
3347   // types, so allow them to override appropriately below.
3348   QualType ResultType = ValType;
3349 
3350   // We need to figure out which concrete builtin this maps onto.  For example,
3351   // __sync_fetch_and_add with a 2 byte object turns into
3352   // __sync_fetch_and_add_2.
3353 #define BUILTIN_ROW(x) \
3354   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3355     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3356 
3357   static const unsigned BuiltinIndices[][5] = {
3358     BUILTIN_ROW(__sync_fetch_and_add),
3359     BUILTIN_ROW(__sync_fetch_and_sub),
3360     BUILTIN_ROW(__sync_fetch_and_or),
3361     BUILTIN_ROW(__sync_fetch_and_and),
3362     BUILTIN_ROW(__sync_fetch_and_xor),
3363     BUILTIN_ROW(__sync_fetch_and_nand),
3364 
3365     BUILTIN_ROW(__sync_add_and_fetch),
3366     BUILTIN_ROW(__sync_sub_and_fetch),
3367     BUILTIN_ROW(__sync_and_and_fetch),
3368     BUILTIN_ROW(__sync_or_and_fetch),
3369     BUILTIN_ROW(__sync_xor_and_fetch),
3370     BUILTIN_ROW(__sync_nand_and_fetch),
3371 
3372     BUILTIN_ROW(__sync_val_compare_and_swap),
3373     BUILTIN_ROW(__sync_bool_compare_and_swap),
3374     BUILTIN_ROW(__sync_lock_test_and_set),
3375     BUILTIN_ROW(__sync_lock_release),
3376     BUILTIN_ROW(__sync_swap)
3377   };
3378 #undef BUILTIN_ROW
3379 
3380   // Determine the index of the size.
3381   unsigned SizeIndex;
3382   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3383   case 1: SizeIndex = 0; break;
3384   case 2: SizeIndex = 1; break;
3385   case 4: SizeIndex = 2; break;
3386   case 8: SizeIndex = 3; break;
3387   case 16: SizeIndex = 4; break;
3388   default:
3389     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3390       << FirstArg->getType() << FirstArg->getSourceRange();
3391     return ExprError();
3392   }
3393 
3394   // Each of these builtins has one pointer argument, followed by some number of
3395   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3396   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3397   // as the number of fixed args.
3398   unsigned BuiltinID = FDecl->getBuiltinID();
3399   unsigned BuiltinIndex, NumFixed = 1;
3400   bool WarnAboutSemanticsChange = false;
3401   switch (BuiltinID) {
3402   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3403   case Builtin::BI__sync_fetch_and_add:
3404   case Builtin::BI__sync_fetch_and_add_1:
3405   case Builtin::BI__sync_fetch_and_add_2:
3406   case Builtin::BI__sync_fetch_and_add_4:
3407   case Builtin::BI__sync_fetch_and_add_8:
3408   case Builtin::BI__sync_fetch_and_add_16:
3409     BuiltinIndex = 0;
3410     break;
3411 
3412   case Builtin::BI__sync_fetch_and_sub:
3413   case Builtin::BI__sync_fetch_and_sub_1:
3414   case Builtin::BI__sync_fetch_and_sub_2:
3415   case Builtin::BI__sync_fetch_and_sub_4:
3416   case Builtin::BI__sync_fetch_and_sub_8:
3417   case Builtin::BI__sync_fetch_and_sub_16:
3418     BuiltinIndex = 1;
3419     break;
3420 
3421   case Builtin::BI__sync_fetch_and_or:
3422   case Builtin::BI__sync_fetch_and_or_1:
3423   case Builtin::BI__sync_fetch_and_or_2:
3424   case Builtin::BI__sync_fetch_and_or_4:
3425   case Builtin::BI__sync_fetch_and_or_8:
3426   case Builtin::BI__sync_fetch_and_or_16:
3427     BuiltinIndex = 2;
3428     break;
3429 
3430   case Builtin::BI__sync_fetch_and_and:
3431   case Builtin::BI__sync_fetch_and_and_1:
3432   case Builtin::BI__sync_fetch_and_and_2:
3433   case Builtin::BI__sync_fetch_and_and_4:
3434   case Builtin::BI__sync_fetch_and_and_8:
3435   case Builtin::BI__sync_fetch_and_and_16:
3436     BuiltinIndex = 3;
3437     break;
3438 
3439   case Builtin::BI__sync_fetch_and_xor:
3440   case Builtin::BI__sync_fetch_and_xor_1:
3441   case Builtin::BI__sync_fetch_and_xor_2:
3442   case Builtin::BI__sync_fetch_and_xor_4:
3443   case Builtin::BI__sync_fetch_and_xor_8:
3444   case Builtin::BI__sync_fetch_and_xor_16:
3445     BuiltinIndex = 4;
3446     break;
3447 
3448   case Builtin::BI__sync_fetch_and_nand:
3449   case Builtin::BI__sync_fetch_and_nand_1:
3450   case Builtin::BI__sync_fetch_and_nand_2:
3451   case Builtin::BI__sync_fetch_and_nand_4:
3452   case Builtin::BI__sync_fetch_and_nand_8:
3453   case Builtin::BI__sync_fetch_and_nand_16:
3454     BuiltinIndex = 5;
3455     WarnAboutSemanticsChange = true;
3456     break;
3457 
3458   case Builtin::BI__sync_add_and_fetch:
3459   case Builtin::BI__sync_add_and_fetch_1:
3460   case Builtin::BI__sync_add_and_fetch_2:
3461   case Builtin::BI__sync_add_and_fetch_4:
3462   case Builtin::BI__sync_add_and_fetch_8:
3463   case Builtin::BI__sync_add_and_fetch_16:
3464     BuiltinIndex = 6;
3465     break;
3466 
3467   case Builtin::BI__sync_sub_and_fetch:
3468   case Builtin::BI__sync_sub_and_fetch_1:
3469   case Builtin::BI__sync_sub_and_fetch_2:
3470   case Builtin::BI__sync_sub_and_fetch_4:
3471   case Builtin::BI__sync_sub_and_fetch_8:
3472   case Builtin::BI__sync_sub_and_fetch_16:
3473     BuiltinIndex = 7;
3474     break;
3475 
3476   case Builtin::BI__sync_and_and_fetch:
3477   case Builtin::BI__sync_and_and_fetch_1:
3478   case Builtin::BI__sync_and_and_fetch_2:
3479   case Builtin::BI__sync_and_and_fetch_4:
3480   case Builtin::BI__sync_and_and_fetch_8:
3481   case Builtin::BI__sync_and_and_fetch_16:
3482     BuiltinIndex = 8;
3483     break;
3484 
3485   case Builtin::BI__sync_or_and_fetch:
3486   case Builtin::BI__sync_or_and_fetch_1:
3487   case Builtin::BI__sync_or_and_fetch_2:
3488   case Builtin::BI__sync_or_and_fetch_4:
3489   case Builtin::BI__sync_or_and_fetch_8:
3490   case Builtin::BI__sync_or_and_fetch_16:
3491     BuiltinIndex = 9;
3492     break;
3493 
3494   case Builtin::BI__sync_xor_and_fetch:
3495   case Builtin::BI__sync_xor_and_fetch_1:
3496   case Builtin::BI__sync_xor_and_fetch_2:
3497   case Builtin::BI__sync_xor_and_fetch_4:
3498   case Builtin::BI__sync_xor_and_fetch_8:
3499   case Builtin::BI__sync_xor_and_fetch_16:
3500     BuiltinIndex = 10;
3501     break;
3502 
3503   case Builtin::BI__sync_nand_and_fetch:
3504   case Builtin::BI__sync_nand_and_fetch_1:
3505   case Builtin::BI__sync_nand_and_fetch_2:
3506   case Builtin::BI__sync_nand_and_fetch_4:
3507   case Builtin::BI__sync_nand_and_fetch_8:
3508   case Builtin::BI__sync_nand_and_fetch_16:
3509     BuiltinIndex = 11;
3510     WarnAboutSemanticsChange = true;
3511     break;
3512 
3513   case Builtin::BI__sync_val_compare_and_swap:
3514   case Builtin::BI__sync_val_compare_and_swap_1:
3515   case Builtin::BI__sync_val_compare_and_swap_2:
3516   case Builtin::BI__sync_val_compare_and_swap_4:
3517   case Builtin::BI__sync_val_compare_and_swap_8:
3518   case Builtin::BI__sync_val_compare_and_swap_16:
3519     BuiltinIndex = 12;
3520     NumFixed = 2;
3521     break;
3522 
3523   case Builtin::BI__sync_bool_compare_and_swap:
3524   case Builtin::BI__sync_bool_compare_and_swap_1:
3525   case Builtin::BI__sync_bool_compare_and_swap_2:
3526   case Builtin::BI__sync_bool_compare_and_swap_4:
3527   case Builtin::BI__sync_bool_compare_and_swap_8:
3528   case Builtin::BI__sync_bool_compare_and_swap_16:
3529     BuiltinIndex = 13;
3530     NumFixed = 2;
3531     ResultType = Context.BoolTy;
3532     break;
3533 
3534   case Builtin::BI__sync_lock_test_and_set:
3535   case Builtin::BI__sync_lock_test_and_set_1:
3536   case Builtin::BI__sync_lock_test_and_set_2:
3537   case Builtin::BI__sync_lock_test_and_set_4:
3538   case Builtin::BI__sync_lock_test_and_set_8:
3539   case Builtin::BI__sync_lock_test_and_set_16:
3540     BuiltinIndex = 14;
3541     break;
3542 
3543   case Builtin::BI__sync_lock_release:
3544   case Builtin::BI__sync_lock_release_1:
3545   case Builtin::BI__sync_lock_release_2:
3546   case Builtin::BI__sync_lock_release_4:
3547   case Builtin::BI__sync_lock_release_8:
3548   case Builtin::BI__sync_lock_release_16:
3549     BuiltinIndex = 15;
3550     NumFixed = 0;
3551     ResultType = Context.VoidTy;
3552     break;
3553 
3554   case Builtin::BI__sync_swap:
3555   case Builtin::BI__sync_swap_1:
3556   case Builtin::BI__sync_swap_2:
3557   case Builtin::BI__sync_swap_4:
3558   case Builtin::BI__sync_swap_8:
3559   case Builtin::BI__sync_swap_16:
3560     BuiltinIndex = 16;
3561     break;
3562   }
3563 
3564   // Now that we know how many fixed arguments we expect, first check that we
3565   // have at least that many.
3566   if (TheCall->getNumArgs() < 1+NumFixed) {
3567     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3568       << 0 << 1+NumFixed << TheCall->getNumArgs()
3569       << TheCall->getCallee()->getSourceRange();
3570     return ExprError();
3571   }
3572 
3573   if (WarnAboutSemanticsChange) {
3574     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3575       << TheCall->getCallee()->getSourceRange();
3576   }
3577 
3578   // Get the decl for the concrete builtin from this, we can tell what the
3579   // concrete integer type we should convert to is.
3580   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3581   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3582   FunctionDecl *NewBuiltinDecl;
3583   if (NewBuiltinID == BuiltinID)
3584     NewBuiltinDecl = FDecl;
3585   else {
3586     // Perform builtin lookup to avoid redeclaring it.
3587     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3588     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3589     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3590     assert(Res.getFoundDecl());
3591     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3592     if (!NewBuiltinDecl)
3593       return ExprError();
3594   }
3595 
3596   // The first argument --- the pointer --- has a fixed type; we
3597   // deduce the types of the rest of the arguments accordingly.  Walk
3598   // the remaining arguments, converting them to the deduced value type.
3599   for (unsigned i = 0; i != NumFixed; ++i) {
3600     ExprResult Arg = TheCall->getArg(i+1);
3601 
3602     // GCC does an implicit conversion to the pointer or integer ValType.  This
3603     // can fail in some cases (1i -> int**), check for this error case now.
3604     // Initialize the argument.
3605     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3606                                                    ValType, /*consume*/ false);
3607     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3608     if (Arg.isInvalid())
3609       return ExprError();
3610 
3611     // Okay, we have something that *can* be converted to the right type.  Check
3612     // to see if there is a potentially weird extension going on here.  This can
3613     // happen when you do an atomic operation on something like an char* and
3614     // pass in 42.  The 42 gets converted to char.  This is even more strange
3615     // for things like 45.123 -> char, etc.
3616     // FIXME: Do this check.
3617     TheCall->setArg(i+1, Arg.get());
3618   }
3619 
3620   ASTContext& Context = this->getASTContext();
3621 
3622   // Create a new DeclRefExpr to refer to the new decl.
3623   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3624       Context,
3625       DRE->getQualifierLoc(),
3626       SourceLocation(),
3627       NewBuiltinDecl,
3628       /*enclosing*/ false,
3629       DRE->getLocation(),
3630       Context.BuiltinFnTy,
3631       DRE->getValueKind());
3632 
3633   // Set the callee in the CallExpr.
3634   // FIXME: This loses syntactic information.
3635   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3636   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3637                                               CK_BuiltinFnToFnPtr);
3638   TheCall->setCallee(PromotedCall.get());
3639 
3640   // Change the result type of the call to match the original value type. This
3641   // is arbitrary, but the codegen for these builtins ins design to handle it
3642   // gracefully.
3643   TheCall->setType(ResultType);
3644 
3645   return TheCallResult;
3646 }
3647 
3648 /// SemaBuiltinNontemporalOverloaded - We have a call to
3649 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3650 /// overloaded function based on the pointer type of its last argument.
3651 ///
3652 /// This function goes through and does final semantic checking for these
3653 /// builtins.
3654 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3655   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3656   DeclRefExpr *DRE =
3657       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3658   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3659   unsigned BuiltinID = FDecl->getBuiltinID();
3660   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3661           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3662          "Unexpected nontemporal load/store builtin!");
3663   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3664   unsigned numArgs = isStore ? 2 : 1;
3665 
3666   // Ensure that we have the proper number of arguments.
3667   if (checkArgCount(*this, TheCall, numArgs))
3668     return ExprError();
3669 
3670   // Inspect the last argument of the nontemporal builtin.  This should always
3671   // be a pointer type, from which we imply the type of the memory access.
3672   // Because it is a pointer type, we don't have to worry about any implicit
3673   // casts here.
3674   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3675   ExprResult PointerArgResult =
3676       DefaultFunctionArrayLvalueConversion(PointerArg);
3677 
3678   if (PointerArgResult.isInvalid())
3679     return ExprError();
3680   PointerArg = PointerArgResult.get();
3681   TheCall->setArg(numArgs - 1, PointerArg);
3682 
3683   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3684   if (!pointerType) {
3685     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3686         << PointerArg->getType() << PointerArg->getSourceRange();
3687     return ExprError();
3688   }
3689 
3690   QualType ValType = pointerType->getPointeeType();
3691 
3692   // Strip any qualifiers off ValType.
3693   ValType = ValType.getUnqualifiedType();
3694   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3695       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3696       !ValType->isVectorType()) {
3697     Diag(DRE->getLocStart(),
3698          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3699         << PointerArg->getType() << PointerArg->getSourceRange();
3700     return ExprError();
3701   }
3702 
3703   if (!isStore) {
3704     TheCall->setType(ValType);
3705     return TheCallResult;
3706   }
3707 
3708   ExprResult ValArg = TheCall->getArg(0);
3709   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3710       Context, ValType, /*consume*/ false);
3711   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3712   if (ValArg.isInvalid())
3713     return ExprError();
3714 
3715   TheCall->setArg(0, ValArg.get());
3716   TheCall->setType(Context.VoidTy);
3717   return TheCallResult;
3718 }
3719 
3720 /// CheckObjCString - Checks that the argument to the builtin
3721 /// CFString constructor is correct
3722 /// Note: It might also make sense to do the UTF-16 conversion here (would
3723 /// simplify the backend).
3724 bool Sema::CheckObjCString(Expr *Arg) {
3725   Arg = Arg->IgnoreParenCasts();
3726   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3727 
3728   if (!Literal || !Literal->isAscii()) {
3729     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3730       << Arg->getSourceRange();
3731     return true;
3732   }
3733 
3734   if (Literal->containsNonAsciiOrNull()) {
3735     StringRef String = Literal->getString();
3736     unsigned NumBytes = String.size();
3737     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3738     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3739     llvm::UTF16 *ToPtr = &ToBuf[0];
3740 
3741     llvm::ConversionResult Result =
3742         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3743                                  ToPtr + NumBytes, llvm::strictConversion);
3744     // Check for conversion failure.
3745     if (Result != llvm::conversionOK)
3746       Diag(Arg->getLocStart(),
3747            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3748   }
3749   return false;
3750 }
3751 
3752 /// CheckObjCString - Checks that the format string argument to the os_log()
3753 /// and os_trace() functions is correct, and converts it to const char *.
3754 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3755   Arg = Arg->IgnoreParenCasts();
3756   auto *Literal = dyn_cast<StringLiteral>(Arg);
3757   if (!Literal) {
3758     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3759       Literal = ObjcLiteral->getString();
3760     }
3761   }
3762 
3763   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3764     return ExprError(
3765         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3766         << Arg->getSourceRange());
3767   }
3768 
3769   ExprResult Result(Literal);
3770   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3771   InitializedEntity Entity =
3772       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3773   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3774   return Result;
3775 }
3776 
3777 /// Check that the user is calling the appropriate va_start builtin for the
3778 /// target and calling convention.
3779 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3780   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3781   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3782   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3783   bool IsWindows = TT.isOSWindows();
3784   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3785   if (IsX64 || IsAArch64) {
3786     clang::CallingConv CC = CC_C;
3787     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3788       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3789     if (IsMSVAStart) {
3790       // Don't allow this in System V ABI functions.
3791       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3792         return S.Diag(Fn->getLocStart(),
3793                       diag::err_ms_va_start_used_in_sysv_function);
3794     } else {
3795       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3796       // On x64 Windows, don't allow this in System V ABI functions.
3797       // (Yes, that means there's no corresponding way to support variadic
3798       // System V ABI functions on Windows.)
3799       if ((IsWindows && CC == CC_X86_64SysV) ||
3800           (!IsWindows && CC == CC_Win64))
3801         return S.Diag(Fn->getLocStart(),
3802                       diag::err_va_start_used_in_wrong_abi_function)
3803                << !IsWindows;
3804     }
3805     return false;
3806   }
3807 
3808   if (IsMSVAStart)
3809     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3810   return false;
3811 }
3812 
3813 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3814                                              ParmVarDecl **LastParam = nullptr) {
3815   // Determine whether the current function, block, or obj-c method is variadic
3816   // and get its parameter list.
3817   bool IsVariadic = false;
3818   ArrayRef<ParmVarDecl *> Params;
3819   DeclContext *Caller = S.CurContext;
3820   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3821     IsVariadic = Block->isVariadic();
3822     Params = Block->parameters();
3823   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3824     IsVariadic = FD->isVariadic();
3825     Params = FD->parameters();
3826   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3827     IsVariadic = MD->isVariadic();
3828     // FIXME: This isn't correct for methods (results in bogus warning).
3829     Params = MD->parameters();
3830   } else if (isa<CapturedDecl>(Caller)) {
3831     // We don't support va_start in a CapturedDecl.
3832     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3833     return true;
3834   } else {
3835     // This must be some other declcontext that parses exprs.
3836     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3837     return true;
3838   }
3839 
3840   if (!IsVariadic) {
3841     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3842     return true;
3843   }
3844 
3845   if (LastParam)
3846     *LastParam = Params.empty() ? nullptr : Params.back();
3847 
3848   return false;
3849 }
3850 
3851 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3852 /// for validity.  Emit an error and return true on failure; return false
3853 /// on success.
3854 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3855   Expr *Fn = TheCall->getCallee();
3856 
3857   if (checkVAStartABI(*this, BuiltinID, Fn))
3858     return true;
3859 
3860   if (TheCall->getNumArgs() > 2) {
3861     Diag(TheCall->getArg(2)->getLocStart(),
3862          diag::err_typecheck_call_too_many_args)
3863       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3864       << Fn->getSourceRange()
3865       << SourceRange(TheCall->getArg(2)->getLocStart(),
3866                      (*(TheCall->arg_end()-1))->getLocEnd());
3867     return true;
3868   }
3869 
3870   if (TheCall->getNumArgs() < 2) {
3871     return Diag(TheCall->getLocEnd(),
3872       diag::err_typecheck_call_too_few_args_at_least)
3873       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3874   }
3875 
3876   // Type-check the first argument normally.
3877   if (checkBuiltinArgument(*this, TheCall, 0))
3878     return true;
3879 
3880   // Check that the current function is variadic, and get its last parameter.
3881   ParmVarDecl *LastParam;
3882   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3883     return true;
3884 
3885   // Verify that the second argument to the builtin is the last argument of the
3886   // current function or method.
3887   bool SecondArgIsLastNamedArgument = false;
3888   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3889 
3890   // These are valid if SecondArgIsLastNamedArgument is false after the next
3891   // block.
3892   QualType Type;
3893   SourceLocation ParamLoc;
3894   bool IsCRegister = false;
3895 
3896   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3897     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3898       SecondArgIsLastNamedArgument = PV == LastParam;
3899 
3900       Type = PV->getType();
3901       ParamLoc = PV->getLocation();
3902       IsCRegister =
3903           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3904     }
3905   }
3906 
3907   if (!SecondArgIsLastNamedArgument)
3908     Diag(TheCall->getArg(1)->getLocStart(),
3909          diag::warn_second_arg_of_va_start_not_last_named_param);
3910   else if (IsCRegister || Type->isReferenceType() ||
3911            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3912              // Promotable integers are UB, but enumerations need a bit of
3913              // extra checking to see what their promotable type actually is.
3914              if (!Type->isPromotableIntegerType())
3915                return false;
3916              if (!Type->isEnumeralType())
3917                return true;
3918              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3919              return !(ED &&
3920                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3921            }()) {
3922     unsigned Reason = 0;
3923     if (Type->isReferenceType())  Reason = 1;
3924     else if (IsCRegister)         Reason = 2;
3925     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3926     Diag(ParamLoc, diag::note_parameter_type) << Type;
3927   }
3928 
3929   TheCall->setType(Context.VoidTy);
3930   return false;
3931 }
3932 
3933 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3934   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3935   //                 const char *named_addr);
3936 
3937   Expr *Func = Call->getCallee();
3938 
3939   if (Call->getNumArgs() < 3)
3940     return Diag(Call->getLocEnd(),
3941                 diag::err_typecheck_call_too_few_args_at_least)
3942            << 0 /*function call*/ << 3 << Call->getNumArgs();
3943 
3944   // Type-check the first argument normally.
3945   if (checkBuiltinArgument(*this, Call, 0))
3946     return true;
3947 
3948   // Check that the current function is variadic.
3949   if (checkVAStartIsInVariadicFunction(*this, Func))
3950     return true;
3951 
3952   // __va_start on Windows does not validate the parameter qualifiers
3953 
3954   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3955   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3956 
3957   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3958   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3959 
3960   const QualType &ConstCharPtrTy =
3961       Context.getPointerType(Context.CharTy.withConst());
3962   if (!Arg1Ty->isPointerType() ||
3963       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3964     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3965         << Arg1->getType() << ConstCharPtrTy
3966         << 1 /* different class */
3967         << 0 /* qualifier difference */
3968         << 3 /* parameter mismatch */
3969         << 2 << Arg1->getType() << ConstCharPtrTy;
3970 
3971   const QualType SizeTy = Context.getSizeType();
3972   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3973     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3974         << Arg2->getType() << SizeTy
3975         << 1 /* different class */
3976         << 0 /* qualifier difference */
3977         << 3 /* parameter mismatch */
3978         << 3 << Arg2->getType() << SizeTy;
3979 
3980   return false;
3981 }
3982 
3983 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3984 /// friends.  This is declared to take (...), so we have to check everything.
3985 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3986   if (TheCall->getNumArgs() < 2)
3987     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3988       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3989   if (TheCall->getNumArgs() > 2)
3990     return Diag(TheCall->getArg(2)->getLocStart(),
3991                 diag::err_typecheck_call_too_many_args)
3992       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3993       << SourceRange(TheCall->getArg(2)->getLocStart(),
3994                      (*(TheCall->arg_end()-1))->getLocEnd());
3995 
3996   ExprResult OrigArg0 = TheCall->getArg(0);
3997   ExprResult OrigArg1 = TheCall->getArg(1);
3998 
3999   // Do standard promotions between the two arguments, returning their common
4000   // type.
4001   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
4002   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
4003     return true;
4004 
4005   // Make sure any conversions are pushed back into the call; this is
4006   // type safe since unordered compare builtins are declared as "_Bool
4007   // foo(...)".
4008   TheCall->setArg(0, OrigArg0.get());
4009   TheCall->setArg(1, OrigArg1.get());
4010 
4011   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4012     return false;
4013 
4014   // If the common type isn't a real floating type, then the arguments were
4015   // invalid for this operation.
4016   if (Res.isNull() || !Res->isRealFloatingType())
4017     return Diag(OrigArg0.get()->getLocStart(),
4018                 diag::err_typecheck_call_invalid_ordered_compare)
4019       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4020       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4021 
4022   return false;
4023 }
4024 
4025 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4026 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4027 /// to check everything. We expect the last argument to be a floating point
4028 /// value.
4029 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4030   if (TheCall->getNumArgs() < NumArgs)
4031     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4032       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4033   if (TheCall->getNumArgs() > NumArgs)
4034     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4035                 diag::err_typecheck_call_too_many_args)
4036       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4037       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4038                      (*(TheCall->arg_end()-1))->getLocEnd());
4039 
4040   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4041 
4042   if (OrigArg->isTypeDependent())
4043     return false;
4044 
4045   // This operation requires a non-_Complex floating-point number.
4046   if (!OrigArg->getType()->isRealFloatingType())
4047     return Diag(OrigArg->getLocStart(),
4048                 diag::err_typecheck_call_invalid_unary_fp)
4049       << OrigArg->getType() << OrigArg->getSourceRange();
4050 
4051   // If this is an implicit conversion from float -> float or double, remove it.
4052   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4053     // Only remove standard FloatCasts, leaving other casts inplace
4054     if (Cast->getCastKind() == CK_FloatingCast) {
4055       Expr *CastArg = Cast->getSubExpr();
4056       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4057           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4058                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4059                "promotion from float to either float or double is the only expected cast here");
4060         Cast->setSubExpr(nullptr);
4061         TheCall->setArg(NumArgs-1, CastArg);
4062       }
4063     }
4064   }
4065 
4066   return false;
4067 }
4068 
4069 // Customized Sema Checking for VSX builtins that have the following signature:
4070 // vector [...] builtinName(vector [...], vector [...], const int);
4071 // Which takes the same type of vectors (any legal vector type) for the first
4072 // two arguments and takes compile time constant for the third argument.
4073 // Example builtins are :
4074 // vector double vec_xxpermdi(vector double, vector double, int);
4075 // vector short vec_xxsldwi(vector short, vector short, int);
4076 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4077   unsigned ExpectedNumArgs = 3;
4078   if (TheCall->getNumArgs() < ExpectedNumArgs)
4079     return Diag(TheCall->getLocEnd(),
4080                 diag::err_typecheck_call_too_few_args_at_least)
4081            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4082            << TheCall->getSourceRange();
4083 
4084   if (TheCall->getNumArgs() > ExpectedNumArgs)
4085     return Diag(TheCall->getLocEnd(),
4086                 diag::err_typecheck_call_too_many_args_at_most)
4087            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4088            << TheCall->getSourceRange();
4089 
4090   // Check the third argument is a compile time constant
4091   llvm::APSInt Value;
4092   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4093     return Diag(TheCall->getLocStart(),
4094                 diag::err_vsx_builtin_nonconstant_argument)
4095            << 3 /* argument index */ << TheCall->getDirectCallee()
4096            << SourceRange(TheCall->getArg(2)->getLocStart(),
4097                           TheCall->getArg(2)->getLocEnd());
4098 
4099   QualType Arg1Ty = TheCall->getArg(0)->getType();
4100   QualType Arg2Ty = TheCall->getArg(1)->getType();
4101 
4102   // Check the type of argument 1 and argument 2 are vectors.
4103   SourceLocation BuiltinLoc = TheCall->getLocStart();
4104   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4105       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4106     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4107            << TheCall->getDirectCallee()
4108            << SourceRange(TheCall->getArg(0)->getLocStart(),
4109                           TheCall->getArg(1)->getLocEnd());
4110   }
4111 
4112   // Check the first two arguments are the same type.
4113   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4114     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4115            << TheCall->getDirectCallee()
4116            << SourceRange(TheCall->getArg(0)->getLocStart(),
4117                           TheCall->getArg(1)->getLocEnd());
4118   }
4119 
4120   // When default clang type checking is turned off and the customized type
4121   // checking is used, the returning type of the function must be explicitly
4122   // set. Otherwise it is _Bool by default.
4123   TheCall->setType(Arg1Ty);
4124 
4125   return false;
4126 }
4127 
4128 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4129 // This is declared to take (...), so we have to check everything.
4130 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4131   if (TheCall->getNumArgs() < 2)
4132     return ExprError(Diag(TheCall->getLocEnd(),
4133                           diag::err_typecheck_call_too_few_args_at_least)
4134                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4135                      << TheCall->getSourceRange());
4136 
4137   // Determine which of the following types of shufflevector we're checking:
4138   // 1) unary, vector mask: (lhs, mask)
4139   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4140   QualType resType = TheCall->getArg(0)->getType();
4141   unsigned numElements = 0;
4142 
4143   if (!TheCall->getArg(0)->isTypeDependent() &&
4144       !TheCall->getArg(1)->isTypeDependent()) {
4145     QualType LHSType = TheCall->getArg(0)->getType();
4146     QualType RHSType = TheCall->getArg(1)->getType();
4147 
4148     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4149       return ExprError(Diag(TheCall->getLocStart(),
4150                             diag::err_vec_builtin_non_vector)
4151                        << TheCall->getDirectCallee()
4152                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4153                                       TheCall->getArg(1)->getLocEnd()));
4154 
4155     numElements = LHSType->getAs<VectorType>()->getNumElements();
4156     unsigned numResElements = TheCall->getNumArgs() - 2;
4157 
4158     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4159     // with mask.  If so, verify that RHS is an integer vector type with the
4160     // same number of elts as lhs.
4161     if (TheCall->getNumArgs() == 2) {
4162       if (!RHSType->hasIntegerRepresentation() ||
4163           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4164         return ExprError(Diag(TheCall->getLocStart(),
4165                               diag::err_vec_builtin_incompatible_vector)
4166                          << TheCall->getDirectCallee()
4167                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4168                                         TheCall->getArg(1)->getLocEnd()));
4169     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4170       return ExprError(Diag(TheCall->getLocStart(),
4171                             diag::err_vec_builtin_incompatible_vector)
4172                        << TheCall->getDirectCallee()
4173                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4174                                       TheCall->getArg(1)->getLocEnd()));
4175     } else if (numElements != numResElements) {
4176       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4177       resType = Context.getVectorType(eltType, numResElements,
4178                                       VectorType::GenericVector);
4179     }
4180   }
4181 
4182   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4183     if (TheCall->getArg(i)->isTypeDependent() ||
4184         TheCall->getArg(i)->isValueDependent())
4185       continue;
4186 
4187     llvm::APSInt Result(32);
4188     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4189       return ExprError(Diag(TheCall->getLocStart(),
4190                             diag::err_shufflevector_nonconstant_argument)
4191                        << TheCall->getArg(i)->getSourceRange());
4192 
4193     // Allow -1 which will be translated to undef in the IR.
4194     if (Result.isSigned() && Result.isAllOnesValue())
4195       continue;
4196 
4197     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4198       return ExprError(Diag(TheCall->getLocStart(),
4199                             diag::err_shufflevector_argument_too_large)
4200                        << TheCall->getArg(i)->getSourceRange());
4201   }
4202 
4203   SmallVector<Expr*, 32> exprs;
4204 
4205   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4206     exprs.push_back(TheCall->getArg(i));
4207     TheCall->setArg(i, nullptr);
4208   }
4209 
4210   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4211                                          TheCall->getCallee()->getLocStart(),
4212                                          TheCall->getRParenLoc());
4213 }
4214 
4215 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4216 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4217                                        SourceLocation BuiltinLoc,
4218                                        SourceLocation RParenLoc) {
4219   ExprValueKind VK = VK_RValue;
4220   ExprObjectKind OK = OK_Ordinary;
4221   QualType DstTy = TInfo->getType();
4222   QualType SrcTy = E->getType();
4223 
4224   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4225     return ExprError(Diag(BuiltinLoc,
4226                           diag::err_convertvector_non_vector)
4227                      << E->getSourceRange());
4228   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4229     return ExprError(Diag(BuiltinLoc,
4230                           diag::err_convertvector_non_vector_type));
4231 
4232   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4233     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4234     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4235     if (SrcElts != DstElts)
4236       return ExprError(Diag(BuiltinLoc,
4237                             diag::err_convertvector_incompatible_vector)
4238                        << E->getSourceRange());
4239   }
4240 
4241   return new (Context)
4242       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4243 }
4244 
4245 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4246 // This is declared to take (const void*, ...) and can take two
4247 // optional constant int args.
4248 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4249   unsigned NumArgs = TheCall->getNumArgs();
4250 
4251   if (NumArgs > 3)
4252     return Diag(TheCall->getLocEnd(),
4253              diag::err_typecheck_call_too_many_args_at_most)
4254              << 0 /*function call*/ << 3 << NumArgs
4255              << TheCall->getSourceRange();
4256 
4257   // Argument 0 is checked for us and the remaining arguments must be
4258   // constant integers.
4259   for (unsigned i = 1; i != NumArgs; ++i)
4260     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4261       return true;
4262 
4263   return false;
4264 }
4265 
4266 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4267 // __assume does not evaluate its arguments, and should warn if its argument
4268 // has side effects.
4269 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4270   Expr *Arg = TheCall->getArg(0);
4271   if (Arg->isInstantiationDependent()) return false;
4272 
4273   if (Arg->HasSideEffects(Context))
4274     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4275       << Arg->getSourceRange()
4276       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4277 
4278   return false;
4279 }
4280 
4281 /// Handle __builtin_alloca_with_align. This is declared
4282 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4283 /// than 8.
4284 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4285   // The alignment must be a constant integer.
4286   Expr *Arg = TheCall->getArg(1);
4287 
4288   // We can't check the value of a dependent argument.
4289   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4290     if (const auto *UE =
4291             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4292       if (UE->getKind() == UETT_AlignOf)
4293         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4294           << Arg->getSourceRange();
4295 
4296     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4297 
4298     if (!Result.isPowerOf2())
4299       return Diag(TheCall->getLocStart(),
4300                   diag::err_alignment_not_power_of_two)
4301            << Arg->getSourceRange();
4302 
4303     if (Result < Context.getCharWidth())
4304       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4305            << (unsigned)Context.getCharWidth()
4306            << Arg->getSourceRange();
4307 
4308     if (Result > INT32_MAX)
4309       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4310            << INT32_MAX
4311            << Arg->getSourceRange();
4312   }
4313 
4314   return false;
4315 }
4316 
4317 /// Handle __builtin_assume_aligned. This is declared
4318 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4319 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4320   unsigned NumArgs = TheCall->getNumArgs();
4321 
4322   if (NumArgs > 3)
4323     return Diag(TheCall->getLocEnd(),
4324              diag::err_typecheck_call_too_many_args_at_most)
4325              << 0 /*function call*/ << 3 << NumArgs
4326              << TheCall->getSourceRange();
4327 
4328   // The alignment must be a constant integer.
4329   Expr *Arg = TheCall->getArg(1);
4330 
4331   // We can't check the value of a dependent argument.
4332   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4333     llvm::APSInt Result;
4334     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4335       return true;
4336 
4337     if (!Result.isPowerOf2())
4338       return Diag(TheCall->getLocStart(),
4339                   diag::err_alignment_not_power_of_two)
4340            << Arg->getSourceRange();
4341   }
4342 
4343   if (NumArgs > 2) {
4344     ExprResult Arg(TheCall->getArg(2));
4345     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4346       Context.getSizeType(), false);
4347     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4348     if (Arg.isInvalid()) return true;
4349     TheCall->setArg(2, Arg.get());
4350   }
4351 
4352   return false;
4353 }
4354 
4355 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4356   unsigned BuiltinID =
4357       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4358   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4359 
4360   unsigned NumArgs = TheCall->getNumArgs();
4361   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4362   if (NumArgs < NumRequiredArgs) {
4363     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4364            << 0 /* function call */ << NumRequiredArgs << NumArgs
4365            << TheCall->getSourceRange();
4366   }
4367   if (NumArgs >= NumRequiredArgs + 0x100) {
4368     return Diag(TheCall->getLocEnd(),
4369                 diag::err_typecheck_call_too_many_args_at_most)
4370            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4371            << TheCall->getSourceRange();
4372   }
4373   unsigned i = 0;
4374 
4375   // For formatting call, check buffer arg.
4376   if (!IsSizeCall) {
4377     ExprResult Arg(TheCall->getArg(i));
4378     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4379         Context, Context.VoidPtrTy, false);
4380     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4381     if (Arg.isInvalid())
4382       return true;
4383     TheCall->setArg(i, Arg.get());
4384     i++;
4385   }
4386 
4387   // Check string literal arg.
4388   unsigned FormatIdx = i;
4389   {
4390     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4391     if (Arg.isInvalid())
4392       return true;
4393     TheCall->setArg(i, Arg.get());
4394     i++;
4395   }
4396 
4397   // Make sure variadic args are scalar.
4398   unsigned FirstDataArg = i;
4399   while (i < NumArgs) {
4400     ExprResult Arg = DefaultVariadicArgumentPromotion(
4401         TheCall->getArg(i), VariadicFunction, nullptr);
4402     if (Arg.isInvalid())
4403       return true;
4404     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4405     if (ArgSize.getQuantity() >= 0x100) {
4406       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4407              << i << (int)ArgSize.getQuantity() << 0xff
4408              << TheCall->getSourceRange();
4409     }
4410     TheCall->setArg(i, Arg.get());
4411     i++;
4412   }
4413 
4414   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4415   // call to avoid duplicate diagnostics.
4416   if (!IsSizeCall) {
4417     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4418     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4419     bool Success = CheckFormatArguments(
4420         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4421         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4422         CheckedVarArgs);
4423     if (!Success)
4424       return true;
4425   }
4426 
4427   if (IsSizeCall) {
4428     TheCall->setType(Context.getSizeType());
4429   } else {
4430     TheCall->setType(Context.VoidPtrTy);
4431   }
4432   return false;
4433 }
4434 
4435 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4436 /// TheCall is a constant expression.
4437 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4438                                   llvm::APSInt &Result) {
4439   Expr *Arg = TheCall->getArg(ArgNum);
4440   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4441   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4442 
4443   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4444 
4445   if (!Arg->isIntegerConstantExpr(Result, Context))
4446     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4447                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4448 
4449   return false;
4450 }
4451 
4452 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4453 /// TheCall is a constant expression in the range [Low, High].
4454 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4455                                        int Low, int High) {
4456   llvm::APSInt Result;
4457 
4458   // We can't check the value of a dependent argument.
4459   Expr *Arg = TheCall->getArg(ArgNum);
4460   if (Arg->isTypeDependent() || Arg->isValueDependent())
4461     return false;
4462 
4463   // Check constant-ness first.
4464   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4465     return true;
4466 
4467   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4468     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4469       << Low << High << Arg->getSourceRange();
4470 
4471   return false;
4472 }
4473 
4474 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4475 /// TheCall is a constant expression is a multiple of Num..
4476 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4477                                           unsigned Num) {
4478   llvm::APSInt Result;
4479 
4480   // We can't check the value of a dependent argument.
4481   Expr *Arg = TheCall->getArg(ArgNum);
4482   if (Arg->isTypeDependent() || Arg->isValueDependent())
4483     return false;
4484 
4485   // Check constant-ness first.
4486   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4487     return true;
4488 
4489   if (Result.getSExtValue() % Num != 0)
4490     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4491       << Num << Arg->getSourceRange();
4492 
4493   return false;
4494 }
4495 
4496 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4497 /// TheCall is an ARM/AArch64 special register string literal.
4498 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4499                                     int ArgNum, unsigned ExpectedFieldNum,
4500                                     bool AllowName) {
4501   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4502                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4503                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4504                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4505                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4506                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4507   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4508                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4509                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4510                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4511                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4512                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4513   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4514 
4515   // We can't check the value of a dependent argument.
4516   Expr *Arg = TheCall->getArg(ArgNum);
4517   if (Arg->isTypeDependent() || Arg->isValueDependent())
4518     return false;
4519 
4520   // Check if the argument is a string literal.
4521   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4522     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4523            << Arg->getSourceRange();
4524 
4525   // Check the type of special register given.
4526   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4527   SmallVector<StringRef, 6> Fields;
4528   Reg.split(Fields, ":");
4529 
4530   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4531     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4532            << Arg->getSourceRange();
4533 
4534   // If the string is the name of a register then we cannot check that it is
4535   // valid here but if the string is of one the forms described in ACLE then we
4536   // can check that the supplied fields are integers and within the valid
4537   // ranges.
4538   if (Fields.size() > 1) {
4539     bool FiveFields = Fields.size() == 5;
4540 
4541     bool ValidString = true;
4542     if (IsARMBuiltin) {
4543       ValidString &= Fields[0].startswith_lower("cp") ||
4544                      Fields[0].startswith_lower("p");
4545       if (ValidString)
4546         Fields[0] =
4547           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4548 
4549       ValidString &= Fields[2].startswith_lower("c");
4550       if (ValidString)
4551         Fields[2] = Fields[2].drop_front(1);
4552 
4553       if (FiveFields) {
4554         ValidString &= Fields[3].startswith_lower("c");
4555         if (ValidString)
4556           Fields[3] = Fields[3].drop_front(1);
4557       }
4558     }
4559 
4560     SmallVector<int, 5> Ranges;
4561     if (FiveFields)
4562       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4563     else
4564       Ranges.append({15, 7, 15});
4565 
4566     for (unsigned i=0; i<Fields.size(); ++i) {
4567       int IntField;
4568       ValidString &= !Fields[i].getAsInteger(10, IntField);
4569       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4570     }
4571 
4572     if (!ValidString)
4573       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4574              << Arg->getSourceRange();
4575 
4576   } else if (IsAArch64Builtin && Fields.size() == 1) {
4577     // If the register name is one of those that appear in the condition below
4578     // and the special register builtin being used is one of the write builtins,
4579     // then we require that the argument provided for writing to the register
4580     // is an integer constant expression. This is because it will be lowered to
4581     // an MSR (immediate) instruction, so we need to know the immediate at
4582     // compile time.
4583     if (TheCall->getNumArgs() != 2)
4584       return false;
4585 
4586     std::string RegLower = Reg.lower();
4587     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4588         RegLower != "pan" && RegLower != "uao")
4589       return false;
4590 
4591     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4592   }
4593 
4594   return false;
4595 }
4596 
4597 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4598 /// This checks that the target supports __builtin_longjmp and
4599 /// that val is a constant 1.
4600 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4601   if (!Context.getTargetInfo().hasSjLjLowering())
4602     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4603              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4604 
4605   Expr *Arg = TheCall->getArg(1);
4606   llvm::APSInt Result;
4607 
4608   // TODO: This is less than ideal. Overload this to take a value.
4609   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4610     return true;
4611 
4612   if (Result != 1)
4613     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4614              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4615 
4616   return false;
4617 }
4618 
4619 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4620 /// This checks that the target supports __builtin_setjmp.
4621 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4622   if (!Context.getTargetInfo().hasSjLjLowering())
4623     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4624              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4625   return false;
4626 }
4627 
4628 namespace {
4629 class UncoveredArgHandler {
4630   enum { Unknown = -1, AllCovered = -2 };
4631   signed FirstUncoveredArg;
4632   SmallVector<const Expr *, 4> DiagnosticExprs;
4633 
4634 public:
4635   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4636 
4637   bool hasUncoveredArg() const {
4638     return (FirstUncoveredArg >= 0);
4639   }
4640 
4641   unsigned getUncoveredArg() const {
4642     assert(hasUncoveredArg() && "no uncovered argument");
4643     return FirstUncoveredArg;
4644   }
4645 
4646   void setAllCovered() {
4647     // A string has been found with all arguments covered, so clear out
4648     // the diagnostics.
4649     DiagnosticExprs.clear();
4650     FirstUncoveredArg = AllCovered;
4651   }
4652 
4653   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4654     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4655 
4656     // Don't update if a previous string covers all arguments.
4657     if (FirstUncoveredArg == AllCovered)
4658       return;
4659 
4660     // UncoveredArgHandler tracks the highest uncovered argument index
4661     // and with it all the strings that match this index.
4662     if (NewFirstUncoveredArg == FirstUncoveredArg)
4663       DiagnosticExprs.push_back(StrExpr);
4664     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4665       DiagnosticExprs.clear();
4666       DiagnosticExprs.push_back(StrExpr);
4667       FirstUncoveredArg = NewFirstUncoveredArg;
4668     }
4669   }
4670 
4671   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4672 };
4673 
4674 enum StringLiteralCheckType {
4675   SLCT_NotALiteral,
4676   SLCT_UncheckedLiteral,
4677   SLCT_CheckedLiteral
4678 };
4679 } // end anonymous namespace
4680 
4681 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4682                                      BinaryOperatorKind BinOpKind,
4683                                      bool AddendIsRight) {
4684   unsigned BitWidth = Offset.getBitWidth();
4685   unsigned AddendBitWidth = Addend.getBitWidth();
4686   // There might be negative interim results.
4687   if (Addend.isUnsigned()) {
4688     Addend = Addend.zext(++AddendBitWidth);
4689     Addend.setIsSigned(true);
4690   }
4691   // Adjust the bit width of the APSInts.
4692   if (AddendBitWidth > BitWidth) {
4693     Offset = Offset.sext(AddendBitWidth);
4694     BitWidth = AddendBitWidth;
4695   } else if (BitWidth > AddendBitWidth) {
4696     Addend = Addend.sext(BitWidth);
4697   }
4698 
4699   bool Ov = false;
4700   llvm::APSInt ResOffset = Offset;
4701   if (BinOpKind == BO_Add)
4702     ResOffset = Offset.sadd_ov(Addend, Ov);
4703   else {
4704     assert(AddendIsRight && BinOpKind == BO_Sub &&
4705            "operator must be add or sub with addend on the right");
4706     ResOffset = Offset.ssub_ov(Addend, Ov);
4707   }
4708 
4709   // We add an offset to a pointer here so we should support an offset as big as
4710   // possible.
4711   if (Ov) {
4712     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4713     Offset = Offset.sext(2 * BitWidth);
4714     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4715     return;
4716   }
4717 
4718   Offset = ResOffset;
4719 }
4720 
4721 namespace {
4722 // This is a wrapper class around StringLiteral to support offsetted string
4723 // literals as format strings. It takes the offset into account when returning
4724 // the string and its length or the source locations to display notes correctly.
4725 class FormatStringLiteral {
4726   const StringLiteral *FExpr;
4727   int64_t Offset;
4728 
4729  public:
4730   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4731       : FExpr(fexpr), Offset(Offset) {}
4732 
4733   StringRef getString() const {
4734     return FExpr->getString().drop_front(Offset);
4735   }
4736 
4737   unsigned getByteLength() const {
4738     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4739   }
4740   unsigned getLength() const { return FExpr->getLength() - Offset; }
4741   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4742 
4743   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4744 
4745   QualType getType() const { return FExpr->getType(); }
4746 
4747   bool isAscii() const { return FExpr->isAscii(); }
4748   bool isWide() const { return FExpr->isWide(); }
4749   bool isUTF8() const { return FExpr->isUTF8(); }
4750   bool isUTF16() const { return FExpr->isUTF16(); }
4751   bool isUTF32() const { return FExpr->isUTF32(); }
4752   bool isPascal() const { return FExpr->isPascal(); }
4753 
4754   SourceLocation getLocationOfByte(
4755       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4756       const TargetInfo &Target, unsigned *StartToken = nullptr,
4757       unsigned *StartTokenByteOffset = nullptr) const {
4758     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4759                                     StartToken, StartTokenByteOffset);
4760   }
4761 
4762   SourceLocation getLocStart() const LLVM_READONLY {
4763     return FExpr->getLocStart().getLocWithOffset(Offset);
4764   }
4765   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4766 };
4767 }  // end anonymous namespace
4768 
4769 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4770                               const Expr *OrigFormatExpr,
4771                               ArrayRef<const Expr *> Args,
4772                               bool HasVAListArg, unsigned format_idx,
4773                               unsigned firstDataArg,
4774                               Sema::FormatStringType Type,
4775                               bool inFunctionCall,
4776                               Sema::VariadicCallType CallType,
4777                               llvm::SmallBitVector &CheckedVarArgs,
4778                               UncoveredArgHandler &UncoveredArg);
4779 
4780 // Determine if an expression is a string literal or constant string.
4781 // If this function returns false on the arguments to a function expecting a
4782 // format string, we will usually need to emit a warning.
4783 // True string literals are then checked by CheckFormatString.
4784 static StringLiteralCheckType
4785 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4786                       bool HasVAListArg, unsigned format_idx,
4787                       unsigned firstDataArg, Sema::FormatStringType Type,
4788                       Sema::VariadicCallType CallType, bool InFunctionCall,
4789                       llvm::SmallBitVector &CheckedVarArgs,
4790                       UncoveredArgHandler &UncoveredArg,
4791                       llvm::APSInt Offset) {
4792  tryAgain:
4793   assert(Offset.isSigned() && "invalid offset");
4794 
4795   if (E->isTypeDependent() || E->isValueDependent())
4796     return SLCT_NotALiteral;
4797 
4798   E = E->IgnoreParenCasts();
4799 
4800   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4801     // Technically -Wformat-nonliteral does not warn about this case.
4802     // The behavior of printf and friends in this case is implementation
4803     // dependent.  Ideally if the format string cannot be null then
4804     // it should have a 'nonnull' attribute in the function prototype.
4805     return SLCT_UncheckedLiteral;
4806 
4807   switch (E->getStmtClass()) {
4808   case Stmt::BinaryConditionalOperatorClass:
4809   case Stmt::ConditionalOperatorClass: {
4810     // The expression is a literal if both sub-expressions were, and it was
4811     // completely checked only if both sub-expressions were checked.
4812     const AbstractConditionalOperator *C =
4813         cast<AbstractConditionalOperator>(E);
4814 
4815     // Determine whether it is necessary to check both sub-expressions, for
4816     // example, because the condition expression is a constant that can be
4817     // evaluated at compile time.
4818     bool CheckLeft = true, CheckRight = true;
4819 
4820     bool Cond;
4821     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4822       if (Cond)
4823         CheckRight = false;
4824       else
4825         CheckLeft = false;
4826     }
4827 
4828     // We need to maintain the offsets for the right and the left hand side
4829     // separately to check if every possible indexed expression is a valid
4830     // string literal. They might have different offsets for different string
4831     // literals in the end.
4832     StringLiteralCheckType Left;
4833     if (!CheckLeft)
4834       Left = SLCT_UncheckedLiteral;
4835     else {
4836       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4837                                    HasVAListArg, format_idx, firstDataArg,
4838                                    Type, CallType, InFunctionCall,
4839                                    CheckedVarArgs, UncoveredArg, Offset);
4840       if (Left == SLCT_NotALiteral || !CheckRight) {
4841         return Left;
4842       }
4843     }
4844 
4845     StringLiteralCheckType Right =
4846         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4847                               HasVAListArg, format_idx, firstDataArg,
4848                               Type, CallType, InFunctionCall, CheckedVarArgs,
4849                               UncoveredArg, Offset);
4850 
4851     return (CheckLeft && Left < Right) ? Left : Right;
4852   }
4853 
4854   case Stmt::ImplicitCastExprClass: {
4855     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4856     goto tryAgain;
4857   }
4858 
4859   case Stmt::OpaqueValueExprClass:
4860     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4861       E = src;
4862       goto tryAgain;
4863     }
4864     return SLCT_NotALiteral;
4865 
4866   case Stmt::PredefinedExprClass:
4867     // While __func__, etc., are technically not string literals, they
4868     // cannot contain format specifiers and thus are not a security
4869     // liability.
4870     return SLCT_UncheckedLiteral;
4871 
4872   case Stmt::DeclRefExprClass: {
4873     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4874 
4875     // As an exception, do not flag errors for variables binding to
4876     // const string literals.
4877     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4878       bool isConstant = false;
4879       QualType T = DR->getType();
4880 
4881       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4882         isConstant = AT->getElementType().isConstant(S.Context);
4883       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4884         isConstant = T.isConstant(S.Context) &&
4885                      PT->getPointeeType().isConstant(S.Context);
4886       } else if (T->isObjCObjectPointerType()) {
4887         // In ObjC, there is usually no "const ObjectPointer" type,
4888         // so don't check if the pointee type is constant.
4889         isConstant = T.isConstant(S.Context);
4890       }
4891 
4892       if (isConstant) {
4893         if (const Expr *Init = VD->getAnyInitializer()) {
4894           // Look through initializers like const char c[] = { "foo" }
4895           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4896             if (InitList->isStringLiteralInit())
4897               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4898           }
4899           return checkFormatStringExpr(S, Init, Args,
4900                                        HasVAListArg, format_idx,
4901                                        firstDataArg, Type, CallType,
4902                                        /*InFunctionCall*/ false, CheckedVarArgs,
4903                                        UncoveredArg, Offset);
4904         }
4905       }
4906 
4907       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4908       // special check to see if the format string is a function parameter
4909       // of the function calling the printf function.  If the function
4910       // has an attribute indicating it is a printf-like function, then we
4911       // should suppress warnings concerning non-literals being used in a call
4912       // to a vprintf function.  For example:
4913       //
4914       // void
4915       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4916       //      va_list ap;
4917       //      va_start(ap, fmt);
4918       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4919       //      ...
4920       // }
4921       if (HasVAListArg) {
4922         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4923           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4924             int PVIndex = PV->getFunctionScopeIndex() + 1;
4925             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4926               // adjust for implicit parameter
4927               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4928                 if (MD->isInstance())
4929                   ++PVIndex;
4930               // We also check if the formats are compatible.
4931               // We can't pass a 'scanf' string to a 'printf' function.
4932               if (PVIndex == PVFormat->getFormatIdx() &&
4933                   Type == S.GetFormatStringType(PVFormat))
4934                 return SLCT_UncheckedLiteral;
4935             }
4936           }
4937         }
4938       }
4939     }
4940 
4941     return SLCT_NotALiteral;
4942   }
4943 
4944   case Stmt::CallExprClass:
4945   case Stmt::CXXMemberCallExprClass: {
4946     const CallExpr *CE = cast<CallExpr>(E);
4947     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4948       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4949         unsigned ArgIndex = FA->getFormatIdx();
4950         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4951           if (MD->isInstance())
4952             --ArgIndex;
4953         const Expr *Arg = CE->getArg(ArgIndex - 1);
4954 
4955         return checkFormatStringExpr(S, Arg, Args,
4956                                      HasVAListArg, format_idx, firstDataArg,
4957                                      Type, CallType, InFunctionCall,
4958                                      CheckedVarArgs, UncoveredArg, Offset);
4959       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4960         unsigned BuiltinID = FD->getBuiltinID();
4961         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4962             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4963           const Expr *Arg = CE->getArg(0);
4964           return checkFormatStringExpr(S, Arg, Args,
4965                                        HasVAListArg, format_idx,
4966                                        firstDataArg, Type, CallType,
4967                                        InFunctionCall, CheckedVarArgs,
4968                                        UncoveredArg, Offset);
4969         }
4970       }
4971     }
4972 
4973     return SLCT_NotALiteral;
4974   }
4975   case Stmt::ObjCMessageExprClass: {
4976     const auto *ME = cast<ObjCMessageExpr>(E);
4977     if (const auto *ND = ME->getMethodDecl()) {
4978       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4979         unsigned ArgIndex = FA->getFormatIdx();
4980         const Expr *Arg = ME->getArg(ArgIndex - 1);
4981         return checkFormatStringExpr(
4982             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4983             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4984       }
4985     }
4986 
4987     return SLCT_NotALiteral;
4988   }
4989   case Stmt::ObjCStringLiteralClass:
4990   case Stmt::StringLiteralClass: {
4991     const StringLiteral *StrE = nullptr;
4992 
4993     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4994       StrE = ObjCFExpr->getString();
4995     else
4996       StrE = cast<StringLiteral>(E);
4997 
4998     if (StrE) {
4999       if (Offset.isNegative() || Offset > StrE->getLength()) {
5000         // TODO: It would be better to have an explicit warning for out of
5001         // bounds literals.
5002         return SLCT_NotALiteral;
5003       }
5004       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
5005       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5006                         firstDataArg, Type, InFunctionCall, CallType,
5007                         CheckedVarArgs, UncoveredArg);
5008       return SLCT_CheckedLiteral;
5009     }
5010 
5011     return SLCT_NotALiteral;
5012   }
5013   case Stmt::BinaryOperatorClass: {
5014     llvm::APSInt LResult;
5015     llvm::APSInt RResult;
5016 
5017     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5018 
5019     // A string literal + an int offset is still a string literal.
5020     if (BinOp->isAdditiveOp()) {
5021       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5022       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5023 
5024       if (LIsInt != RIsInt) {
5025         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5026 
5027         if (LIsInt) {
5028           if (BinOpKind == BO_Add) {
5029             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5030             E = BinOp->getRHS();
5031             goto tryAgain;
5032           }
5033         } else {
5034           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5035           E = BinOp->getLHS();
5036           goto tryAgain;
5037         }
5038       }
5039     }
5040 
5041     return SLCT_NotALiteral;
5042   }
5043   case Stmt::UnaryOperatorClass: {
5044     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5045     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5046     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5047       llvm::APSInt IndexResult;
5048       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5049         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5050         E = ASE->getBase();
5051         goto tryAgain;
5052       }
5053     }
5054 
5055     return SLCT_NotALiteral;
5056   }
5057 
5058   default:
5059     return SLCT_NotALiteral;
5060   }
5061 }
5062 
5063 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5064   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5065       .Case("scanf", FST_Scanf)
5066       .Cases("printf", "printf0", FST_Printf)
5067       .Cases("NSString", "CFString", FST_NSString)
5068       .Case("strftime", FST_Strftime)
5069       .Case("strfmon", FST_Strfmon)
5070       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5071       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5072       .Case("os_trace", FST_OSLog)
5073       .Case("os_log", FST_OSLog)
5074       .Default(FST_Unknown);
5075 }
5076 
5077 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5078 /// functions) for correct use of format strings.
5079 /// Returns true if a format string has been fully checked.
5080 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5081                                 ArrayRef<const Expr *> Args,
5082                                 bool IsCXXMember,
5083                                 VariadicCallType CallType,
5084                                 SourceLocation Loc, SourceRange Range,
5085                                 llvm::SmallBitVector &CheckedVarArgs) {
5086   FormatStringInfo FSI;
5087   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5088     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5089                                 FSI.FirstDataArg, GetFormatStringType(Format),
5090                                 CallType, Loc, Range, CheckedVarArgs);
5091   return false;
5092 }
5093 
5094 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5095                                 bool HasVAListArg, unsigned format_idx,
5096                                 unsigned firstDataArg, FormatStringType Type,
5097                                 VariadicCallType CallType,
5098                                 SourceLocation Loc, SourceRange Range,
5099                                 llvm::SmallBitVector &CheckedVarArgs) {
5100   // CHECK: printf/scanf-like function is called with no format string.
5101   if (format_idx >= Args.size()) {
5102     Diag(Loc, diag::warn_missing_format_string) << Range;
5103     return false;
5104   }
5105 
5106   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5107 
5108   // CHECK: format string is not a string literal.
5109   //
5110   // Dynamically generated format strings are difficult to
5111   // automatically vet at compile time.  Requiring that format strings
5112   // are string literals: (1) permits the checking of format strings by
5113   // the compiler and thereby (2) can practically remove the source of
5114   // many format string exploits.
5115 
5116   // Format string can be either ObjC string (e.g. @"%d") or
5117   // C string (e.g. "%d")
5118   // ObjC string uses the same format specifiers as C string, so we can use
5119   // the same format string checking logic for both ObjC and C strings.
5120   UncoveredArgHandler UncoveredArg;
5121   StringLiteralCheckType CT =
5122       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5123                             format_idx, firstDataArg, Type, CallType,
5124                             /*IsFunctionCall*/ true, CheckedVarArgs,
5125                             UncoveredArg,
5126                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5127 
5128   // Generate a diagnostic where an uncovered argument is detected.
5129   if (UncoveredArg.hasUncoveredArg()) {
5130     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5131     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5132     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5133   }
5134 
5135   if (CT != SLCT_NotALiteral)
5136     // Literal format string found, check done!
5137     return CT == SLCT_CheckedLiteral;
5138 
5139   // Strftime is particular as it always uses a single 'time' argument,
5140   // so it is safe to pass a non-literal string.
5141   if (Type == FST_Strftime)
5142     return false;
5143 
5144   // Do not emit diag when the string param is a macro expansion and the
5145   // format is either NSString or CFString. This is a hack to prevent
5146   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5147   // which are usually used in place of NS and CF string literals.
5148   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5149   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5150     return false;
5151 
5152   // If there are no arguments specified, warn with -Wformat-security, otherwise
5153   // warn only with -Wformat-nonliteral.
5154   if (Args.size() == firstDataArg) {
5155     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5156       << OrigFormatExpr->getSourceRange();
5157     switch (Type) {
5158     default:
5159       break;
5160     case FST_Kprintf:
5161     case FST_FreeBSDKPrintf:
5162     case FST_Printf:
5163       Diag(FormatLoc, diag::note_format_security_fixit)
5164         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5165       break;
5166     case FST_NSString:
5167       Diag(FormatLoc, diag::note_format_security_fixit)
5168         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5169       break;
5170     }
5171   } else {
5172     Diag(FormatLoc, diag::warn_format_nonliteral)
5173       << OrigFormatExpr->getSourceRange();
5174   }
5175   return false;
5176 }
5177 
5178 namespace {
5179 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5180 protected:
5181   Sema &S;
5182   const FormatStringLiteral *FExpr;
5183   const Expr *OrigFormatExpr;
5184   const Sema::FormatStringType FSType;
5185   const unsigned FirstDataArg;
5186   const unsigned NumDataArgs;
5187   const char *Beg; // Start of format string.
5188   const bool HasVAListArg;
5189   ArrayRef<const Expr *> Args;
5190   unsigned FormatIdx;
5191   llvm::SmallBitVector CoveredArgs;
5192   bool usesPositionalArgs;
5193   bool atFirstArg;
5194   bool inFunctionCall;
5195   Sema::VariadicCallType CallType;
5196   llvm::SmallBitVector &CheckedVarArgs;
5197   UncoveredArgHandler &UncoveredArg;
5198 
5199 public:
5200   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5201                      const Expr *origFormatExpr,
5202                      const Sema::FormatStringType type, unsigned firstDataArg,
5203                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5204                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5205                      bool inFunctionCall, Sema::VariadicCallType callType,
5206                      llvm::SmallBitVector &CheckedVarArgs,
5207                      UncoveredArgHandler &UncoveredArg)
5208       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5209         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5210         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5211         usesPositionalArgs(false), atFirstArg(true),
5212         inFunctionCall(inFunctionCall), CallType(callType),
5213         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5214     CoveredArgs.resize(numDataArgs);
5215     CoveredArgs.reset();
5216   }
5217 
5218   void DoneProcessing();
5219 
5220   void HandleIncompleteSpecifier(const char *startSpecifier,
5221                                  unsigned specifierLen) override;
5222 
5223   void HandleInvalidLengthModifier(
5224                            const analyze_format_string::FormatSpecifier &FS,
5225                            const analyze_format_string::ConversionSpecifier &CS,
5226                            const char *startSpecifier, unsigned specifierLen,
5227                            unsigned DiagID);
5228 
5229   void HandleNonStandardLengthModifier(
5230                     const analyze_format_string::FormatSpecifier &FS,
5231                     const char *startSpecifier, unsigned specifierLen);
5232 
5233   void HandleNonStandardConversionSpecifier(
5234                     const analyze_format_string::ConversionSpecifier &CS,
5235                     const char *startSpecifier, unsigned specifierLen);
5236 
5237   void HandlePosition(const char *startPos, unsigned posLen) override;
5238 
5239   void HandleInvalidPosition(const char *startSpecifier,
5240                              unsigned specifierLen,
5241                              analyze_format_string::PositionContext p) override;
5242 
5243   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5244 
5245   void HandleNullChar(const char *nullCharacter) override;
5246 
5247   template <typename Range>
5248   static void
5249   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5250                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5251                        bool IsStringLocation, Range StringRange,
5252                        ArrayRef<FixItHint> Fixit = None);
5253 
5254 protected:
5255   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5256                                         const char *startSpec,
5257                                         unsigned specifierLen,
5258                                         const char *csStart, unsigned csLen);
5259 
5260   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5261                                          const char *startSpec,
5262                                          unsigned specifierLen);
5263 
5264   SourceRange getFormatStringRange();
5265   CharSourceRange getSpecifierRange(const char *startSpecifier,
5266                                     unsigned specifierLen);
5267   SourceLocation getLocationOfByte(const char *x);
5268 
5269   const Expr *getDataArg(unsigned i) const;
5270 
5271   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5272                     const analyze_format_string::ConversionSpecifier &CS,
5273                     const char *startSpecifier, unsigned specifierLen,
5274                     unsigned argIndex);
5275 
5276   template <typename Range>
5277   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5278                             bool IsStringLocation, Range StringRange,
5279                             ArrayRef<FixItHint> Fixit = None);
5280 };
5281 } // end anonymous namespace
5282 
5283 SourceRange CheckFormatHandler::getFormatStringRange() {
5284   return OrigFormatExpr->getSourceRange();
5285 }
5286 
5287 CharSourceRange CheckFormatHandler::
5288 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5289   SourceLocation Start = getLocationOfByte(startSpecifier);
5290   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5291 
5292   // Advance the end SourceLocation by one due to half-open ranges.
5293   End = End.getLocWithOffset(1);
5294 
5295   return CharSourceRange::getCharRange(Start, End);
5296 }
5297 
5298 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5299   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5300                                   S.getLangOpts(), S.Context.getTargetInfo());
5301 }
5302 
5303 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5304                                                    unsigned specifierLen){
5305   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5306                        getLocationOfByte(startSpecifier),
5307                        /*IsStringLocation*/true,
5308                        getSpecifierRange(startSpecifier, specifierLen));
5309 }
5310 
5311 void CheckFormatHandler::HandleInvalidLengthModifier(
5312     const analyze_format_string::FormatSpecifier &FS,
5313     const analyze_format_string::ConversionSpecifier &CS,
5314     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5315   using namespace analyze_format_string;
5316 
5317   const LengthModifier &LM = FS.getLengthModifier();
5318   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5319 
5320   // See if we know how to fix this length modifier.
5321   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5322   if (FixedLM) {
5323     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5324                          getLocationOfByte(LM.getStart()),
5325                          /*IsStringLocation*/true,
5326                          getSpecifierRange(startSpecifier, specifierLen));
5327 
5328     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5329       << FixedLM->toString()
5330       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5331 
5332   } else {
5333     FixItHint Hint;
5334     if (DiagID == diag::warn_format_nonsensical_length)
5335       Hint = FixItHint::CreateRemoval(LMRange);
5336 
5337     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5338                          getLocationOfByte(LM.getStart()),
5339                          /*IsStringLocation*/true,
5340                          getSpecifierRange(startSpecifier, specifierLen),
5341                          Hint);
5342   }
5343 }
5344 
5345 void CheckFormatHandler::HandleNonStandardLengthModifier(
5346     const analyze_format_string::FormatSpecifier &FS,
5347     const char *startSpecifier, unsigned specifierLen) {
5348   using namespace analyze_format_string;
5349 
5350   const LengthModifier &LM = FS.getLengthModifier();
5351   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5352 
5353   // See if we know how to fix this length modifier.
5354   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5355   if (FixedLM) {
5356     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5357                            << LM.toString() << 0,
5358                          getLocationOfByte(LM.getStart()),
5359                          /*IsStringLocation*/true,
5360                          getSpecifierRange(startSpecifier, specifierLen));
5361 
5362     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5363       << FixedLM->toString()
5364       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5365 
5366   } else {
5367     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5368                            << LM.toString() << 0,
5369                          getLocationOfByte(LM.getStart()),
5370                          /*IsStringLocation*/true,
5371                          getSpecifierRange(startSpecifier, specifierLen));
5372   }
5373 }
5374 
5375 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5376     const analyze_format_string::ConversionSpecifier &CS,
5377     const char *startSpecifier, unsigned specifierLen) {
5378   using namespace analyze_format_string;
5379 
5380   // See if we know how to fix this conversion specifier.
5381   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5382   if (FixedCS) {
5383     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5384                           << CS.toString() << /*conversion specifier*/1,
5385                          getLocationOfByte(CS.getStart()),
5386                          /*IsStringLocation*/true,
5387                          getSpecifierRange(startSpecifier, specifierLen));
5388 
5389     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5390     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5391       << FixedCS->toString()
5392       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5393   } else {
5394     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5395                           << CS.toString() << /*conversion specifier*/1,
5396                          getLocationOfByte(CS.getStart()),
5397                          /*IsStringLocation*/true,
5398                          getSpecifierRange(startSpecifier, specifierLen));
5399   }
5400 }
5401 
5402 void CheckFormatHandler::HandlePosition(const char *startPos,
5403                                         unsigned posLen) {
5404   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5405                                getLocationOfByte(startPos),
5406                                /*IsStringLocation*/true,
5407                                getSpecifierRange(startPos, posLen));
5408 }
5409 
5410 void
5411 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5412                                      analyze_format_string::PositionContext p) {
5413   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5414                          << (unsigned) p,
5415                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5416                        getSpecifierRange(startPos, posLen));
5417 }
5418 
5419 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5420                                             unsigned posLen) {
5421   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5422                                getLocationOfByte(startPos),
5423                                /*IsStringLocation*/true,
5424                                getSpecifierRange(startPos, posLen));
5425 }
5426 
5427 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5428   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5429     // The presence of a null character is likely an error.
5430     EmitFormatDiagnostic(
5431       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5432       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5433       getFormatStringRange());
5434   }
5435 }
5436 
5437 // Note that this may return NULL if there was an error parsing or building
5438 // one of the argument expressions.
5439 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5440   return Args[FirstDataArg + i];
5441 }
5442 
5443 void CheckFormatHandler::DoneProcessing() {
5444   // Does the number of data arguments exceed the number of
5445   // format conversions in the format string?
5446   if (!HasVAListArg) {
5447       // Find any arguments that weren't covered.
5448     CoveredArgs.flip();
5449     signed notCoveredArg = CoveredArgs.find_first();
5450     if (notCoveredArg >= 0) {
5451       assert((unsigned)notCoveredArg < NumDataArgs);
5452       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5453     } else {
5454       UncoveredArg.setAllCovered();
5455     }
5456   }
5457 }
5458 
5459 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5460                                    const Expr *ArgExpr) {
5461   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5462          "Invalid state");
5463 
5464   if (!ArgExpr)
5465     return;
5466 
5467   SourceLocation Loc = ArgExpr->getLocStart();
5468 
5469   if (S.getSourceManager().isInSystemMacro(Loc))
5470     return;
5471 
5472   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5473   for (auto E : DiagnosticExprs)
5474     PDiag << E->getSourceRange();
5475 
5476   CheckFormatHandler::EmitFormatDiagnostic(
5477                                   S, IsFunctionCall, DiagnosticExprs[0],
5478                                   PDiag, Loc, /*IsStringLocation*/false,
5479                                   DiagnosticExprs[0]->getSourceRange());
5480 }
5481 
5482 bool
5483 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5484                                                      SourceLocation Loc,
5485                                                      const char *startSpec,
5486                                                      unsigned specifierLen,
5487                                                      const char *csStart,
5488                                                      unsigned csLen) {
5489   bool keepGoing = true;
5490   if (argIndex < NumDataArgs) {
5491     // Consider the argument coverered, even though the specifier doesn't
5492     // make sense.
5493     CoveredArgs.set(argIndex);
5494   }
5495   else {
5496     // If argIndex exceeds the number of data arguments we
5497     // don't issue a warning because that is just a cascade of warnings (and
5498     // they may have intended '%%' anyway). We don't want to continue processing
5499     // the format string after this point, however, as we will like just get
5500     // gibberish when trying to match arguments.
5501     keepGoing = false;
5502   }
5503 
5504   StringRef Specifier(csStart, csLen);
5505 
5506   // If the specifier in non-printable, it could be the first byte of a UTF-8
5507   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5508   // hex value.
5509   std::string CodePointStr;
5510   if (!llvm::sys::locale::isPrint(*csStart)) {
5511     llvm::UTF32 CodePoint;
5512     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5513     const llvm::UTF8 *E =
5514         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5515     llvm::ConversionResult Result =
5516         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5517 
5518     if (Result != llvm::conversionOK) {
5519       unsigned char FirstChar = *csStart;
5520       CodePoint = (llvm::UTF32)FirstChar;
5521     }
5522 
5523     llvm::raw_string_ostream OS(CodePointStr);
5524     if (CodePoint < 256)
5525       OS << "\\x" << llvm::format("%02x", CodePoint);
5526     else if (CodePoint <= 0xFFFF)
5527       OS << "\\u" << llvm::format("%04x", CodePoint);
5528     else
5529       OS << "\\U" << llvm::format("%08x", CodePoint);
5530     OS.flush();
5531     Specifier = CodePointStr;
5532   }
5533 
5534   EmitFormatDiagnostic(
5535       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5536       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5537 
5538   return keepGoing;
5539 }
5540 
5541 void
5542 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5543                                                       const char *startSpec,
5544                                                       unsigned specifierLen) {
5545   EmitFormatDiagnostic(
5546     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5547     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5548 }
5549 
5550 bool
5551 CheckFormatHandler::CheckNumArgs(
5552   const analyze_format_string::FormatSpecifier &FS,
5553   const analyze_format_string::ConversionSpecifier &CS,
5554   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5555 
5556   if (argIndex >= NumDataArgs) {
5557     PartialDiagnostic PDiag = FS.usesPositionalArg()
5558       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5559            << (argIndex+1) << NumDataArgs)
5560       : S.PDiag(diag::warn_printf_insufficient_data_args);
5561     EmitFormatDiagnostic(
5562       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5563       getSpecifierRange(startSpecifier, specifierLen));
5564 
5565     // Since more arguments than conversion tokens are given, by extension
5566     // all arguments are covered, so mark this as so.
5567     UncoveredArg.setAllCovered();
5568     return false;
5569   }
5570   return true;
5571 }
5572 
5573 template<typename Range>
5574 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5575                                               SourceLocation Loc,
5576                                               bool IsStringLocation,
5577                                               Range StringRange,
5578                                               ArrayRef<FixItHint> FixIt) {
5579   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5580                        Loc, IsStringLocation, StringRange, FixIt);
5581 }
5582 
5583 /// \brief If the format string is not within the funcion call, emit a note
5584 /// so that the function call and string are in diagnostic messages.
5585 ///
5586 /// \param InFunctionCall if true, the format string is within the function
5587 /// call and only one diagnostic message will be produced.  Otherwise, an
5588 /// extra note will be emitted pointing to location of the format string.
5589 ///
5590 /// \param ArgumentExpr the expression that is passed as the format string
5591 /// argument in the function call.  Used for getting locations when two
5592 /// diagnostics are emitted.
5593 ///
5594 /// \param PDiag the callee should already have provided any strings for the
5595 /// diagnostic message.  This function only adds locations and fixits
5596 /// to diagnostics.
5597 ///
5598 /// \param Loc primary location for diagnostic.  If two diagnostics are
5599 /// required, one will be at Loc and a new SourceLocation will be created for
5600 /// the other one.
5601 ///
5602 /// \param IsStringLocation if true, Loc points to the format string should be
5603 /// used for the note.  Otherwise, Loc points to the argument list and will
5604 /// be used with PDiag.
5605 ///
5606 /// \param StringRange some or all of the string to highlight.  This is
5607 /// templated so it can accept either a CharSourceRange or a SourceRange.
5608 ///
5609 /// \param FixIt optional fix it hint for the format string.
5610 template <typename Range>
5611 void CheckFormatHandler::EmitFormatDiagnostic(
5612     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5613     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5614     Range StringRange, ArrayRef<FixItHint> FixIt) {
5615   if (InFunctionCall) {
5616     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5617     D << StringRange;
5618     D << FixIt;
5619   } else {
5620     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5621       << ArgumentExpr->getSourceRange();
5622 
5623     const Sema::SemaDiagnosticBuilder &Note =
5624       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5625              diag::note_format_string_defined);
5626 
5627     Note << StringRange;
5628     Note << FixIt;
5629   }
5630 }
5631 
5632 //===--- CHECK: Printf format string checking ------------------------------===//
5633 
5634 namespace {
5635 class CheckPrintfHandler : public CheckFormatHandler {
5636 public:
5637   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5638                      const Expr *origFormatExpr,
5639                      const Sema::FormatStringType type, unsigned firstDataArg,
5640                      unsigned numDataArgs, bool isObjC, const char *beg,
5641                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5642                      unsigned formatIdx, bool inFunctionCall,
5643                      Sema::VariadicCallType CallType,
5644                      llvm::SmallBitVector &CheckedVarArgs,
5645                      UncoveredArgHandler &UncoveredArg)
5646       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5647                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5648                            inFunctionCall, CallType, CheckedVarArgs,
5649                            UncoveredArg) {}
5650 
5651   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5652 
5653   /// Returns true if '%@' specifiers are allowed in the format string.
5654   bool allowsObjCArg() const {
5655     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5656            FSType == Sema::FST_OSTrace;
5657   }
5658 
5659   bool HandleInvalidPrintfConversionSpecifier(
5660                                       const analyze_printf::PrintfSpecifier &FS,
5661                                       const char *startSpecifier,
5662                                       unsigned specifierLen) override;
5663 
5664   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5665                              const char *startSpecifier,
5666                              unsigned specifierLen) override;
5667   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5668                        const char *StartSpecifier,
5669                        unsigned SpecifierLen,
5670                        const Expr *E);
5671 
5672   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5673                     const char *startSpecifier, unsigned specifierLen);
5674   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5675                            const analyze_printf::OptionalAmount &Amt,
5676                            unsigned type,
5677                            const char *startSpecifier, unsigned specifierLen);
5678   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5679                   const analyze_printf::OptionalFlag &flag,
5680                   const char *startSpecifier, unsigned specifierLen);
5681   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5682                          const analyze_printf::OptionalFlag &ignoredFlag,
5683                          const analyze_printf::OptionalFlag &flag,
5684                          const char *startSpecifier, unsigned specifierLen);
5685   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5686                            const Expr *E);
5687 
5688   void HandleEmptyObjCModifierFlag(const char *startFlag,
5689                                    unsigned flagLen) override;
5690 
5691   void HandleInvalidObjCModifierFlag(const char *startFlag,
5692                                             unsigned flagLen) override;
5693 
5694   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5695                                            const char *flagsEnd,
5696                                            const char *conversionPosition)
5697                                              override;
5698 };
5699 } // end anonymous namespace
5700 
5701 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5702                                       const analyze_printf::PrintfSpecifier &FS,
5703                                       const char *startSpecifier,
5704                                       unsigned specifierLen) {
5705   const analyze_printf::PrintfConversionSpecifier &CS =
5706     FS.getConversionSpecifier();
5707 
5708   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5709                                           getLocationOfByte(CS.getStart()),
5710                                           startSpecifier, specifierLen,
5711                                           CS.getStart(), CS.getLength());
5712 }
5713 
5714 bool CheckPrintfHandler::HandleAmount(
5715                                const analyze_format_string::OptionalAmount &Amt,
5716                                unsigned k, const char *startSpecifier,
5717                                unsigned specifierLen) {
5718   if (Amt.hasDataArgument()) {
5719     if (!HasVAListArg) {
5720       unsigned argIndex = Amt.getArgIndex();
5721       if (argIndex >= NumDataArgs) {
5722         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5723                                << k,
5724                              getLocationOfByte(Amt.getStart()),
5725                              /*IsStringLocation*/true,
5726                              getSpecifierRange(startSpecifier, specifierLen));
5727         // Don't do any more checking.  We will just emit
5728         // spurious errors.
5729         return false;
5730       }
5731 
5732       // Type check the data argument.  It should be an 'int'.
5733       // Although not in conformance with C99, we also allow the argument to be
5734       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5735       // doesn't emit a warning for that case.
5736       CoveredArgs.set(argIndex);
5737       const Expr *Arg = getDataArg(argIndex);
5738       if (!Arg)
5739         return false;
5740 
5741       QualType T = Arg->getType();
5742 
5743       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5744       assert(AT.isValid());
5745 
5746       if (!AT.matchesType(S.Context, T)) {
5747         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5748                                << k << AT.getRepresentativeTypeName(S.Context)
5749                                << T << Arg->getSourceRange(),
5750                              getLocationOfByte(Amt.getStart()),
5751                              /*IsStringLocation*/true,
5752                              getSpecifierRange(startSpecifier, specifierLen));
5753         // Don't do any more checking.  We will just emit
5754         // spurious errors.
5755         return false;
5756       }
5757     }
5758   }
5759   return true;
5760 }
5761 
5762 void CheckPrintfHandler::HandleInvalidAmount(
5763                                       const analyze_printf::PrintfSpecifier &FS,
5764                                       const analyze_printf::OptionalAmount &Amt,
5765                                       unsigned type,
5766                                       const char *startSpecifier,
5767                                       unsigned specifierLen) {
5768   const analyze_printf::PrintfConversionSpecifier &CS =
5769     FS.getConversionSpecifier();
5770 
5771   FixItHint fixit =
5772     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5773       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5774                                  Amt.getConstantLength()))
5775       : FixItHint();
5776 
5777   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5778                          << type << CS.toString(),
5779                        getLocationOfByte(Amt.getStart()),
5780                        /*IsStringLocation*/true,
5781                        getSpecifierRange(startSpecifier, specifierLen),
5782                        fixit);
5783 }
5784 
5785 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5786                                     const analyze_printf::OptionalFlag &flag,
5787                                     const char *startSpecifier,
5788                                     unsigned specifierLen) {
5789   // Warn about pointless flag with a fixit removal.
5790   const analyze_printf::PrintfConversionSpecifier &CS =
5791     FS.getConversionSpecifier();
5792   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5793                          << flag.toString() << CS.toString(),
5794                        getLocationOfByte(flag.getPosition()),
5795                        /*IsStringLocation*/true,
5796                        getSpecifierRange(startSpecifier, specifierLen),
5797                        FixItHint::CreateRemoval(
5798                          getSpecifierRange(flag.getPosition(), 1)));
5799 }
5800 
5801 void CheckPrintfHandler::HandleIgnoredFlag(
5802                                 const analyze_printf::PrintfSpecifier &FS,
5803                                 const analyze_printf::OptionalFlag &ignoredFlag,
5804                                 const analyze_printf::OptionalFlag &flag,
5805                                 const char *startSpecifier,
5806                                 unsigned specifierLen) {
5807   // Warn about ignored flag with a fixit removal.
5808   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5809                          << ignoredFlag.toString() << flag.toString(),
5810                        getLocationOfByte(ignoredFlag.getPosition()),
5811                        /*IsStringLocation*/true,
5812                        getSpecifierRange(startSpecifier, specifierLen),
5813                        FixItHint::CreateRemoval(
5814                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5815 }
5816 
5817 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5818 //                            bool IsStringLocation, Range StringRange,
5819 //                            ArrayRef<FixItHint> Fixit = None);
5820 
5821 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5822                                                      unsigned flagLen) {
5823   // Warn about an empty flag.
5824   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5825                        getLocationOfByte(startFlag),
5826                        /*IsStringLocation*/true,
5827                        getSpecifierRange(startFlag, flagLen));
5828 }
5829 
5830 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5831                                                        unsigned flagLen) {
5832   // Warn about an invalid flag.
5833   auto Range = getSpecifierRange(startFlag, flagLen);
5834   StringRef flag(startFlag, flagLen);
5835   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5836                       getLocationOfByte(startFlag),
5837                       /*IsStringLocation*/true,
5838                       Range, FixItHint::CreateRemoval(Range));
5839 }
5840 
5841 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5842     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5843     // Warn about using '[...]' without a '@' conversion.
5844     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5845     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5846     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5847                          getLocationOfByte(conversionPosition),
5848                          /*IsStringLocation*/true,
5849                          Range, FixItHint::CreateRemoval(Range));
5850 }
5851 
5852 // Determines if the specified is a C++ class or struct containing
5853 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5854 // "c_str()").
5855 template<typename MemberKind>
5856 static llvm::SmallPtrSet<MemberKind*, 1>
5857 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5858   const RecordType *RT = Ty->getAs<RecordType>();
5859   llvm::SmallPtrSet<MemberKind*, 1> Results;
5860 
5861   if (!RT)
5862     return Results;
5863   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5864   if (!RD || !RD->getDefinition())
5865     return Results;
5866 
5867   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5868                  Sema::LookupMemberName);
5869   R.suppressDiagnostics();
5870 
5871   // We just need to include all members of the right kind turned up by the
5872   // filter, at this point.
5873   if (S.LookupQualifiedName(R, RT->getDecl()))
5874     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5875       NamedDecl *decl = (*I)->getUnderlyingDecl();
5876       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5877         Results.insert(FK);
5878     }
5879   return Results;
5880 }
5881 
5882 /// Check if we could call '.c_str()' on an object.
5883 ///
5884 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5885 /// allow the call, or if it would be ambiguous).
5886 bool Sema::hasCStrMethod(const Expr *E) {
5887   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5888   MethodSet Results =
5889       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5890   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5891        MI != ME; ++MI)
5892     if ((*MI)->getMinRequiredArguments() == 0)
5893       return true;
5894   return false;
5895 }
5896 
5897 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5898 // better diagnostic if so. AT is assumed to be valid.
5899 // Returns true when a c_str() conversion method is found.
5900 bool CheckPrintfHandler::checkForCStrMembers(
5901     const analyze_printf::ArgType &AT, const Expr *E) {
5902   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5903 
5904   MethodSet Results =
5905       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5906 
5907   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5908        MI != ME; ++MI) {
5909     const CXXMethodDecl *Method = *MI;
5910     if (Method->getMinRequiredArguments() == 0 &&
5911         AT.matchesType(S.Context, Method->getReturnType())) {
5912       // FIXME: Suggest parens if the expression needs them.
5913       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5914       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5915           << "c_str()"
5916           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5917       return true;
5918     }
5919   }
5920 
5921   return false;
5922 }
5923 
5924 bool
5925 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5926                                             &FS,
5927                                           const char *startSpecifier,
5928                                           unsigned specifierLen) {
5929   using namespace analyze_format_string;
5930   using namespace analyze_printf;
5931   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5932 
5933   if (FS.consumesDataArgument()) {
5934     if (atFirstArg) {
5935         atFirstArg = false;
5936         usesPositionalArgs = FS.usesPositionalArg();
5937     }
5938     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5939       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5940                                         startSpecifier, specifierLen);
5941       return false;
5942     }
5943   }
5944 
5945   // First check if the field width, precision, and conversion specifier
5946   // have matching data arguments.
5947   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5948                     startSpecifier, specifierLen)) {
5949     return false;
5950   }
5951 
5952   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5953                     startSpecifier, specifierLen)) {
5954     return false;
5955   }
5956 
5957   if (!CS.consumesDataArgument()) {
5958     // FIXME: Technically specifying a precision or field width here
5959     // makes no sense.  Worth issuing a warning at some point.
5960     return true;
5961   }
5962 
5963   // Consume the argument.
5964   unsigned argIndex = FS.getArgIndex();
5965   if (argIndex < NumDataArgs) {
5966     // The check to see if the argIndex is valid will come later.
5967     // We set the bit here because we may exit early from this
5968     // function if we encounter some other error.
5969     CoveredArgs.set(argIndex);
5970   }
5971 
5972   // FreeBSD kernel extensions.
5973   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5974       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5975     // We need at least two arguments.
5976     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5977       return false;
5978 
5979     // Claim the second argument.
5980     CoveredArgs.set(argIndex + 1);
5981 
5982     // Type check the first argument (int for %b, pointer for %D)
5983     const Expr *Ex = getDataArg(argIndex);
5984     const analyze_printf::ArgType &AT =
5985       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5986         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5987     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5988       EmitFormatDiagnostic(
5989         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5990         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5991         << false << Ex->getSourceRange(),
5992         Ex->getLocStart(), /*IsStringLocation*/false,
5993         getSpecifierRange(startSpecifier, specifierLen));
5994 
5995     // Type check the second argument (char * for both %b and %D)
5996     Ex = getDataArg(argIndex + 1);
5997     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5998     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5999       EmitFormatDiagnostic(
6000         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6001         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
6002         << false << Ex->getSourceRange(),
6003         Ex->getLocStart(), /*IsStringLocation*/false,
6004         getSpecifierRange(startSpecifier, specifierLen));
6005 
6006      return true;
6007   }
6008 
6009   // Check for using an Objective-C specific conversion specifier
6010   // in a non-ObjC literal.
6011   if (!allowsObjCArg() && CS.isObjCArg()) {
6012     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6013                                                   specifierLen);
6014   }
6015 
6016   // %P can only be used with os_log.
6017   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6018     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6019                                                   specifierLen);
6020   }
6021 
6022   // %n is not allowed with os_log.
6023   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6024     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6025                          getLocationOfByte(CS.getStart()),
6026                          /*IsStringLocation*/ false,
6027                          getSpecifierRange(startSpecifier, specifierLen));
6028 
6029     return true;
6030   }
6031 
6032   // Only scalars are allowed for os_trace.
6033   if (FSType == Sema::FST_OSTrace &&
6034       (CS.getKind() == ConversionSpecifier::PArg ||
6035        CS.getKind() == ConversionSpecifier::sArg ||
6036        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6037     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6038                                                   specifierLen);
6039   }
6040 
6041   // Check for use of public/private annotation outside of os_log().
6042   if (FSType != Sema::FST_OSLog) {
6043     if (FS.isPublic().isSet()) {
6044       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6045                                << "public",
6046                            getLocationOfByte(FS.isPublic().getPosition()),
6047                            /*IsStringLocation*/ false,
6048                            getSpecifierRange(startSpecifier, specifierLen));
6049     }
6050     if (FS.isPrivate().isSet()) {
6051       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6052                                << "private",
6053                            getLocationOfByte(FS.isPrivate().getPosition()),
6054                            /*IsStringLocation*/ false,
6055                            getSpecifierRange(startSpecifier, specifierLen));
6056     }
6057   }
6058 
6059   // Check for invalid use of field width
6060   if (!FS.hasValidFieldWidth()) {
6061     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6062         startSpecifier, specifierLen);
6063   }
6064 
6065   // Check for invalid use of precision
6066   if (!FS.hasValidPrecision()) {
6067     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6068         startSpecifier, specifierLen);
6069   }
6070 
6071   // Precision is mandatory for %P specifier.
6072   if (CS.getKind() == ConversionSpecifier::PArg &&
6073       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6074     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6075                          getLocationOfByte(startSpecifier),
6076                          /*IsStringLocation*/ false,
6077                          getSpecifierRange(startSpecifier, specifierLen));
6078   }
6079 
6080   // Check each flag does not conflict with any other component.
6081   if (!FS.hasValidThousandsGroupingPrefix())
6082     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6083   if (!FS.hasValidLeadingZeros())
6084     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6085   if (!FS.hasValidPlusPrefix())
6086     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6087   if (!FS.hasValidSpacePrefix())
6088     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6089   if (!FS.hasValidAlternativeForm())
6090     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6091   if (!FS.hasValidLeftJustified())
6092     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6093 
6094   // Check that flags are not ignored by another flag
6095   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6096     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6097         startSpecifier, specifierLen);
6098   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6099     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6100             startSpecifier, specifierLen);
6101 
6102   // Check the length modifier is valid with the given conversion specifier.
6103   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6104     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6105                                 diag::warn_format_nonsensical_length);
6106   else if (!FS.hasStandardLengthModifier())
6107     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6108   else if (!FS.hasStandardLengthConversionCombination())
6109     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6110                                 diag::warn_format_non_standard_conversion_spec);
6111 
6112   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6113     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6114 
6115   // The remaining checks depend on the data arguments.
6116   if (HasVAListArg)
6117     return true;
6118 
6119   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6120     return false;
6121 
6122   const Expr *Arg = getDataArg(argIndex);
6123   if (!Arg)
6124     return true;
6125 
6126   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6127 }
6128 
6129 static bool requiresParensToAddCast(const Expr *E) {
6130   // FIXME: We should have a general way to reason about operator
6131   // precedence and whether parens are actually needed here.
6132   // Take care of a few common cases where they aren't.
6133   const Expr *Inside = E->IgnoreImpCasts();
6134   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6135     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6136 
6137   switch (Inside->getStmtClass()) {
6138   case Stmt::ArraySubscriptExprClass:
6139   case Stmt::CallExprClass:
6140   case Stmt::CharacterLiteralClass:
6141   case Stmt::CXXBoolLiteralExprClass:
6142   case Stmt::DeclRefExprClass:
6143   case Stmt::FloatingLiteralClass:
6144   case Stmt::IntegerLiteralClass:
6145   case Stmt::MemberExprClass:
6146   case Stmt::ObjCArrayLiteralClass:
6147   case Stmt::ObjCBoolLiteralExprClass:
6148   case Stmt::ObjCBoxedExprClass:
6149   case Stmt::ObjCDictionaryLiteralClass:
6150   case Stmt::ObjCEncodeExprClass:
6151   case Stmt::ObjCIvarRefExprClass:
6152   case Stmt::ObjCMessageExprClass:
6153   case Stmt::ObjCPropertyRefExprClass:
6154   case Stmt::ObjCStringLiteralClass:
6155   case Stmt::ObjCSubscriptRefExprClass:
6156   case Stmt::ParenExprClass:
6157   case Stmt::StringLiteralClass:
6158   case Stmt::UnaryOperatorClass:
6159     return false;
6160   default:
6161     return true;
6162   }
6163 }
6164 
6165 static std::pair<QualType, StringRef>
6166 shouldNotPrintDirectly(const ASTContext &Context,
6167                        QualType IntendedTy,
6168                        const Expr *E) {
6169   // Use a 'while' to peel off layers of typedefs.
6170   QualType TyTy = IntendedTy;
6171   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6172     StringRef Name = UserTy->getDecl()->getName();
6173     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6174       .Case("CFIndex", Context.getNSIntegerType())
6175       .Case("NSInteger", Context.getNSIntegerType())
6176       .Case("NSUInteger", Context.getNSUIntegerType())
6177       .Case("SInt32", Context.IntTy)
6178       .Case("UInt32", Context.UnsignedIntTy)
6179       .Default(QualType());
6180 
6181     if (!CastTy.isNull())
6182       return std::make_pair(CastTy, Name);
6183 
6184     TyTy = UserTy->desugar();
6185   }
6186 
6187   // Strip parens if necessary.
6188   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6189     return shouldNotPrintDirectly(Context,
6190                                   PE->getSubExpr()->getType(),
6191                                   PE->getSubExpr());
6192 
6193   // If this is a conditional expression, then its result type is constructed
6194   // via usual arithmetic conversions and thus there might be no necessary
6195   // typedef sugar there.  Recurse to operands to check for NSInteger &
6196   // Co. usage condition.
6197   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6198     QualType TrueTy, FalseTy;
6199     StringRef TrueName, FalseName;
6200 
6201     std::tie(TrueTy, TrueName) =
6202       shouldNotPrintDirectly(Context,
6203                              CO->getTrueExpr()->getType(),
6204                              CO->getTrueExpr());
6205     std::tie(FalseTy, FalseName) =
6206       shouldNotPrintDirectly(Context,
6207                              CO->getFalseExpr()->getType(),
6208                              CO->getFalseExpr());
6209 
6210     if (TrueTy == FalseTy)
6211       return std::make_pair(TrueTy, TrueName);
6212     else if (TrueTy.isNull())
6213       return std::make_pair(FalseTy, FalseName);
6214     else if (FalseTy.isNull())
6215       return std::make_pair(TrueTy, TrueName);
6216   }
6217 
6218   return std::make_pair(QualType(), StringRef());
6219 }
6220 
6221 bool
6222 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6223                                     const char *StartSpecifier,
6224                                     unsigned SpecifierLen,
6225                                     const Expr *E) {
6226   using namespace analyze_format_string;
6227   using namespace analyze_printf;
6228   // Now type check the data expression that matches the
6229   // format specifier.
6230   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6231   if (!AT.isValid())
6232     return true;
6233 
6234   QualType ExprTy = E->getType();
6235   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6236     ExprTy = TET->getUnderlyingExpr()->getType();
6237   }
6238 
6239   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6240 
6241   if (match == analyze_printf::ArgType::Match) {
6242     return true;
6243   }
6244 
6245   // Look through argument promotions for our error message's reported type.
6246   // This includes the integral and floating promotions, but excludes array
6247   // and function pointer decay; seeing that an argument intended to be a
6248   // string has type 'char [6]' is probably more confusing than 'char *'.
6249   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6250     if (ICE->getCastKind() == CK_IntegralCast ||
6251         ICE->getCastKind() == CK_FloatingCast) {
6252       E = ICE->getSubExpr();
6253       ExprTy = E->getType();
6254 
6255       // Check if we didn't match because of an implicit cast from a 'char'
6256       // or 'short' to an 'int'.  This is done because printf is a varargs
6257       // function.
6258       if (ICE->getType() == S.Context.IntTy ||
6259           ICE->getType() == S.Context.UnsignedIntTy) {
6260         // All further checking is done on the subexpression.
6261         if (AT.matchesType(S.Context, ExprTy))
6262           return true;
6263       }
6264     }
6265   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6266     // Special case for 'a', which has type 'int' in C.
6267     // Note, however, that we do /not/ want to treat multibyte constants like
6268     // 'MooV' as characters! This form is deprecated but still exists.
6269     if (ExprTy == S.Context.IntTy)
6270       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6271         ExprTy = S.Context.CharTy;
6272   }
6273 
6274   // Look through enums to their underlying type.
6275   bool IsEnum = false;
6276   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6277     ExprTy = EnumTy->getDecl()->getIntegerType();
6278     IsEnum = true;
6279   }
6280 
6281   // %C in an Objective-C context prints a unichar, not a wchar_t.
6282   // If the argument is an integer of some kind, believe the %C and suggest
6283   // a cast instead of changing the conversion specifier.
6284   QualType IntendedTy = ExprTy;
6285   if (isObjCContext() &&
6286       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6287     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6288         !ExprTy->isCharType()) {
6289       // 'unichar' is defined as a typedef of unsigned short, but we should
6290       // prefer using the typedef if it is visible.
6291       IntendedTy = S.Context.UnsignedShortTy;
6292 
6293       // While we are here, check if the value is an IntegerLiteral that happens
6294       // to be within the valid range.
6295       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6296         const llvm::APInt &V = IL->getValue();
6297         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6298           return true;
6299       }
6300 
6301       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6302                           Sema::LookupOrdinaryName);
6303       if (S.LookupName(Result, S.getCurScope())) {
6304         NamedDecl *ND = Result.getFoundDecl();
6305         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6306           if (TD->getUnderlyingType() == IntendedTy)
6307             IntendedTy = S.Context.getTypedefType(TD);
6308       }
6309     }
6310   }
6311 
6312   // Special-case some of Darwin's platform-independence types by suggesting
6313   // casts to primitive types that are known to be large enough.
6314   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6315   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6316     QualType CastTy;
6317     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6318     if (!CastTy.isNull()) {
6319       IntendedTy = CastTy;
6320       ShouldNotPrintDirectly = true;
6321     }
6322   }
6323 
6324   // We may be able to offer a FixItHint if it is a supported type.
6325   PrintfSpecifier fixedFS = FS;
6326   bool success =
6327       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6328 
6329   if (success) {
6330     // Get the fix string from the fixed format specifier
6331     SmallString<16> buf;
6332     llvm::raw_svector_ostream os(buf);
6333     fixedFS.toString(os);
6334 
6335     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6336 
6337     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6338       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6339       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6340         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6341       }
6342       // In this case, the specifier is wrong and should be changed to match
6343       // the argument.
6344       EmitFormatDiagnostic(S.PDiag(diag)
6345                                << AT.getRepresentativeTypeName(S.Context)
6346                                << IntendedTy << IsEnum << E->getSourceRange(),
6347                            E->getLocStart(),
6348                            /*IsStringLocation*/ false, SpecRange,
6349                            FixItHint::CreateReplacement(SpecRange, os.str()));
6350     } else {
6351       // The canonical type for formatting this value is different from the
6352       // actual type of the expression. (This occurs, for example, with Darwin's
6353       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6354       // should be printed as 'long' for 64-bit compatibility.)
6355       // Rather than emitting a normal format/argument mismatch, we want to
6356       // add a cast to the recommended type (and correct the format string
6357       // if necessary).
6358       SmallString<16> CastBuf;
6359       llvm::raw_svector_ostream CastFix(CastBuf);
6360       CastFix << "(";
6361       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6362       CastFix << ")";
6363 
6364       SmallVector<FixItHint,4> Hints;
6365       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6366         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6367 
6368       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6369         // If there's already a cast present, just replace it.
6370         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6371         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6372 
6373       } else if (!requiresParensToAddCast(E)) {
6374         // If the expression has high enough precedence,
6375         // just write the C-style cast.
6376         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6377                                                    CastFix.str()));
6378       } else {
6379         // Otherwise, add parens around the expression as well as the cast.
6380         CastFix << "(";
6381         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6382                                                    CastFix.str()));
6383 
6384         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6385         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6386       }
6387 
6388       if (ShouldNotPrintDirectly) {
6389         // The expression has a type that should not be printed directly.
6390         // We extract the name from the typedef because we don't want to show
6391         // the underlying type in the diagnostic.
6392         StringRef Name;
6393         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6394           Name = TypedefTy->getDecl()->getName();
6395         else
6396           Name = CastTyName;
6397         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6398                                << Name << IntendedTy << IsEnum
6399                                << E->getSourceRange(),
6400                              E->getLocStart(), /*IsStringLocation=*/false,
6401                              SpecRange, Hints);
6402       } else {
6403         // In this case, the expression could be printed using a different
6404         // specifier, but we've decided that the specifier is probably correct
6405         // and we should cast instead. Just use the normal warning message.
6406         EmitFormatDiagnostic(
6407           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6408             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6409             << E->getSourceRange(),
6410           E->getLocStart(), /*IsStringLocation*/false,
6411           SpecRange, Hints);
6412       }
6413     }
6414   } else {
6415     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6416                                                    SpecifierLen);
6417     // Since the warning for passing non-POD types to variadic functions
6418     // was deferred until now, we emit a warning for non-POD
6419     // arguments here.
6420     switch (S.isValidVarArgType(ExprTy)) {
6421     case Sema::VAK_Valid:
6422     case Sema::VAK_ValidInCXX11: {
6423       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6424       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6425         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6426       }
6427 
6428       EmitFormatDiagnostic(
6429           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6430                         << IsEnum << CSR << E->getSourceRange(),
6431           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6432       break;
6433     }
6434     case Sema::VAK_Undefined:
6435     case Sema::VAK_MSVCUndefined:
6436       EmitFormatDiagnostic(
6437         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6438           << S.getLangOpts().CPlusPlus11
6439           << ExprTy
6440           << CallType
6441           << AT.getRepresentativeTypeName(S.Context)
6442           << CSR
6443           << E->getSourceRange(),
6444         E->getLocStart(), /*IsStringLocation*/false, CSR);
6445       checkForCStrMembers(AT, E);
6446       break;
6447 
6448     case Sema::VAK_Invalid:
6449       if (ExprTy->isObjCObjectType())
6450         EmitFormatDiagnostic(
6451           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6452             << S.getLangOpts().CPlusPlus11
6453             << ExprTy
6454             << CallType
6455             << AT.getRepresentativeTypeName(S.Context)
6456             << CSR
6457             << E->getSourceRange(),
6458           E->getLocStart(), /*IsStringLocation*/false, CSR);
6459       else
6460         // FIXME: If this is an initializer list, suggest removing the braces
6461         // or inserting a cast to the target type.
6462         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6463           << isa<InitListExpr>(E) << ExprTy << CallType
6464           << AT.getRepresentativeTypeName(S.Context)
6465           << E->getSourceRange();
6466       break;
6467     }
6468 
6469     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6470            "format string specifier index out of range");
6471     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6472   }
6473 
6474   return true;
6475 }
6476 
6477 //===--- CHECK: Scanf format string checking ------------------------------===//
6478 
6479 namespace {
6480 class CheckScanfHandler : public CheckFormatHandler {
6481 public:
6482   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6483                     const Expr *origFormatExpr, Sema::FormatStringType type,
6484                     unsigned firstDataArg, unsigned numDataArgs,
6485                     const char *beg, bool hasVAListArg,
6486                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6487                     bool inFunctionCall, Sema::VariadicCallType CallType,
6488                     llvm::SmallBitVector &CheckedVarArgs,
6489                     UncoveredArgHandler &UncoveredArg)
6490       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6491                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6492                            inFunctionCall, CallType, CheckedVarArgs,
6493                            UncoveredArg) {}
6494 
6495   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6496                             const char *startSpecifier,
6497                             unsigned specifierLen) override;
6498 
6499   bool HandleInvalidScanfConversionSpecifier(
6500           const analyze_scanf::ScanfSpecifier &FS,
6501           const char *startSpecifier,
6502           unsigned specifierLen) override;
6503 
6504   void HandleIncompleteScanList(const char *start, const char *end) override;
6505 };
6506 } // end anonymous namespace
6507 
6508 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6509                                                  const char *end) {
6510   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6511                        getLocationOfByte(end), /*IsStringLocation*/true,
6512                        getSpecifierRange(start, end - start));
6513 }
6514 
6515 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6516                                         const analyze_scanf::ScanfSpecifier &FS,
6517                                         const char *startSpecifier,
6518                                         unsigned specifierLen) {
6519 
6520   const analyze_scanf::ScanfConversionSpecifier &CS =
6521     FS.getConversionSpecifier();
6522 
6523   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6524                                           getLocationOfByte(CS.getStart()),
6525                                           startSpecifier, specifierLen,
6526                                           CS.getStart(), CS.getLength());
6527 }
6528 
6529 bool CheckScanfHandler::HandleScanfSpecifier(
6530                                        const analyze_scanf::ScanfSpecifier &FS,
6531                                        const char *startSpecifier,
6532                                        unsigned specifierLen) {
6533   using namespace analyze_scanf;
6534   using namespace analyze_format_string;
6535 
6536   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6537 
6538   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6539   // be used to decide if we are using positional arguments consistently.
6540   if (FS.consumesDataArgument()) {
6541     if (atFirstArg) {
6542       atFirstArg = false;
6543       usesPositionalArgs = FS.usesPositionalArg();
6544     }
6545     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6546       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6547                                         startSpecifier, specifierLen);
6548       return false;
6549     }
6550   }
6551 
6552   // Check if the field with is non-zero.
6553   const OptionalAmount &Amt = FS.getFieldWidth();
6554   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6555     if (Amt.getConstantAmount() == 0) {
6556       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6557                                                    Amt.getConstantLength());
6558       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6559                            getLocationOfByte(Amt.getStart()),
6560                            /*IsStringLocation*/true, R,
6561                            FixItHint::CreateRemoval(R));
6562     }
6563   }
6564 
6565   if (!FS.consumesDataArgument()) {
6566     // FIXME: Technically specifying a precision or field width here
6567     // makes no sense.  Worth issuing a warning at some point.
6568     return true;
6569   }
6570 
6571   // Consume the argument.
6572   unsigned argIndex = FS.getArgIndex();
6573   if (argIndex < NumDataArgs) {
6574       // The check to see if the argIndex is valid will come later.
6575       // We set the bit here because we may exit early from this
6576       // function if we encounter some other error.
6577     CoveredArgs.set(argIndex);
6578   }
6579 
6580   // Check the length modifier is valid with the given conversion specifier.
6581   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6582     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6583                                 diag::warn_format_nonsensical_length);
6584   else if (!FS.hasStandardLengthModifier())
6585     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6586   else if (!FS.hasStandardLengthConversionCombination())
6587     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6588                                 diag::warn_format_non_standard_conversion_spec);
6589 
6590   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6591     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6592 
6593   // The remaining checks depend on the data arguments.
6594   if (HasVAListArg)
6595     return true;
6596 
6597   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6598     return false;
6599 
6600   // Check that the argument type matches the format specifier.
6601   const Expr *Ex = getDataArg(argIndex);
6602   if (!Ex)
6603     return true;
6604 
6605   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6606 
6607   if (!AT.isValid()) {
6608     return true;
6609   }
6610 
6611   analyze_format_string::ArgType::MatchKind match =
6612       AT.matchesType(S.Context, Ex->getType());
6613   if (match == analyze_format_string::ArgType::Match) {
6614     return true;
6615   }
6616 
6617   ScanfSpecifier fixedFS = FS;
6618   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6619                                  S.getLangOpts(), S.Context);
6620 
6621   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6622   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6623     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6624   }
6625 
6626   if (success) {
6627     // Get the fix string from the fixed format specifier.
6628     SmallString<128> buf;
6629     llvm::raw_svector_ostream os(buf);
6630     fixedFS.toString(os);
6631 
6632     EmitFormatDiagnostic(
6633         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6634                       << Ex->getType() << false << Ex->getSourceRange(),
6635         Ex->getLocStart(),
6636         /*IsStringLocation*/ false,
6637         getSpecifierRange(startSpecifier, specifierLen),
6638         FixItHint::CreateReplacement(
6639             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6640   } else {
6641     EmitFormatDiagnostic(S.PDiag(diag)
6642                              << AT.getRepresentativeTypeName(S.Context)
6643                              << Ex->getType() << false << Ex->getSourceRange(),
6644                          Ex->getLocStart(),
6645                          /*IsStringLocation*/ false,
6646                          getSpecifierRange(startSpecifier, specifierLen));
6647   }
6648 
6649   return true;
6650 }
6651 
6652 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6653                               const Expr *OrigFormatExpr,
6654                               ArrayRef<const Expr *> Args,
6655                               bool HasVAListArg, unsigned format_idx,
6656                               unsigned firstDataArg,
6657                               Sema::FormatStringType Type,
6658                               bool inFunctionCall,
6659                               Sema::VariadicCallType CallType,
6660                               llvm::SmallBitVector &CheckedVarArgs,
6661                               UncoveredArgHandler &UncoveredArg) {
6662   // CHECK: is the format string a wide literal?
6663   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6664     CheckFormatHandler::EmitFormatDiagnostic(
6665       S, inFunctionCall, Args[format_idx],
6666       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6667       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6668     return;
6669   }
6670 
6671   // Str - The format string.  NOTE: this is NOT null-terminated!
6672   StringRef StrRef = FExpr->getString();
6673   const char *Str = StrRef.data();
6674   // Account for cases where the string literal is truncated in a declaration.
6675   const ConstantArrayType *T =
6676     S.Context.getAsConstantArrayType(FExpr->getType());
6677   assert(T && "String literal not of constant array type!");
6678   size_t TypeSize = T->getSize().getZExtValue();
6679   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6680   const unsigned numDataArgs = Args.size() - firstDataArg;
6681 
6682   // Emit a warning if the string literal is truncated and does not contain an
6683   // embedded null character.
6684   if (TypeSize <= StrRef.size() &&
6685       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6686     CheckFormatHandler::EmitFormatDiagnostic(
6687         S, inFunctionCall, Args[format_idx],
6688         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6689         FExpr->getLocStart(),
6690         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6691     return;
6692   }
6693 
6694   // CHECK: empty format string?
6695   if (StrLen == 0 && numDataArgs > 0) {
6696     CheckFormatHandler::EmitFormatDiagnostic(
6697       S, inFunctionCall, Args[format_idx],
6698       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6699       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6700     return;
6701   }
6702 
6703   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6704       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6705       Type == Sema::FST_OSTrace) {
6706     CheckPrintfHandler H(
6707         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6708         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6709         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6710         CheckedVarArgs, UncoveredArg);
6711 
6712     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6713                                                   S.getLangOpts(),
6714                                                   S.Context.getTargetInfo(),
6715                                             Type == Sema::FST_FreeBSDKPrintf))
6716       H.DoneProcessing();
6717   } else if (Type == Sema::FST_Scanf) {
6718     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6719                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6720                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6721 
6722     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6723                                                  S.getLangOpts(),
6724                                                  S.Context.getTargetInfo()))
6725       H.DoneProcessing();
6726   } // TODO: handle other formats
6727 }
6728 
6729 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6730   // Str - The format string.  NOTE: this is NOT null-terminated!
6731   StringRef StrRef = FExpr->getString();
6732   const char *Str = StrRef.data();
6733   // Account for cases where the string literal is truncated in a declaration.
6734   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6735   assert(T && "String literal not of constant array type!");
6736   size_t TypeSize = T->getSize().getZExtValue();
6737   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6738   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6739                                                          getLangOpts(),
6740                                                          Context.getTargetInfo());
6741 }
6742 
6743 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6744 
6745 // Returns the related absolute value function that is larger, of 0 if one
6746 // does not exist.
6747 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6748   switch (AbsFunction) {
6749   default:
6750     return 0;
6751 
6752   case Builtin::BI__builtin_abs:
6753     return Builtin::BI__builtin_labs;
6754   case Builtin::BI__builtin_labs:
6755     return Builtin::BI__builtin_llabs;
6756   case Builtin::BI__builtin_llabs:
6757     return 0;
6758 
6759   case Builtin::BI__builtin_fabsf:
6760     return Builtin::BI__builtin_fabs;
6761   case Builtin::BI__builtin_fabs:
6762     return Builtin::BI__builtin_fabsl;
6763   case Builtin::BI__builtin_fabsl:
6764     return 0;
6765 
6766   case Builtin::BI__builtin_cabsf:
6767     return Builtin::BI__builtin_cabs;
6768   case Builtin::BI__builtin_cabs:
6769     return Builtin::BI__builtin_cabsl;
6770   case Builtin::BI__builtin_cabsl:
6771     return 0;
6772 
6773   case Builtin::BIabs:
6774     return Builtin::BIlabs;
6775   case Builtin::BIlabs:
6776     return Builtin::BIllabs;
6777   case Builtin::BIllabs:
6778     return 0;
6779 
6780   case Builtin::BIfabsf:
6781     return Builtin::BIfabs;
6782   case Builtin::BIfabs:
6783     return Builtin::BIfabsl;
6784   case Builtin::BIfabsl:
6785     return 0;
6786 
6787   case Builtin::BIcabsf:
6788    return Builtin::BIcabs;
6789   case Builtin::BIcabs:
6790     return Builtin::BIcabsl;
6791   case Builtin::BIcabsl:
6792     return 0;
6793   }
6794 }
6795 
6796 // Returns the argument type of the absolute value function.
6797 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6798                                              unsigned AbsType) {
6799   if (AbsType == 0)
6800     return QualType();
6801 
6802   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6803   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6804   if (Error != ASTContext::GE_None)
6805     return QualType();
6806 
6807   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6808   if (!FT)
6809     return QualType();
6810 
6811   if (FT->getNumParams() != 1)
6812     return QualType();
6813 
6814   return FT->getParamType(0);
6815 }
6816 
6817 // Returns the best absolute value function, or zero, based on type and
6818 // current absolute value function.
6819 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6820                                    unsigned AbsFunctionKind) {
6821   unsigned BestKind = 0;
6822   uint64_t ArgSize = Context.getTypeSize(ArgType);
6823   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6824        Kind = getLargerAbsoluteValueFunction(Kind)) {
6825     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6826     if (Context.getTypeSize(ParamType) >= ArgSize) {
6827       if (BestKind == 0)
6828         BestKind = Kind;
6829       else if (Context.hasSameType(ParamType, ArgType)) {
6830         BestKind = Kind;
6831         break;
6832       }
6833     }
6834   }
6835   return BestKind;
6836 }
6837 
6838 enum AbsoluteValueKind {
6839   AVK_Integer,
6840   AVK_Floating,
6841   AVK_Complex
6842 };
6843 
6844 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6845   if (T->isIntegralOrEnumerationType())
6846     return AVK_Integer;
6847   if (T->isRealFloatingType())
6848     return AVK_Floating;
6849   if (T->isAnyComplexType())
6850     return AVK_Complex;
6851 
6852   llvm_unreachable("Type not integer, floating, or complex");
6853 }
6854 
6855 // Changes the absolute value function to a different type.  Preserves whether
6856 // the function is a builtin.
6857 static unsigned changeAbsFunction(unsigned AbsKind,
6858                                   AbsoluteValueKind ValueKind) {
6859   switch (ValueKind) {
6860   case AVK_Integer:
6861     switch (AbsKind) {
6862     default:
6863       return 0;
6864     case Builtin::BI__builtin_fabsf:
6865     case Builtin::BI__builtin_fabs:
6866     case Builtin::BI__builtin_fabsl:
6867     case Builtin::BI__builtin_cabsf:
6868     case Builtin::BI__builtin_cabs:
6869     case Builtin::BI__builtin_cabsl:
6870       return Builtin::BI__builtin_abs;
6871     case Builtin::BIfabsf:
6872     case Builtin::BIfabs:
6873     case Builtin::BIfabsl:
6874     case Builtin::BIcabsf:
6875     case Builtin::BIcabs:
6876     case Builtin::BIcabsl:
6877       return Builtin::BIabs;
6878     }
6879   case AVK_Floating:
6880     switch (AbsKind) {
6881     default:
6882       return 0;
6883     case Builtin::BI__builtin_abs:
6884     case Builtin::BI__builtin_labs:
6885     case Builtin::BI__builtin_llabs:
6886     case Builtin::BI__builtin_cabsf:
6887     case Builtin::BI__builtin_cabs:
6888     case Builtin::BI__builtin_cabsl:
6889       return Builtin::BI__builtin_fabsf;
6890     case Builtin::BIabs:
6891     case Builtin::BIlabs:
6892     case Builtin::BIllabs:
6893     case Builtin::BIcabsf:
6894     case Builtin::BIcabs:
6895     case Builtin::BIcabsl:
6896       return Builtin::BIfabsf;
6897     }
6898   case AVK_Complex:
6899     switch (AbsKind) {
6900     default:
6901       return 0;
6902     case Builtin::BI__builtin_abs:
6903     case Builtin::BI__builtin_labs:
6904     case Builtin::BI__builtin_llabs:
6905     case Builtin::BI__builtin_fabsf:
6906     case Builtin::BI__builtin_fabs:
6907     case Builtin::BI__builtin_fabsl:
6908       return Builtin::BI__builtin_cabsf;
6909     case Builtin::BIabs:
6910     case Builtin::BIlabs:
6911     case Builtin::BIllabs:
6912     case Builtin::BIfabsf:
6913     case Builtin::BIfabs:
6914     case Builtin::BIfabsl:
6915       return Builtin::BIcabsf;
6916     }
6917   }
6918   llvm_unreachable("Unable to convert function");
6919 }
6920 
6921 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6922   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6923   if (!FnInfo)
6924     return 0;
6925 
6926   switch (FDecl->getBuiltinID()) {
6927   default:
6928     return 0;
6929   case Builtin::BI__builtin_abs:
6930   case Builtin::BI__builtin_fabs:
6931   case Builtin::BI__builtin_fabsf:
6932   case Builtin::BI__builtin_fabsl:
6933   case Builtin::BI__builtin_labs:
6934   case Builtin::BI__builtin_llabs:
6935   case Builtin::BI__builtin_cabs:
6936   case Builtin::BI__builtin_cabsf:
6937   case Builtin::BI__builtin_cabsl:
6938   case Builtin::BIabs:
6939   case Builtin::BIlabs:
6940   case Builtin::BIllabs:
6941   case Builtin::BIfabs:
6942   case Builtin::BIfabsf:
6943   case Builtin::BIfabsl:
6944   case Builtin::BIcabs:
6945   case Builtin::BIcabsf:
6946   case Builtin::BIcabsl:
6947     return FDecl->getBuiltinID();
6948   }
6949   llvm_unreachable("Unknown Builtin type");
6950 }
6951 
6952 // If the replacement is valid, emit a note with replacement function.
6953 // Additionally, suggest including the proper header if not already included.
6954 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6955                             unsigned AbsKind, QualType ArgType) {
6956   bool EmitHeaderHint = true;
6957   const char *HeaderName = nullptr;
6958   const char *FunctionName = nullptr;
6959   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6960     FunctionName = "std::abs";
6961     if (ArgType->isIntegralOrEnumerationType()) {
6962       HeaderName = "cstdlib";
6963     } else if (ArgType->isRealFloatingType()) {
6964       HeaderName = "cmath";
6965     } else {
6966       llvm_unreachable("Invalid Type");
6967     }
6968 
6969     // Lookup all std::abs
6970     if (NamespaceDecl *Std = S.getStdNamespace()) {
6971       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6972       R.suppressDiagnostics();
6973       S.LookupQualifiedName(R, Std);
6974 
6975       for (const auto *I : R) {
6976         const FunctionDecl *FDecl = nullptr;
6977         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6978           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6979         } else {
6980           FDecl = dyn_cast<FunctionDecl>(I);
6981         }
6982         if (!FDecl)
6983           continue;
6984 
6985         // Found std::abs(), check that they are the right ones.
6986         if (FDecl->getNumParams() != 1)
6987           continue;
6988 
6989         // Check that the parameter type can handle the argument.
6990         QualType ParamType = FDecl->getParamDecl(0)->getType();
6991         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6992             S.Context.getTypeSize(ArgType) <=
6993                 S.Context.getTypeSize(ParamType)) {
6994           // Found a function, don't need the header hint.
6995           EmitHeaderHint = false;
6996           break;
6997         }
6998       }
6999     }
7000   } else {
7001     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
7002     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
7003 
7004     if (HeaderName) {
7005       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7006       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7007       R.suppressDiagnostics();
7008       S.LookupName(R, S.getCurScope());
7009 
7010       if (R.isSingleResult()) {
7011         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7012         if (FD && FD->getBuiltinID() == AbsKind) {
7013           EmitHeaderHint = false;
7014         } else {
7015           return;
7016         }
7017       } else if (!R.empty()) {
7018         return;
7019       }
7020     }
7021   }
7022 
7023   S.Diag(Loc, diag::note_replace_abs_function)
7024       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7025 
7026   if (!HeaderName)
7027     return;
7028 
7029   if (!EmitHeaderHint)
7030     return;
7031 
7032   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7033                                                     << FunctionName;
7034 }
7035 
7036 template <std::size_t StrLen>
7037 static bool IsStdFunction(const FunctionDecl *FDecl,
7038                           const char (&Str)[StrLen]) {
7039   if (!FDecl)
7040     return false;
7041   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7042     return false;
7043   if (!FDecl->isInStdNamespace())
7044     return false;
7045 
7046   return true;
7047 }
7048 
7049 // Warn when using the wrong abs() function.
7050 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7051                                       const FunctionDecl *FDecl) {
7052   if (Call->getNumArgs() != 1)
7053     return;
7054 
7055   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7056   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7057   if (AbsKind == 0 && !IsStdAbs)
7058     return;
7059 
7060   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7061   QualType ParamType = Call->getArg(0)->getType();
7062 
7063   // Unsigned types cannot be negative.  Suggest removing the absolute value
7064   // function call.
7065   if (ArgType->isUnsignedIntegerType()) {
7066     const char *FunctionName =
7067         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7068     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7069     Diag(Call->getExprLoc(), diag::note_remove_abs)
7070         << FunctionName
7071         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7072     return;
7073   }
7074 
7075   // Taking the absolute value of a pointer is very suspicious, they probably
7076   // wanted to index into an array, dereference a pointer, call a function, etc.
7077   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7078     unsigned DiagType = 0;
7079     if (ArgType->isFunctionType())
7080       DiagType = 1;
7081     else if (ArgType->isArrayType())
7082       DiagType = 2;
7083 
7084     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7085     return;
7086   }
7087 
7088   // std::abs has overloads which prevent most of the absolute value problems
7089   // from occurring.
7090   if (IsStdAbs)
7091     return;
7092 
7093   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7094   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7095 
7096   // The argument and parameter are the same kind.  Check if they are the right
7097   // size.
7098   if (ArgValueKind == ParamValueKind) {
7099     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7100       return;
7101 
7102     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7103     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7104         << FDecl << ArgType << ParamType;
7105 
7106     if (NewAbsKind == 0)
7107       return;
7108 
7109     emitReplacement(*this, Call->getExprLoc(),
7110                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7111     return;
7112   }
7113 
7114   // ArgValueKind != ParamValueKind
7115   // The wrong type of absolute value function was used.  Attempt to find the
7116   // proper one.
7117   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7118   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7119   if (NewAbsKind == 0)
7120     return;
7121 
7122   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7123       << FDecl << ParamValueKind << ArgValueKind;
7124 
7125   emitReplacement(*this, Call->getExprLoc(),
7126                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7127 }
7128 
7129 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7130 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7131                                 const FunctionDecl *FDecl) {
7132   if (!Call || !FDecl) return;
7133 
7134   // Ignore template specializations and macros.
7135   if (inTemplateInstantiation()) return;
7136   if (Call->getExprLoc().isMacroID()) return;
7137 
7138   // Only care about the one template argument, two function parameter std::max
7139   if (Call->getNumArgs() != 2) return;
7140   if (!IsStdFunction(FDecl, "max")) return;
7141   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7142   if (!ArgList) return;
7143   if (ArgList->size() != 1) return;
7144 
7145   // Check that template type argument is unsigned integer.
7146   const auto& TA = ArgList->get(0);
7147   if (TA.getKind() != TemplateArgument::Type) return;
7148   QualType ArgType = TA.getAsType();
7149   if (!ArgType->isUnsignedIntegerType()) return;
7150 
7151   // See if either argument is a literal zero.
7152   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7153     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7154     if (!MTE) return false;
7155     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7156     if (!Num) return false;
7157     if (Num->getValue() != 0) return false;
7158     return true;
7159   };
7160 
7161   const Expr *FirstArg = Call->getArg(0);
7162   const Expr *SecondArg = Call->getArg(1);
7163   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7164   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7165 
7166   // Only warn when exactly one argument is zero.
7167   if (IsFirstArgZero == IsSecondArgZero) return;
7168 
7169   SourceRange FirstRange = FirstArg->getSourceRange();
7170   SourceRange SecondRange = SecondArg->getSourceRange();
7171 
7172   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7173 
7174   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7175       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7176 
7177   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7178   SourceRange RemovalRange;
7179   if (IsFirstArgZero) {
7180     RemovalRange = SourceRange(FirstRange.getBegin(),
7181                                SecondRange.getBegin().getLocWithOffset(-1));
7182   } else {
7183     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7184                                SecondRange.getEnd());
7185   }
7186 
7187   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7188         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7189         << FixItHint::CreateRemoval(RemovalRange);
7190 }
7191 
7192 //===--- CHECK: Standard memory functions ---------------------------------===//
7193 
7194 /// \brief Takes the expression passed to the size_t parameter of functions
7195 /// such as memcmp, strncat, etc and warns if it's a comparison.
7196 ///
7197 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7198 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7199                                            IdentifierInfo *FnName,
7200                                            SourceLocation FnLoc,
7201                                            SourceLocation RParenLoc) {
7202   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7203   if (!Size)
7204     return false;
7205 
7206   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7207   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7208     return false;
7209 
7210   SourceRange SizeRange = Size->getSourceRange();
7211   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7212       << SizeRange << FnName;
7213   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7214       << FnName << FixItHint::CreateInsertion(
7215                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7216       << FixItHint::CreateRemoval(RParenLoc);
7217   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7218       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7219       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7220                                     ")");
7221 
7222   return true;
7223 }
7224 
7225 /// \brief Determine whether the given type is or contains a dynamic class type
7226 /// (e.g., whether it has a vtable).
7227 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7228                                                      bool &IsContained) {
7229   // Look through array types while ignoring qualifiers.
7230   const Type *Ty = T->getBaseElementTypeUnsafe();
7231   IsContained = false;
7232 
7233   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7234   RD = RD ? RD->getDefinition() : nullptr;
7235   if (!RD || RD->isInvalidDecl())
7236     return nullptr;
7237 
7238   if (RD->isDynamicClass())
7239     return RD;
7240 
7241   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7242   // It's impossible for a class to transitively contain itself by value, so
7243   // infinite recursion is impossible.
7244   for (auto *FD : RD->fields()) {
7245     bool SubContained;
7246     if (const CXXRecordDecl *ContainedRD =
7247             getContainedDynamicClass(FD->getType(), SubContained)) {
7248       IsContained = true;
7249       return ContainedRD;
7250     }
7251   }
7252 
7253   return nullptr;
7254 }
7255 
7256 /// \brief If E is a sizeof expression, returns its argument expression,
7257 /// otherwise returns NULL.
7258 static const Expr *getSizeOfExprArg(const Expr *E) {
7259   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7260       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7261     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7262       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7263 
7264   return nullptr;
7265 }
7266 
7267 /// \brief If E is a sizeof expression, returns its argument type.
7268 static QualType getSizeOfArgType(const Expr *E) {
7269   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7270       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7271     if (SizeOf->getKind() == clang::UETT_SizeOf)
7272       return SizeOf->getTypeOfArgument();
7273 
7274   return QualType();
7275 }
7276 
7277 /// \brief Check for dangerous or invalid arguments to memset().
7278 ///
7279 /// This issues warnings on known problematic, dangerous or unspecified
7280 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7281 /// function calls.
7282 ///
7283 /// \param Call The call expression to diagnose.
7284 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7285                                    unsigned BId,
7286                                    IdentifierInfo *FnName) {
7287   assert(BId != 0);
7288 
7289   // It is possible to have a non-standard definition of memset.  Validate
7290   // we have enough arguments, and if not, abort further checking.
7291   unsigned ExpectedNumArgs =
7292       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7293   if (Call->getNumArgs() < ExpectedNumArgs)
7294     return;
7295 
7296   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7297                       BId == Builtin::BIstrndup ? 1 : 2);
7298   unsigned LenArg =
7299       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7300   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7301 
7302   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7303                                      Call->getLocStart(), Call->getRParenLoc()))
7304     return;
7305 
7306   // We have special checking when the length is a sizeof expression.
7307   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7308   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7309   llvm::FoldingSetNodeID SizeOfArgID;
7310 
7311   // Although widely used, 'bzero' is not a standard function. Be more strict
7312   // with the argument types before allowing diagnostics and only allow the
7313   // form bzero(ptr, sizeof(...)).
7314   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7315   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7316     return;
7317 
7318   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7319     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7320     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7321 
7322     QualType DestTy = Dest->getType();
7323     QualType PointeeTy;
7324     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7325       PointeeTy = DestPtrTy->getPointeeType();
7326 
7327       // Never warn about void type pointers. This can be used to suppress
7328       // false positives.
7329       if (PointeeTy->isVoidType())
7330         continue;
7331 
7332       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7333       // actually comparing the expressions for equality. Because computing the
7334       // expression IDs can be expensive, we only do this if the diagnostic is
7335       // enabled.
7336       if (SizeOfArg &&
7337           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7338                            SizeOfArg->getExprLoc())) {
7339         // We only compute IDs for expressions if the warning is enabled, and
7340         // cache the sizeof arg's ID.
7341         if (SizeOfArgID == llvm::FoldingSetNodeID())
7342           SizeOfArg->Profile(SizeOfArgID, Context, true);
7343         llvm::FoldingSetNodeID DestID;
7344         Dest->Profile(DestID, Context, true);
7345         if (DestID == SizeOfArgID) {
7346           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7347           //       over sizeof(src) as well.
7348           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7349           StringRef ReadableName = FnName->getName();
7350 
7351           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7352             if (UnaryOp->getOpcode() == UO_AddrOf)
7353               ActionIdx = 1; // If its an address-of operator, just remove it.
7354           if (!PointeeTy->isIncompleteType() &&
7355               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7356             ActionIdx = 2; // If the pointee's size is sizeof(char),
7357                            // suggest an explicit length.
7358 
7359           // If the function is defined as a builtin macro, do not show macro
7360           // expansion.
7361           SourceLocation SL = SizeOfArg->getExprLoc();
7362           SourceRange DSR = Dest->getSourceRange();
7363           SourceRange SSR = SizeOfArg->getSourceRange();
7364           SourceManager &SM = getSourceManager();
7365 
7366           if (SM.isMacroArgExpansion(SL)) {
7367             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7368             SL = SM.getSpellingLoc(SL);
7369             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7370                              SM.getSpellingLoc(DSR.getEnd()));
7371             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7372                              SM.getSpellingLoc(SSR.getEnd()));
7373           }
7374 
7375           DiagRuntimeBehavior(SL, SizeOfArg,
7376                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7377                                 << ReadableName
7378                                 << PointeeTy
7379                                 << DestTy
7380                                 << DSR
7381                                 << SSR);
7382           DiagRuntimeBehavior(SL, SizeOfArg,
7383                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7384                                 << ActionIdx
7385                                 << SSR);
7386 
7387           break;
7388         }
7389       }
7390 
7391       // Also check for cases where the sizeof argument is the exact same
7392       // type as the memory argument, and where it points to a user-defined
7393       // record type.
7394       if (SizeOfArgTy != QualType()) {
7395         if (PointeeTy->isRecordType() &&
7396             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7397           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7398                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7399                                 << FnName << SizeOfArgTy << ArgIdx
7400                                 << PointeeTy << Dest->getSourceRange()
7401                                 << LenExpr->getSourceRange());
7402           break;
7403         }
7404       }
7405     } else if (DestTy->isArrayType()) {
7406       PointeeTy = DestTy;
7407     }
7408 
7409     if (PointeeTy == QualType())
7410       continue;
7411 
7412     // Always complain about dynamic classes.
7413     bool IsContained;
7414     if (const CXXRecordDecl *ContainedRD =
7415             getContainedDynamicClass(PointeeTy, IsContained)) {
7416 
7417       unsigned OperationType = 0;
7418       // "overwritten" if we're warning about the destination for any call
7419       // but memcmp; otherwise a verb appropriate to the call.
7420       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7421         if (BId == Builtin::BImemcpy)
7422           OperationType = 1;
7423         else if(BId == Builtin::BImemmove)
7424           OperationType = 2;
7425         else if (BId == Builtin::BImemcmp)
7426           OperationType = 3;
7427       }
7428 
7429       DiagRuntimeBehavior(
7430         Dest->getExprLoc(), Dest,
7431         PDiag(diag::warn_dyn_class_memaccess)
7432           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7433           << FnName << IsContained << ContainedRD << OperationType
7434           << Call->getCallee()->getSourceRange());
7435     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7436              BId != Builtin::BImemset)
7437       DiagRuntimeBehavior(
7438         Dest->getExprLoc(), Dest,
7439         PDiag(diag::warn_arc_object_memaccess)
7440           << ArgIdx << FnName << PointeeTy
7441           << Call->getCallee()->getSourceRange());
7442     else
7443       continue;
7444 
7445     DiagRuntimeBehavior(
7446       Dest->getExprLoc(), Dest,
7447       PDiag(diag::note_bad_memaccess_silence)
7448         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7449     break;
7450   }
7451 }
7452 
7453 // A little helper routine: ignore addition and subtraction of integer literals.
7454 // This intentionally does not ignore all integer constant expressions because
7455 // we don't want to remove sizeof().
7456 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7457   Ex = Ex->IgnoreParenCasts();
7458 
7459   for (;;) {
7460     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7461     if (!BO || !BO->isAdditiveOp())
7462       break;
7463 
7464     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7465     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7466 
7467     if (isa<IntegerLiteral>(RHS))
7468       Ex = LHS;
7469     else if (isa<IntegerLiteral>(LHS))
7470       Ex = RHS;
7471     else
7472       break;
7473   }
7474 
7475   return Ex;
7476 }
7477 
7478 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7479                                                       ASTContext &Context) {
7480   // Only handle constant-sized or VLAs, but not flexible members.
7481   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7482     // Only issue the FIXIT for arrays of size > 1.
7483     if (CAT->getSize().getSExtValue() <= 1)
7484       return false;
7485   } else if (!Ty->isVariableArrayType()) {
7486     return false;
7487   }
7488   return true;
7489 }
7490 
7491 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7492 // be the size of the source, instead of the destination.
7493 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7494                                     IdentifierInfo *FnName) {
7495 
7496   // Don't crash if the user has the wrong number of arguments
7497   unsigned NumArgs = Call->getNumArgs();
7498   if ((NumArgs != 3) && (NumArgs != 4))
7499     return;
7500 
7501   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7502   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7503   const Expr *CompareWithSrc = nullptr;
7504 
7505   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7506                                      Call->getLocStart(), Call->getRParenLoc()))
7507     return;
7508 
7509   // Look for 'strlcpy(dst, x, sizeof(x))'
7510   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7511     CompareWithSrc = Ex;
7512   else {
7513     // Look for 'strlcpy(dst, x, strlen(x))'
7514     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7515       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7516           SizeCall->getNumArgs() == 1)
7517         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7518     }
7519   }
7520 
7521   if (!CompareWithSrc)
7522     return;
7523 
7524   // Determine if the argument to sizeof/strlen is equal to the source
7525   // argument.  In principle there's all kinds of things you could do
7526   // here, for instance creating an == expression and evaluating it with
7527   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7528   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7529   if (!SrcArgDRE)
7530     return;
7531 
7532   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7533   if (!CompareWithSrcDRE ||
7534       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7535     return;
7536 
7537   const Expr *OriginalSizeArg = Call->getArg(2);
7538   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7539     << OriginalSizeArg->getSourceRange() << FnName;
7540 
7541   // Output a FIXIT hint if the destination is an array (rather than a
7542   // pointer to an array).  This could be enhanced to handle some
7543   // pointers if we know the actual size, like if DstArg is 'array+2'
7544   // we could say 'sizeof(array)-2'.
7545   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7546   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7547     return;
7548 
7549   SmallString<128> sizeString;
7550   llvm::raw_svector_ostream OS(sizeString);
7551   OS << "sizeof(";
7552   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7553   OS << ")";
7554 
7555   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7556     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7557                                     OS.str());
7558 }
7559 
7560 /// Check if two expressions refer to the same declaration.
7561 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7562   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7563     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7564       return D1->getDecl() == D2->getDecl();
7565   return false;
7566 }
7567 
7568 static const Expr *getStrlenExprArg(const Expr *E) {
7569   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7570     const FunctionDecl *FD = CE->getDirectCallee();
7571     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7572       return nullptr;
7573     return CE->getArg(0)->IgnoreParenCasts();
7574   }
7575   return nullptr;
7576 }
7577 
7578 // Warn on anti-patterns as the 'size' argument to strncat.
7579 // The correct size argument should look like following:
7580 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7581 void Sema::CheckStrncatArguments(const CallExpr *CE,
7582                                  IdentifierInfo *FnName) {
7583   // Don't crash if the user has the wrong number of arguments.
7584   if (CE->getNumArgs() < 3)
7585     return;
7586   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7587   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7588   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7589 
7590   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7591                                      CE->getRParenLoc()))
7592     return;
7593 
7594   // Identify common expressions, which are wrongly used as the size argument
7595   // to strncat and may lead to buffer overflows.
7596   unsigned PatternType = 0;
7597   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7598     // - sizeof(dst)
7599     if (referToTheSameDecl(SizeOfArg, DstArg))
7600       PatternType = 1;
7601     // - sizeof(src)
7602     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7603       PatternType = 2;
7604   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7605     if (BE->getOpcode() == BO_Sub) {
7606       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7607       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7608       // - sizeof(dst) - strlen(dst)
7609       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7610           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7611         PatternType = 1;
7612       // - sizeof(src) - (anything)
7613       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7614         PatternType = 2;
7615     }
7616   }
7617 
7618   if (PatternType == 0)
7619     return;
7620 
7621   // Generate the diagnostic.
7622   SourceLocation SL = LenArg->getLocStart();
7623   SourceRange SR = LenArg->getSourceRange();
7624   SourceManager &SM = getSourceManager();
7625 
7626   // If the function is defined as a builtin macro, do not show macro expansion.
7627   if (SM.isMacroArgExpansion(SL)) {
7628     SL = SM.getSpellingLoc(SL);
7629     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7630                      SM.getSpellingLoc(SR.getEnd()));
7631   }
7632 
7633   // Check if the destination is an array (rather than a pointer to an array).
7634   QualType DstTy = DstArg->getType();
7635   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7636                                                                     Context);
7637   if (!isKnownSizeArray) {
7638     if (PatternType == 1)
7639       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7640     else
7641       Diag(SL, diag::warn_strncat_src_size) << SR;
7642     return;
7643   }
7644 
7645   if (PatternType == 1)
7646     Diag(SL, diag::warn_strncat_large_size) << SR;
7647   else
7648     Diag(SL, diag::warn_strncat_src_size) << SR;
7649 
7650   SmallString<128> sizeString;
7651   llvm::raw_svector_ostream OS(sizeString);
7652   OS << "sizeof(";
7653   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7654   OS << ") - ";
7655   OS << "strlen(";
7656   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7657   OS << ") - 1";
7658 
7659   Diag(SL, diag::note_strncat_wrong_size)
7660     << FixItHint::CreateReplacement(SR, OS.str());
7661 }
7662 
7663 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7664 
7665 static const Expr *EvalVal(const Expr *E,
7666                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7667                            const Decl *ParentDecl);
7668 static const Expr *EvalAddr(const Expr *E,
7669                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7670                             const Decl *ParentDecl);
7671 
7672 /// CheckReturnStackAddr - Check if a return statement returns the address
7673 ///   of a stack variable.
7674 static void
7675 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7676                      SourceLocation ReturnLoc) {
7677 
7678   const Expr *stackE = nullptr;
7679   SmallVector<const DeclRefExpr *, 8> refVars;
7680 
7681   // Perform checking for returned stack addresses, local blocks,
7682   // label addresses or references to temporaries.
7683   if (lhsType->isPointerType() ||
7684       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7685     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7686   } else if (lhsType->isReferenceType()) {
7687     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7688   }
7689 
7690   if (!stackE)
7691     return; // Nothing suspicious was found.
7692 
7693   // Parameters are initialized in the calling scope, so taking the address
7694   // of a parameter reference doesn't need a warning.
7695   for (auto *DRE : refVars)
7696     if (isa<ParmVarDecl>(DRE->getDecl()))
7697       return;
7698 
7699   SourceLocation diagLoc;
7700   SourceRange diagRange;
7701   if (refVars.empty()) {
7702     diagLoc = stackE->getLocStart();
7703     diagRange = stackE->getSourceRange();
7704   } else {
7705     // We followed through a reference variable. 'stackE' contains the
7706     // problematic expression but we will warn at the return statement pointing
7707     // at the reference variable. We will later display the "trail" of
7708     // reference variables using notes.
7709     diagLoc = refVars[0]->getLocStart();
7710     diagRange = refVars[0]->getSourceRange();
7711   }
7712 
7713   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7714     // address of local var
7715     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7716      << DR->getDecl()->getDeclName() << diagRange;
7717   } else if (isa<BlockExpr>(stackE)) { // local block.
7718     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7719   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7720     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7721   } else { // local temporary.
7722     // If there is an LValue->RValue conversion, then the value of the
7723     // reference type is used, not the reference.
7724     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7725       if (ICE->getCastKind() == CK_LValueToRValue) {
7726         return;
7727       }
7728     }
7729     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7730      << lhsType->isReferenceType() << diagRange;
7731   }
7732 
7733   // Display the "trail" of reference variables that we followed until we
7734   // found the problematic expression using notes.
7735   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7736     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7737     // If this var binds to another reference var, show the range of the next
7738     // var, otherwise the var binds to the problematic expression, in which case
7739     // show the range of the expression.
7740     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7741                                     : stackE->getSourceRange();
7742     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7743         << VD->getDeclName() << range;
7744   }
7745 }
7746 
7747 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7748 ///  check if the expression in a return statement evaluates to an address
7749 ///  to a location on the stack, a local block, an address of a label, or a
7750 ///  reference to local temporary. The recursion is used to traverse the
7751 ///  AST of the return expression, with recursion backtracking when we
7752 ///  encounter a subexpression that (1) clearly does not lead to one of the
7753 ///  above problematic expressions (2) is something we cannot determine leads to
7754 ///  a problematic expression based on such local checking.
7755 ///
7756 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7757 ///  the expression that they point to. Such variables are added to the
7758 ///  'refVars' vector so that we know what the reference variable "trail" was.
7759 ///
7760 ///  EvalAddr processes expressions that are pointers that are used as
7761 ///  references (and not L-values).  EvalVal handles all other values.
7762 ///  At the base case of the recursion is a check for the above problematic
7763 ///  expressions.
7764 ///
7765 ///  This implementation handles:
7766 ///
7767 ///   * pointer-to-pointer casts
7768 ///   * implicit conversions from array references to pointers
7769 ///   * taking the address of fields
7770 ///   * arbitrary interplay between "&" and "*" operators
7771 ///   * pointer arithmetic from an address of a stack variable
7772 ///   * taking the address of an array element where the array is on the stack
7773 static const Expr *EvalAddr(const Expr *E,
7774                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7775                             const Decl *ParentDecl) {
7776   if (E->isTypeDependent())
7777     return nullptr;
7778 
7779   // We should only be called for evaluating pointer expressions.
7780   assert((E->getType()->isAnyPointerType() ||
7781           E->getType()->isBlockPointerType() ||
7782           E->getType()->isObjCQualifiedIdType()) &&
7783          "EvalAddr only works on pointers");
7784 
7785   E = E->IgnoreParens();
7786 
7787   // Our "symbolic interpreter" is just a dispatch off the currently
7788   // viewed AST node.  We then recursively traverse the AST by calling
7789   // EvalAddr and EvalVal appropriately.
7790   switch (E->getStmtClass()) {
7791   case Stmt::DeclRefExprClass: {
7792     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7793 
7794     // If we leave the immediate function, the lifetime isn't about to end.
7795     if (DR->refersToEnclosingVariableOrCapture())
7796       return nullptr;
7797 
7798     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7799       // If this is a reference variable, follow through to the expression that
7800       // it points to.
7801       if (V->hasLocalStorage() &&
7802           V->getType()->isReferenceType() && V->hasInit()) {
7803         // Add the reference variable to the "trail".
7804         refVars.push_back(DR);
7805         return EvalAddr(V->getInit(), refVars, ParentDecl);
7806       }
7807 
7808     return nullptr;
7809   }
7810 
7811   case Stmt::UnaryOperatorClass: {
7812     // The only unary operator that make sense to handle here
7813     // is AddrOf.  All others don't make sense as pointers.
7814     const UnaryOperator *U = cast<UnaryOperator>(E);
7815 
7816     if (U->getOpcode() == UO_AddrOf)
7817       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7818     return nullptr;
7819   }
7820 
7821   case Stmt::BinaryOperatorClass: {
7822     // Handle pointer arithmetic.  All other binary operators are not valid
7823     // in this context.
7824     const BinaryOperator *B = cast<BinaryOperator>(E);
7825     BinaryOperatorKind op = B->getOpcode();
7826 
7827     if (op != BO_Add && op != BO_Sub)
7828       return nullptr;
7829 
7830     const Expr *Base = B->getLHS();
7831 
7832     // Determine which argument is the real pointer base.  It could be
7833     // the RHS argument instead of the LHS.
7834     if (!Base->getType()->isPointerType())
7835       Base = B->getRHS();
7836 
7837     assert(Base->getType()->isPointerType());
7838     return EvalAddr(Base, refVars, ParentDecl);
7839   }
7840 
7841   // For conditional operators we need to see if either the LHS or RHS are
7842   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7843   case Stmt::ConditionalOperatorClass: {
7844     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7845 
7846     // Handle the GNU extension for missing LHS.
7847     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7848     if (const Expr *LHSExpr = C->getLHS()) {
7849       // In C++, we can have a throw-expression, which has 'void' type.
7850       if (!LHSExpr->getType()->isVoidType())
7851         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7852           return LHS;
7853     }
7854 
7855     // In C++, we can have a throw-expression, which has 'void' type.
7856     if (C->getRHS()->getType()->isVoidType())
7857       return nullptr;
7858 
7859     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7860   }
7861 
7862   case Stmt::BlockExprClass:
7863     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7864       return E; // local block.
7865     return nullptr;
7866 
7867   case Stmt::AddrLabelExprClass:
7868     return E; // address of label.
7869 
7870   case Stmt::ExprWithCleanupsClass:
7871     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7872                     ParentDecl);
7873 
7874   // For casts, we need to handle conversions from arrays to
7875   // pointer values, and pointer-to-pointer conversions.
7876   case Stmt::ImplicitCastExprClass:
7877   case Stmt::CStyleCastExprClass:
7878   case Stmt::CXXFunctionalCastExprClass:
7879   case Stmt::ObjCBridgedCastExprClass:
7880   case Stmt::CXXStaticCastExprClass:
7881   case Stmt::CXXDynamicCastExprClass:
7882   case Stmt::CXXConstCastExprClass:
7883   case Stmt::CXXReinterpretCastExprClass: {
7884     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7885     switch (cast<CastExpr>(E)->getCastKind()) {
7886     case CK_LValueToRValue:
7887     case CK_NoOp:
7888     case CK_BaseToDerived:
7889     case CK_DerivedToBase:
7890     case CK_UncheckedDerivedToBase:
7891     case CK_Dynamic:
7892     case CK_CPointerToObjCPointerCast:
7893     case CK_BlockPointerToObjCPointerCast:
7894     case CK_AnyPointerToBlockPointerCast:
7895       return EvalAddr(SubExpr, refVars, ParentDecl);
7896 
7897     case CK_ArrayToPointerDecay:
7898       return EvalVal(SubExpr, refVars, ParentDecl);
7899 
7900     case CK_BitCast:
7901       if (SubExpr->getType()->isAnyPointerType() ||
7902           SubExpr->getType()->isBlockPointerType() ||
7903           SubExpr->getType()->isObjCQualifiedIdType())
7904         return EvalAddr(SubExpr, refVars, ParentDecl);
7905       else
7906         return nullptr;
7907 
7908     default:
7909       return nullptr;
7910     }
7911   }
7912 
7913   case Stmt::MaterializeTemporaryExprClass:
7914     if (const Expr *Result =
7915             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7916                      refVars, ParentDecl))
7917       return Result;
7918     return E;
7919 
7920   // Everything else: we simply don't reason about them.
7921   default:
7922     return nullptr;
7923   }
7924 }
7925 
7926 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7927 ///   See the comments for EvalAddr for more details.
7928 static const Expr *EvalVal(const Expr *E,
7929                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7930                            const Decl *ParentDecl) {
7931   do {
7932     // We should only be called for evaluating non-pointer expressions, or
7933     // expressions with a pointer type that are not used as references but
7934     // instead
7935     // are l-values (e.g., DeclRefExpr with a pointer type).
7936 
7937     // Our "symbolic interpreter" is just a dispatch off the currently
7938     // viewed AST node.  We then recursively traverse the AST by calling
7939     // EvalAddr and EvalVal appropriately.
7940 
7941     E = E->IgnoreParens();
7942     switch (E->getStmtClass()) {
7943     case Stmt::ImplicitCastExprClass: {
7944       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7945       if (IE->getValueKind() == VK_LValue) {
7946         E = IE->getSubExpr();
7947         continue;
7948       }
7949       return nullptr;
7950     }
7951 
7952     case Stmt::ExprWithCleanupsClass:
7953       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7954                      ParentDecl);
7955 
7956     case Stmt::DeclRefExprClass: {
7957       // When we hit a DeclRefExpr we are looking at code that refers to a
7958       // variable's name. If it's not a reference variable we check if it has
7959       // local storage within the function, and if so, return the expression.
7960       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7961 
7962       // If we leave the immediate function, the lifetime isn't about to end.
7963       if (DR->refersToEnclosingVariableOrCapture())
7964         return nullptr;
7965 
7966       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7967         // Check if it refers to itself, e.g. "int& i = i;".
7968         if (V == ParentDecl)
7969           return DR;
7970 
7971         if (V->hasLocalStorage()) {
7972           if (!V->getType()->isReferenceType())
7973             return DR;
7974 
7975           // Reference variable, follow through to the expression that
7976           // it points to.
7977           if (V->hasInit()) {
7978             // Add the reference variable to the "trail".
7979             refVars.push_back(DR);
7980             return EvalVal(V->getInit(), refVars, V);
7981           }
7982         }
7983       }
7984 
7985       return nullptr;
7986     }
7987 
7988     case Stmt::UnaryOperatorClass: {
7989       // The only unary operator that make sense to handle here
7990       // is Deref.  All others don't resolve to a "name."  This includes
7991       // handling all sorts of rvalues passed to a unary operator.
7992       const UnaryOperator *U = cast<UnaryOperator>(E);
7993 
7994       if (U->getOpcode() == UO_Deref)
7995         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7996 
7997       return nullptr;
7998     }
7999 
8000     case Stmt::ArraySubscriptExprClass: {
8001       // Array subscripts are potential references to data on the stack.  We
8002       // retrieve the DeclRefExpr* for the array variable if it indeed
8003       // has local storage.
8004       const auto *ASE = cast<ArraySubscriptExpr>(E);
8005       if (ASE->isTypeDependent())
8006         return nullptr;
8007       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8008     }
8009 
8010     case Stmt::OMPArraySectionExprClass: {
8011       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8012                       ParentDecl);
8013     }
8014 
8015     case Stmt::ConditionalOperatorClass: {
8016       // For conditional operators we need to see if either the LHS or RHS are
8017       // non-NULL Expr's.  If one is non-NULL, we return it.
8018       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8019 
8020       // Handle the GNU extension for missing LHS.
8021       if (const Expr *LHSExpr = C->getLHS()) {
8022         // In C++, we can have a throw-expression, which has 'void' type.
8023         if (!LHSExpr->getType()->isVoidType())
8024           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8025             return LHS;
8026       }
8027 
8028       // In C++, we can have a throw-expression, which has 'void' type.
8029       if (C->getRHS()->getType()->isVoidType())
8030         return nullptr;
8031 
8032       return EvalVal(C->getRHS(), refVars, ParentDecl);
8033     }
8034 
8035     // Accesses to members are potential references to data on the stack.
8036     case Stmt::MemberExprClass: {
8037       const MemberExpr *M = cast<MemberExpr>(E);
8038 
8039       // Check for indirect access.  We only want direct field accesses.
8040       if (M->isArrow())
8041         return nullptr;
8042 
8043       // Check whether the member type is itself a reference, in which case
8044       // we're not going to refer to the member, but to what the member refers
8045       // to.
8046       if (M->getMemberDecl()->getType()->isReferenceType())
8047         return nullptr;
8048 
8049       return EvalVal(M->getBase(), refVars, ParentDecl);
8050     }
8051 
8052     case Stmt::MaterializeTemporaryExprClass:
8053       if (const Expr *Result =
8054               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8055                       refVars, ParentDecl))
8056         return Result;
8057       return E;
8058 
8059     default:
8060       // Check that we don't return or take the address of a reference to a
8061       // temporary. This is only useful in C++.
8062       if (!E->isTypeDependent() && E->isRValue())
8063         return E;
8064 
8065       // Everything else: we simply don't reason about them.
8066       return nullptr;
8067     }
8068   } while (true);
8069 }
8070 
8071 void
8072 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8073                          SourceLocation ReturnLoc,
8074                          bool isObjCMethod,
8075                          const AttrVec *Attrs,
8076                          const FunctionDecl *FD) {
8077   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8078 
8079   // Check if the return value is null but should not be.
8080   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8081        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8082       CheckNonNullExpr(*this, RetValExp))
8083     Diag(ReturnLoc, diag::warn_null_ret)
8084       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8085 
8086   // C++11 [basic.stc.dynamic.allocation]p4:
8087   //   If an allocation function declared with a non-throwing
8088   //   exception-specification fails to allocate storage, it shall return
8089   //   a null pointer. Any other allocation function that fails to allocate
8090   //   storage shall indicate failure only by throwing an exception [...]
8091   if (FD) {
8092     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8093     if (Op == OO_New || Op == OO_Array_New) {
8094       const FunctionProtoType *Proto
8095         = FD->getType()->castAs<FunctionProtoType>();
8096       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8097           CheckNonNullExpr(*this, RetValExp))
8098         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8099           << FD << getLangOpts().CPlusPlus11;
8100     }
8101   }
8102 }
8103 
8104 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8105 
8106 /// Check for comparisons of floating point operands using != and ==.
8107 /// Issue a warning if these are no self-comparisons, as they are not likely
8108 /// to do what the programmer intended.
8109 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8110   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8111   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8112 
8113   // Special case: check for x == x (which is OK).
8114   // Do not emit warnings for such cases.
8115   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8116     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8117       if (DRL->getDecl() == DRR->getDecl())
8118         return;
8119 
8120   // Special case: check for comparisons against literals that can be exactly
8121   //  represented by APFloat.  In such cases, do not emit a warning.  This
8122   //  is a heuristic: often comparison against such literals are used to
8123   //  detect if a value in a variable has not changed.  This clearly can
8124   //  lead to false negatives.
8125   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8126     if (FLL->isExact())
8127       return;
8128   } else
8129     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8130       if (FLR->isExact())
8131         return;
8132 
8133   // Check for comparisons with builtin types.
8134   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8135     if (CL->getBuiltinCallee())
8136       return;
8137 
8138   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8139     if (CR->getBuiltinCallee())
8140       return;
8141 
8142   // Emit the diagnostic.
8143   Diag(Loc, diag::warn_floatingpoint_eq)
8144     << LHS->getSourceRange() << RHS->getSourceRange();
8145 }
8146 
8147 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8148 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8149 
8150 namespace {
8151 
8152 /// Structure recording the 'active' range of an integer-valued
8153 /// expression.
8154 struct IntRange {
8155   /// The number of bits active in the int.
8156   unsigned Width;
8157 
8158   /// True if the int is known not to have negative values.
8159   bool NonNegative;
8160 
8161   IntRange(unsigned Width, bool NonNegative)
8162     : Width(Width), NonNegative(NonNegative)
8163   {}
8164 
8165   /// Returns the range of the bool type.
8166   static IntRange forBoolType() {
8167     return IntRange(1, true);
8168   }
8169 
8170   /// Returns the range of an opaque value of the given integral type.
8171   static IntRange forValueOfType(ASTContext &C, QualType T) {
8172     return forValueOfCanonicalType(C,
8173                           T->getCanonicalTypeInternal().getTypePtr());
8174   }
8175 
8176   /// Returns the range of an opaque value of a canonical integral type.
8177   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8178     assert(T->isCanonicalUnqualified());
8179 
8180     if (const VectorType *VT = dyn_cast<VectorType>(T))
8181       T = VT->getElementType().getTypePtr();
8182     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8183       T = CT->getElementType().getTypePtr();
8184     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8185       T = AT->getValueType().getTypePtr();
8186 
8187     if (!C.getLangOpts().CPlusPlus) {
8188       // For enum types in C code, use the underlying datatype.
8189       if (const EnumType *ET = dyn_cast<EnumType>(T))
8190         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
8191     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8192       // For enum types in C++, use the known bit width of the enumerators.
8193       EnumDecl *Enum = ET->getDecl();
8194       // In C++11, enums without definitions can have an explicitly specified
8195       // underlying type.  Use this type to compute the range.
8196       if (!Enum->isCompleteDefinition())
8197         return IntRange(C.getIntWidth(QualType(T, 0)),
8198                         !ET->isSignedIntegerOrEnumerationType());
8199 
8200       unsigned NumPositive = Enum->getNumPositiveBits();
8201       unsigned NumNegative = Enum->getNumNegativeBits();
8202 
8203       if (NumNegative == 0)
8204         return IntRange(NumPositive, true/*NonNegative*/);
8205       else
8206         return IntRange(std::max(NumPositive + 1, NumNegative),
8207                         false/*NonNegative*/);
8208     }
8209 
8210     const BuiltinType *BT = cast<BuiltinType>(T);
8211     assert(BT->isInteger());
8212 
8213     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8214   }
8215 
8216   /// Returns the "target" range of a canonical integral type, i.e.
8217   /// the range of values expressible in the type.
8218   ///
8219   /// This matches forValueOfCanonicalType except that enums have the
8220   /// full range of their type, not the range of their enumerators.
8221   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8222     assert(T->isCanonicalUnqualified());
8223 
8224     if (const VectorType *VT = dyn_cast<VectorType>(T))
8225       T = VT->getElementType().getTypePtr();
8226     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8227       T = CT->getElementType().getTypePtr();
8228     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8229       T = AT->getValueType().getTypePtr();
8230     if (const EnumType *ET = dyn_cast<EnumType>(T))
8231       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8232 
8233     const BuiltinType *BT = cast<BuiltinType>(T);
8234     assert(BT->isInteger());
8235 
8236     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8237   }
8238 
8239   /// Returns the supremum of two ranges: i.e. their conservative merge.
8240   static IntRange join(IntRange L, IntRange R) {
8241     return IntRange(std::max(L.Width, R.Width),
8242                     L.NonNegative && R.NonNegative);
8243   }
8244 
8245   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8246   static IntRange meet(IntRange L, IntRange R) {
8247     return IntRange(std::min(L.Width, R.Width),
8248                     L.NonNegative || R.NonNegative);
8249   }
8250 };
8251 
8252 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8253   if (value.isSigned() && value.isNegative())
8254     return IntRange(value.getMinSignedBits(), false);
8255 
8256   if (value.getBitWidth() > MaxWidth)
8257     value = value.trunc(MaxWidth);
8258 
8259   // isNonNegative() just checks the sign bit without considering
8260   // signedness.
8261   return IntRange(value.getActiveBits(), true);
8262 }
8263 
8264 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8265                        unsigned MaxWidth) {
8266   if (result.isInt())
8267     return GetValueRange(C, result.getInt(), MaxWidth);
8268 
8269   if (result.isVector()) {
8270     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8271     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8272       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8273       R = IntRange::join(R, El);
8274     }
8275     return R;
8276   }
8277 
8278   if (result.isComplexInt()) {
8279     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8280     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8281     return IntRange::join(R, I);
8282   }
8283 
8284   // This can happen with lossless casts to intptr_t of "based" lvalues.
8285   // Assume it might use arbitrary bits.
8286   // FIXME: The only reason we need to pass the type in here is to get
8287   // the sign right on this one case.  It would be nice if APValue
8288   // preserved this.
8289   assert(result.isLValue() || result.isAddrLabelDiff());
8290   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8291 }
8292 
8293 QualType GetExprType(const Expr *E) {
8294   QualType Ty = E->getType();
8295   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8296     Ty = AtomicRHS->getValueType();
8297   return Ty;
8298 }
8299 
8300 /// Pseudo-evaluate the given integer expression, estimating the
8301 /// range of values it might take.
8302 ///
8303 /// \param MaxWidth - the width to which the value will be truncated
8304 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8305   E = E->IgnoreParens();
8306 
8307   // Try a full evaluation first.
8308   Expr::EvalResult result;
8309   if (E->EvaluateAsRValue(result, C))
8310     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8311 
8312   // I think we only want to look through implicit casts here; if the
8313   // user has an explicit widening cast, we should treat the value as
8314   // being of the new, wider type.
8315   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8316     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8317       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8318 
8319     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8320 
8321     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8322                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8323 
8324     // Assume that non-integer casts can span the full range of the type.
8325     if (!isIntegerCast)
8326       return OutputTypeRange;
8327 
8328     IntRange SubRange
8329       = GetExprRange(C, CE->getSubExpr(),
8330                      std::min(MaxWidth, OutputTypeRange.Width));
8331 
8332     // Bail out if the subexpr's range is as wide as the cast type.
8333     if (SubRange.Width >= OutputTypeRange.Width)
8334       return OutputTypeRange;
8335 
8336     // Otherwise, we take the smaller width, and we're non-negative if
8337     // either the output type or the subexpr is.
8338     return IntRange(SubRange.Width,
8339                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8340   }
8341 
8342   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8343     // If we can fold the condition, just take that operand.
8344     bool CondResult;
8345     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8346       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8347                                         : CO->getFalseExpr(),
8348                           MaxWidth);
8349 
8350     // Otherwise, conservatively merge.
8351     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8352     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8353     return IntRange::join(L, R);
8354   }
8355 
8356   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8357     switch (BO->getOpcode()) {
8358 
8359     // Boolean-valued operations are single-bit and positive.
8360     case BO_LAnd:
8361     case BO_LOr:
8362     case BO_LT:
8363     case BO_GT:
8364     case BO_LE:
8365     case BO_GE:
8366     case BO_EQ:
8367     case BO_NE:
8368       return IntRange::forBoolType();
8369 
8370     // The type of the assignments is the type of the LHS, so the RHS
8371     // is not necessarily the same type.
8372     case BO_MulAssign:
8373     case BO_DivAssign:
8374     case BO_RemAssign:
8375     case BO_AddAssign:
8376     case BO_SubAssign:
8377     case BO_XorAssign:
8378     case BO_OrAssign:
8379       // TODO: bitfields?
8380       return IntRange::forValueOfType(C, GetExprType(E));
8381 
8382     // Simple assignments just pass through the RHS, which will have
8383     // been coerced to the LHS type.
8384     case BO_Assign:
8385       // TODO: bitfields?
8386       return GetExprRange(C, BO->getRHS(), MaxWidth);
8387 
8388     // Operations with opaque sources are black-listed.
8389     case BO_PtrMemD:
8390     case BO_PtrMemI:
8391       return IntRange::forValueOfType(C, GetExprType(E));
8392 
8393     // Bitwise-and uses the *infinum* of the two source ranges.
8394     case BO_And:
8395     case BO_AndAssign:
8396       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8397                             GetExprRange(C, BO->getRHS(), MaxWidth));
8398 
8399     // Left shift gets black-listed based on a judgement call.
8400     case BO_Shl:
8401       // ...except that we want to treat '1 << (blah)' as logically
8402       // positive.  It's an important idiom.
8403       if (IntegerLiteral *I
8404             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8405         if (I->getValue() == 1) {
8406           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8407           return IntRange(R.Width, /*NonNegative*/ true);
8408         }
8409       }
8410       // fallthrough
8411 
8412     case BO_ShlAssign:
8413       return IntRange::forValueOfType(C, GetExprType(E));
8414 
8415     // Right shift by a constant can narrow its left argument.
8416     case BO_Shr:
8417     case BO_ShrAssign: {
8418       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8419 
8420       // If the shift amount is a positive constant, drop the width by
8421       // that much.
8422       llvm::APSInt shift;
8423       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8424           shift.isNonNegative()) {
8425         unsigned zext = shift.getZExtValue();
8426         if (zext >= L.Width)
8427           L.Width = (L.NonNegative ? 0 : 1);
8428         else
8429           L.Width -= zext;
8430       }
8431 
8432       return L;
8433     }
8434 
8435     // Comma acts as its right operand.
8436     case BO_Comma:
8437       return GetExprRange(C, BO->getRHS(), MaxWidth);
8438 
8439     // Black-list pointer subtractions.
8440     case BO_Sub:
8441       if (BO->getLHS()->getType()->isPointerType())
8442         return IntRange::forValueOfType(C, GetExprType(E));
8443       break;
8444 
8445     // The width of a division result is mostly determined by the size
8446     // of the LHS.
8447     case BO_Div: {
8448       // Don't 'pre-truncate' the operands.
8449       unsigned opWidth = C.getIntWidth(GetExprType(E));
8450       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8451 
8452       // If the divisor is constant, use that.
8453       llvm::APSInt divisor;
8454       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8455         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8456         if (log2 >= L.Width)
8457           L.Width = (L.NonNegative ? 0 : 1);
8458         else
8459           L.Width = std::min(L.Width - log2, MaxWidth);
8460         return L;
8461       }
8462 
8463       // Otherwise, just use the LHS's width.
8464       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8465       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8466     }
8467 
8468     // The result of a remainder can't be larger than the result of
8469     // either side.
8470     case BO_Rem: {
8471       // Don't 'pre-truncate' the operands.
8472       unsigned opWidth = C.getIntWidth(GetExprType(E));
8473       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8474       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8475 
8476       IntRange meet = IntRange::meet(L, R);
8477       meet.Width = std::min(meet.Width, MaxWidth);
8478       return meet;
8479     }
8480 
8481     // The default behavior is okay for these.
8482     case BO_Mul:
8483     case BO_Add:
8484     case BO_Xor:
8485     case BO_Or:
8486       break;
8487     }
8488 
8489     // The default case is to treat the operation as if it were closed
8490     // on the narrowest type that encompasses both operands.
8491     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8492     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8493     return IntRange::join(L, R);
8494   }
8495 
8496   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8497     switch (UO->getOpcode()) {
8498     // Boolean-valued operations are white-listed.
8499     case UO_LNot:
8500       return IntRange::forBoolType();
8501 
8502     // Operations with opaque sources are black-listed.
8503     case UO_Deref:
8504     case UO_AddrOf: // should be impossible
8505       return IntRange::forValueOfType(C, GetExprType(E));
8506 
8507     default:
8508       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8509     }
8510   }
8511 
8512   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8513     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8514 
8515   if (const auto *BitField = E->getSourceBitField())
8516     return IntRange(BitField->getBitWidthValue(C),
8517                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8518 
8519   return IntRange::forValueOfType(C, GetExprType(E));
8520 }
8521 
8522 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8523   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8524 }
8525 
8526 /// Checks whether the given value, which currently has the given
8527 /// source semantics, has the same value when coerced through the
8528 /// target semantics.
8529 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8530                           const llvm::fltSemantics &Src,
8531                           const llvm::fltSemantics &Tgt) {
8532   llvm::APFloat truncated = value;
8533 
8534   bool ignored;
8535   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8536   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8537 
8538   return truncated.bitwiseIsEqual(value);
8539 }
8540 
8541 /// Checks whether the given value, which currently has the given
8542 /// source semantics, has the same value when coerced through the
8543 /// target semantics.
8544 ///
8545 /// The value might be a vector of floats (or a complex number).
8546 bool IsSameFloatAfterCast(const APValue &value,
8547                           const llvm::fltSemantics &Src,
8548                           const llvm::fltSemantics &Tgt) {
8549   if (value.isFloat())
8550     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8551 
8552   if (value.isVector()) {
8553     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8554       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8555         return false;
8556     return true;
8557   }
8558 
8559   assert(value.isComplexFloat());
8560   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8561           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8562 }
8563 
8564 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8565 
8566 bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
8567   // Suppress cases where we are comparing against an enum constant.
8568   if (const DeclRefExpr *DR =
8569       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8570     if (isa<EnumConstantDecl>(DR->getDecl()))
8571       return true;
8572 
8573   // Suppress cases where the '0' value is expanded from a macro.
8574   if (E->getLocStart().isMacroID())
8575     return true;
8576 
8577   return false;
8578 }
8579 
8580 bool isNonBooleanIntegerValue(Expr *E) {
8581   return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType();
8582 }
8583 
8584 bool isNonBooleanUnsignedValue(Expr *E) {
8585   // We are checking that the expression is not known to have boolean value,
8586   // is an integer type; and is either unsigned after implicit casts,
8587   // or was unsigned before implicit casts.
8588   return isNonBooleanIntegerValue(E) &&
8589          (!E->getType()->isSignedIntegerType() ||
8590           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8591 }
8592 
8593 enum class LimitType {
8594   Max = 1U << 0U,  // e.g. 32767 for short
8595   Min = 1U << 1U,  // e.g. -32768 for short
8596   Both = Max | Min // When the value is both the Min and the Max limit at the
8597                    // same time; e.g. in C++, A::a in enum A { a = 0 };
8598 };
8599 
8600 /// Checks whether Expr 'Constant' may be the
8601 /// std::numeric_limits<>::max() or std::numeric_limits<>::min()
8602 /// of the Expr 'Other'. If true, then returns the limit type (min or max).
8603 /// The Value is the evaluation of Constant
8604 llvm::Optional<LimitType> IsTypeLimit(Sema &S, Expr *Constant, Expr *Other,
8605                                       const llvm::APSInt &Value) {
8606   if (IsEnumConstOrFromMacro(S, Constant))
8607     return llvm::Optional<LimitType>();
8608 
8609   if (isNonBooleanUnsignedValue(Other) && Value == 0)
8610     return LimitType::Min;
8611 
8612   // TODO: Investigate using GetExprRange() to get tighter bounds
8613   // on the bit ranges.
8614   QualType OtherT = Other->IgnoreParenImpCasts()->getType();
8615   if (const auto *AT = OtherT->getAs<AtomicType>())
8616     OtherT = AT->getValueType();
8617 
8618   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8619 
8620   // Special-case for C++ for enum with one enumerator with value of 0.
8621   if (OtherRange.Width == 0)
8622     return Value == 0 ? LimitType::Both : llvm::Optional<LimitType>();
8623 
8624   if (llvm::APSInt::isSameValue(
8625           llvm::APSInt::getMaxValue(OtherRange.Width,
8626                                     OtherT->isUnsignedIntegerType()),
8627           Value))
8628     return LimitType::Max;
8629 
8630   if (llvm::APSInt::isSameValue(
8631           llvm::APSInt::getMinValue(OtherRange.Width,
8632                                     OtherT->isUnsignedIntegerType()),
8633           Value))
8634     return LimitType::Min;
8635 
8636   return llvm::None;
8637 }
8638 
8639 bool HasEnumType(Expr *E) {
8640   // Strip off implicit integral promotions.
8641   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8642     if (ICE->getCastKind() != CK_IntegralCast &&
8643         ICE->getCastKind() != CK_NoOp)
8644       break;
8645     E = ICE->getSubExpr();
8646   }
8647 
8648   return E->getType()->isEnumeralType();
8649 }
8650 
8651 bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8652                                  Expr *Other, const llvm::APSInt &Value,
8653                                  bool RhsConstant) {
8654   // Disable warning in template instantiations
8655   // and only analyze <, >, <= and >= operations.
8656   if (S.inTemplateInstantiation() || !E->isRelationalOp())
8657     return false;
8658 
8659   BinaryOperatorKind Op = E->getOpcode();
8660 
8661   QualType OType = Other->IgnoreParenImpCasts()->getType();
8662 
8663   llvm::Optional<LimitType> ValueType; // Which limit (min/max) is the constant?
8664 
8665   if (!(isNonBooleanIntegerValue(Other) &&
8666         (ValueType = IsTypeLimit(S, Constant, Other, Value))))
8667     return false;
8668 
8669   bool ConstIsLowerBound = (Op == BO_LT || Op == BO_LE) ^ RhsConstant;
8670   bool ResultWhenConstEqualsOther = (Op == BO_LE || Op == BO_GE);
8671   if (ValueType != LimitType::Both) {
8672     bool ResultWhenConstNeOther =
8673         ConstIsLowerBound ^ (ValueType == LimitType::Max);
8674     if (ResultWhenConstEqualsOther != ResultWhenConstNeOther)
8675       return false; // The comparison is not tautological.
8676   } else if (ResultWhenConstEqualsOther == ConstIsLowerBound)
8677     return false; // The comparison is not tautological.
8678 
8679   const bool Result = ResultWhenConstEqualsOther;
8680 
8681   unsigned Diag = (isNonBooleanUnsignedValue(Other) && Value == 0)
8682                       ? (HasEnumType(Other)
8683                              ? diag::warn_unsigned_enum_always_true_comparison
8684                              : diag::warn_unsigned_always_true_comparison)
8685                       : diag::warn_tautological_constant_compare;
8686 
8687   // Should be enough for uint128 (39 decimal digits)
8688   SmallString<64> PrettySourceValue;
8689   llvm::raw_svector_ostream OS(PrettySourceValue);
8690   OS << Value;
8691 
8692   S.Diag(E->getOperatorLoc(), Diag)
8693       << RhsConstant << OType << E->getOpcodeStr() << OS.str() << Result
8694       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
8695 
8696   return true;
8697 }
8698 
8699 bool DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8700                                   Expr *Other, const llvm::APSInt &Value,
8701                                   bool RhsConstant) {
8702   // Disable warning in template instantiations.
8703   if (S.inTemplateInstantiation())
8704     return false;
8705 
8706   Constant = Constant->IgnoreParenImpCasts();
8707   Other = Other->IgnoreParenImpCasts();
8708 
8709   // TODO: Investigate using GetExprRange() to get tighter bounds
8710   // on the bit ranges.
8711   QualType OtherT = Other->getType();
8712   if (const auto *AT = OtherT->getAs<AtomicType>())
8713     OtherT = AT->getValueType();
8714   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8715   unsigned OtherWidth = OtherRange.Width;
8716 
8717   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8718 
8719   BinaryOperatorKind op = E->getOpcode();
8720   bool IsTrue = true;
8721 
8722   // Used for diagnostic printout.
8723   enum {
8724     LiteralConstant = 0,
8725     CXXBoolLiteralTrue,
8726     CXXBoolLiteralFalse
8727   } LiteralOrBoolConstant = LiteralConstant;
8728 
8729   if (!OtherIsBooleanType) {
8730     QualType ConstantT = Constant->getType();
8731     QualType CommonT = E->getLHS()->getType();
8732 
8733     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8734       return false;
8735     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8736            "comparison with non-integer type");
8737 
8738     bool ConstantSigned = ConstantT->isSignedIntegerType();
8739     bool CommonSigned = CommonT->isSignedIntegerType();
8740 
8741     bool EqualityOnly = false;
8742 
8743     if (CommonSigned) {
8744       // The common type is signed, therefore no signed to unsigned conversion.
8745       if (!OtherRange.NonNegative) {
8746         // Check that the constant is representable in type OtherT.
8747         if (ConstantSigned) {
8748           if (OtherWidth >= Value.getMinSignedBits())
8749             return false;
8750         } else { // !ConstantSigned
8751           if (OtherWidth >= Value.getActiveBits() + 1)
8752             return false;
8753         }
8754       } else { // !OtherSigned
8755                // Check that the constant is representable in type OtherT.
8756         // Negative values are out of range.
8757         if (ConstantSigned) {
8758           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8759             return false;
8760         } else { // !ConstantSigned
8761           if (OtherWidth >= Value.getActiveBits())
8762             return false;
8763         }
8764       }
8765     } else { // !CommonSigned
8766       if (OtherRange.NonNegative) {
8767         if (OtherWidth >= Value.getActiveBits())
8768           return false;
8769       } else { // OtherSigned
8770         assert(!ConstantSigned &&
8771                "Two signed types converted to unsigned types.");
8772         // Check to see if the constant is representable in OtherT.
8773         if (OtherWidth > Value.getActiveBits())
8774           return false;
8775         // Check to see if the constant is equivalent to a negative value
8776         // cast to CommonT.
8777         if (S.Context.getIntWidth(ConstantT) ==
8778                 S.Context.getIntWidth(CommonT) &&
8779             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8780           return false;
8781         // The constant value rests between values that OtherT can represent
8782         // after conversion.  Relational comparison still works, but equality
8783         // comparisons will be tautological.
8784         EqualityOnly = true;
8785       }
8786     }
8787 
8788     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8789 
8790     if (op == BO_EQ || op == BO_NE) {
8791       IsTrue = op == BO_NE;
8792     } else if (EqualityOnly) {
8793       return false;
8794     } else if (RhsConstant) {
8795       if (op == BO_GT || op == BO_GE)
8796         IsTrue = !PositiveConstant;
8797       else // op == BO_LT || op == BO_LE
8798         IsTrue = PositiveConstant;
8799     } else {
8800       if (op == BO_LT || op == BO_LE)
8801         IsTrue = !PositiveConstant;
8802       else // op == BO_GT || op == BO_GE
8803         IsTrue = PositiveConstant;
8804     }
8805   } else {
8806     // Other isKnownToHaveBooleanValue
8807     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8808     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8809     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8810 
8811     static const struct LinkedConditions {
8812       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8813       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8814       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8815       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8816       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8817       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8818 
8819     } TruthTable = {
8820         // Constant on LHS.              | Constant on RHS.              |
8821         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8822         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8823         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8824         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8825         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8826         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8827         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8828       };
8829 
8830     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8831 
8832     enum ConstantValue ConstVal = Zero;
8833     if (Value.isUnsigned() || Value.isNonNegative()) {
8834       if (Value == 0) {
8835         LiteralOrBoolConstant =
8836             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8837         ConstVal = Zero;
8838       } else if (Value == 1) {
8839         LiteralOrBoolConstant =
8840             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8841         ConstVal = One;
8842       } else {
8843         LiteralOrBoolConstant = LiteralConstant;
8844         ConstVal = GT_One;
8845       }
8846     } else {
8847       ConstVal = LT_Zero;
8848     }
8849 
8850     CompareBoolWithConstantResult CmpRes;
8851 
8852     switch (op) {
8853     case BO_LT:
8854       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8855       break;
8856     case BO_GT:
8857       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8858       break;
8859     case BO_LE:
8860       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8861       break;
8862     case BO_GE:
8863       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8864       break;
8865     case BO_EQ:
8866       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8867       break;
8868     case BO_NE:
8869       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8870       break;
8871     default:
8872       CmpRes = Unkwn;
8873       break;
8874     }
8875 
8876     if (CmpRes == AFals) {
8877       IsTrue = false;
8878     } else if (CmpRes == ATrue) {
8879       IsTrue = true;
8880     } else {
8881       return false;
8882     }
8883   }
8884 
8885   // If this is a comparison to an enum constant, include that
8886   // constant in the diagnostic.
8887   const EnumConstantDecl *ED = nullptr;
8888   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8889     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8890 
8891   SmallString<64> PrettySourceValue;
8892   llvm::raw_svector_ostream OS(PrettySourceValue);
8893   if (ED)
8894     OS << '\'' << *ED << "' (" << Value << ")";
8895   else
8896     OS << Value;
8897 
8898   S.DiagRuntimeBehavior(
8899     E->getOperatorLoc(), E,
8900     S.PDiag(diag::warn_out_of_range_compare)
8901         << OS.str() << LiteralOrBoolConstant
8902         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8903         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8904 
8905    return true;
8906 }
8907 
8908 /// Analyze the operands of the given comparison.  Implements the
8909 /// fallback case from AnalyzeComparison.
8910 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8911   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8912   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8913 }
8914 
8915 /// \brief Implements -Wsign-compare.
8916 ///
8917 /// \param E the binary operator to check for warnings
8918 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8919   // The type the comparison is being performed in.
8920   QualType T = E->getLHS()->getType();
8921 
8922   // Only analyze comparison operators where both sides have been converted to
8923   // the same type.
8924   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8925     return AnalyzeImpConvsInComparison(S, E);
8926 
8927   // Don't analyze value-dependent comparisons directly.
8928   if (E->isValueDependent())
8929     return AnalyzeImpConvsInComparison(S, E);
8930 
8931   Expr *LHS = E->getLHS();
8932   Expr *RHS = E->getRHS();
8933 
8934   if (T->isIntegralType(S.Context)) {
8935     llvm::APSInt RHSValue;
8936     llvm::APSInt LHSValue;
8937 
8938     bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context);
8939     bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context);
8940 
8941     // We don't care about expressions whose result is a constant.
8942     if (IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8943       return AnalyzeImpConvsInComparison(S, E);
8944 
8945     // We only care about expressions where just one side is literal
8946     if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) {
8947       // Is the constant on the RHS or LHS?
8948       const bool RhsConstant = IsRHSIntegralLiteral;
8949       Expr *Const = RhsConstant ? RHS : LHS;
8950       Expr *Other = RhsConstant ? LHS : RHS;
8951       const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue;
8952 
8953       // Check whether an integer constant comparison results in a value
8954       // of 'true' or 'false'.
8955 
8956       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
8957         return AnalyzeImpConvsInComparison(S, E);
8958 
8959       if (DiagnoseOutOfRangeComparison(S, E, Const, Other, Value, RhsConstant))
8960         return AnalyzeImpConvsInComparison(S, E);
8961     }
8962   }
8963 
8964   if (!T->hasUnsignedIntegerRepresentation()) {
8965     // We don't do anything special if this isn't an unsigned integral
8966     // comparison:  we're only interested in integral comparisons, and
8967     // signed comparisons only happen in cases we don't care to warn about.
8968     return AnalyzeImpConvsInComparison(S, E);
8969   }
8970 
8971   LHS = LHS->IgnoreParenImpCasts();
8972   RHS = RHS->IgnoreParenImpCasts();
8973 
8974   // Check to see if one of the (unmodified) operands is of different
8975   // signedness.
8976   Expr *signedOperand, *unsignedOperand;
8977   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8978     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8979            "unsigned comparison between two signed integer expressions?");
8980     signedOperand = LHS;
8981     unsignedOperand = RHS;
8982   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8983     signedOperand = RHS;
8984     unsignedOperand = LHS;
8985   } else {
8986     return AnalyzeImpConvsInComparison(S, E);
8987   }
8988 
8989   // Otherwise, calculate the effective range of the signed operand.
8990   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8991 
8992   // Go ahead and analyze implicit conversions in the operands.  Note
8993   // that we skip the implicit conversions on both sides.
8994   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8995   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8996 
8997   // If the signed range is non-negative, -Wsign-compare won't fire.
8998   if (signedRange.NonNegative)
8999     return;
9000 
9001   // For (in)equality comparisons, if the unsigned operand is a
9002   // constant which cannot collide with a overflowed signed operand,
9003   // then reinterpreting the signed operand as unsigned will not
9004   // change the result of the comparison.
9005   if (E->isEqualityOp()) {
9006     unsigned comparisonWidth = S.Context.getIntWidth(T);
9007     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
9008 
9009     // We should never be unable to prove that the unsigned operand is
9010     // non-negative.
9011     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
9012 
9013     if (unsignedRange.Width < comparisonWidth)
9014       return;
9015   }
9016 
9017   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
9018     S.PDiag(diag::warn_mixed_sign_comparison)
9019       << LHS->getType() << RHS->getType()
9020       << LHS->getSourceRange() << RHS->getSourceRange());
9021 }
9022 
9023 /// Analyzes an attempt to assign the given value to a bitfield.
9024 ///
9025 /// Returns true if there was something fishy about the attempt.
9026 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
9027                                SourceLocation InitLoc) {
9028   assert(Bitfield->isBitField());
9029   if (Bitfield->isInvalidDecl())
9030     return false;
9031 
9032   // White-list bool bitfields.
9033   QualType BitfieldType = Bitfield->getType();
9034   if (BitfieldType->isBooleanType())
9035      return false;
9036 
9037   if (BitfieldType->isEnumeralType()) {
9038     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
9039     // If the underlying enum type was not explicitly specified as an unsigned
9040     // type and the enum contain only positive values, MSVC++ will cause an
9041     // inconsistency by storing this as a signed type.
9042     if (S.getLangOpts().CPlusPlus11 &&
9043         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
9044         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
9045         BitfieldEnumDecl->getNumNegativeBits() == 0) {
9046       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
9047         << BitfieldEnumDecl->getNameAsString();
9048     }
9049   }
9050 
9051   if (Bitfield->getType()->isBooleanType())
9052     return false;
9053 
9054   // Ignore value- or type-dependent expressions.
9055   if (Bitfield->getBitWidth()->isValueDependent() ||
9056       Bitfield->getBitWidth()->isTypeDependent() ||
9057       Init->isValueDependent() ||
9058       Init->isTypeDependent())
9059     return false;
9060 
9061   Expr *OriginalInit = Init->IgnoreParenImpCasts();
9062   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
9063 
9064   llvm::APSInt Value;
9065   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
9066                                    Expr::SE_AllowSideEffects)) {
9067     // The RHS is not constant.  If the RHS has an enum type, make sure the
9068     // bitfield is wide enough to hold all the values of the enum without
9069     // truncation.
9070     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9071       EnumDecl *ED = EnumTy->getDecl();
9072       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9073 
9074       // Enum types are implicitly signed on Windows, so check if there are any
9075       // negative enumerators to see if the enum was intended to be signed or
9076       // not.
9077       bool SignedEnum = ED->getNumNegativeBits() > 0;
9078 
9079       // Check for surprising sign changes when assigning enum values to a
9080       // bitfield of different signedness.  If the bitfield is signed and we
9081       // have exactly the right number of bits to store this unsigned enum,
9082       // suggest changing the enum to an unsigned type. This typically happens
9083       // on Windows where unfixed enums always use an underlying type of 'int'.
9084       unsigned DiagID = 0;
9085       if (SignedEnum && !SignedBitfield) {
9086         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9087       } else if (SignedBitfield && !SignedEnum &&
9088                  ED->getNumPositiveBits() == FieldWidth) {
9089         DiagID = diag::warn_signed_bitfield_enum_conversion;
9090       }
9091 
9092       if (DiagID) {
9093         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9094         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9095         SourceRange TypeRange =
9096             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9097         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9098             << SignedEnum << TypeRange;
9099       }
9100 
9101       // Compute the required bitwidth. If the enum has negative values, we need
9102       // one more bit than the normal number of positive bits to represent the
9103       // sign bit.
9104       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9105                                                   ED->getNumNegativeBits())
9106                                        : ED->getNumPositiveBits();
9107 
9108       // Check the bitwidth.
9109       if (BitsNeeded > FieldWidth) {
9110         Expr *WidthExpr = Bitfield->getBitWidth();
9111         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9112             << Bitfield << ED;
9113         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9114             << BitsNeeded << ED << WidthExpr->getSourceRange();
9115       }
9116     }
9117 
9118     return false;
9119   }
9120 
9121   unsigned OriginalWidth = Value.getBitWidth();
9122 
9123   if (!Value.isSigned() || Value.isNegative())
9124     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9125       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9126         OriginalWidth = Value.getMinSignedBits();
9127 
9128   if (OriginalWidth <= FieldWidth)
9129     return false;
9130 
9131   // Compute the value which the bitfield will contain.
9132   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9133   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9134 
9135   // Check whether the stored value is equal to the original value.
9136   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9137   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9138     return false;
9139 
9140   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9141   // therefore don't strictly fit into a signed bitfield of width 1.
9142   if (FieldWidth == 1 && Value == 1)
9143     return false;
9144 
9145   std::string PrettyValue = Value.toString(10);
9146   std::string PrettyTrunc = TruncatedValue.toString(10);
9147 
9148   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9149     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9150     << Init->getSourceRange();
9151 
9152   return true;
9153 }
9154 
9155 /// Analyze the given simple or compound assignment for warning-worthy
9156 /// operations.
9157 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9158   // Just recurse on the LHS.
9159   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9160 
9161   // We want to recurse on the RHS as normal unless we're assigning to
9162   // a bitfield.
9163   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9164     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9165                                   E->getOperatorLoc())) {
9166       // Recurse, ignoring any implicit conversions on the RHS.
9167       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9168                                         E->getOperatorLoc());
9169     }
9170   }
9171 
9172   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9173 }
9174 
9175 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9176 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9177                      SourceLocation CContext, unsigned diag,
9178                      bool pruneControlFlow = false) {
9179   if (pruneControlFlow) {
9180     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9181                           S.PDiag(diag)
9182                             << SourceType << T << E->getSourceRange()
9183                             << SourceRange(CContext));
9184     return;
9185   }
9186   S.Diag(E->getExprLoc(), diag)
9187     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9188 }
9189 
9190 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9191 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9192                      unsigned diag, bool pruneControlFlow = false) {
9193   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9194 }
9195 
9196 
9197 /// Diagnose an implicit cast from a floating point value to an integer value.
9198 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9199 
9200                              SourceLocation CContext) {
9201   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9202   const bool PruneWarnings = S.inTemplateInstantiation();
9203 
9204   Expr *InnerE = E->IgnoreParenImpCasts();
9205   // We also want to warn on, e.g., "int i = -1.234"
9206   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9207     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9208       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9209 
9210   const bool IsLiteral =
9211       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9212 
9213   llvm::APFloat Value(0.0);
9214   bool IsConstant =
9215     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9216   if (!IsConstant) {
9217     return DiagnoseImpCast(S, E, T, CContext,
9218                            diag::warn_impcast_float_integer, PruneWarnings);
9219   }
9220 
9221   bool isExact = false;
9222 
9223   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9224                             T->hasUnsignedIntegerRepresentation());
9225   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9226                              &isExact) == llvm::APFloat::opOK &&
9227       isExact) {
9228     if (IsLiteral) return;
9229     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9230                            PruneWarnings);
9231   }
9232 
9233   unsigned DiagID = 0;
9234   if (IsLiteral) {
9235     // Warn on floating point literal to integer.
9236     DiagID = diag::warn_impcast_literal_float_to_integer;
9237   } else if (IntegerValue == 0) {
9238     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9239       return DiagnoseImpCast(S, E, T, CContext,
9240                              diag::warn_impcast_float_integer, PruneWarnings);
9241     }
9242     // Warn on non-zero to zero conversion.
9243     DiagID = diag::warn_impcast_float_to_integer_zero;
9244   } else {
9245     if (IntegerValue.isUnsigned()) {
9246       if (!IntegerValue.isMaxValue()) {
9247         return DiagnoseImpCast(S, E, T, CContext,
9248                                diag::warn_impcast_float_integer, PruneWarnings);
9249       }
9250     } else {  // IntegerValue.isSigned()
9251       if (!IntegerValue.isMaxSignedValue() &&
9252           !IntegerValue.isMinSignedValue()) {
9253         return DiagnoseImpCast(S, E, T, CContext,
9254                                diag::warn_impcast_float_integer, PruneWarnings);
9255       }
9256     }
9257     // Warn on evaluatable floating point expression to integer conversion.
9258     DiagID = diag::warn_impcast_float_to_integer;
9259   }
9260 
9261   // FIXME: Force the precision of the source value down so we don't print
9262   // digits which are usually useless (we don't really care here if we
9263   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9264   // would automatically print the shortest representation, but it's a bit
9265   // tricky to implement.
9266   SmallString<16> PrettySourceValue;
9267   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9268   precision = (precision * 59 + 195) / 196;
9269   Value.toString(PrettySourceValue, precision);
9270 
9271   SmallString<16> PrettyTargetValue;
9272   if (IsBool)
9273     PrettyTargetValue = Value.isZero() ? "false" : "true";
9274   else
9275     IntegerValue.toString(PrettyTargetValue);
9276 
9277   if (PruneWarnings) {
9278     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9279                           S.PDiag(DiagID)
9280                               << E->getType() << T.getUnqualifiedType()
9281                               << PrettySourceValue << PrettyTargetValue
9282                               << E->getSourceRange() << SourceRange(CContext));
9283   } else {
9284     S.Diag(E->getExprLoc(), DiagID)
9285         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9286         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9287   }
9288 }
9289 
9290 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9291   if (!Range.Width) return "0";
9292 
9293   llvm::APSInt ValueInRange = Value;
9294   ValueInRange.setIsSigned(!Range.NonNegative);
9295   ValueInRange = ValueInRange.trunc(Range.Width);
9296   return ValueInRange.toString(10);
9297 }
9298 
9299 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9300   if (!isa<ImplicitCastExpr>(Ex))
9301     return false;
9302 
9303   Expr *InnerE = Ex->IgnoreParenImpCasts();
9304   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9305   const Type *Source =
9306     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9307   if (Target->isDependentType())
9308     return false;
9309 
9310   const BuiltinType *FloatCandidateBT =
9311     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9312   const Type *BoolCandidateType = ToBool ? Target : Source;
9313 
9314   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9315           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9316 }
9317 
9318 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9319                                       SourceLocation CC) {
9320   unsigned NumArgs = TheCall->getNumArgs();
9321   for (unsigned i = 0; i < NumArgs; ++i) {
9322     Expr *CurrA = TheCall->getArg(i);
9323     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9324       continue;
9325 
9326     bool IsSwapped = ((i > 0) &&
9327         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9328     IsSwapped |= ((i < (NumArgs - 1)) &&
9329         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9330     if (IsSwapped) {
9331       // Warn on this floating-point to bool conversion.
9332       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9333                       CurrA->getType(), CC,
9334                       diag::warn_impcast_floating_point_to_bool);
9335     }
9336   }
9337 }
9338 
9339 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9340   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9341                         E->getExprLoc()))
9342     return;
9343 
9344   // Don't warn on functions which have return type nullptr_t.
9345   if (isa<CallExpr>(E))
9346     return;
9347 
9348   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9349   const Expr::NullPointerConstantKind NullKind =
9350       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9351   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9352     return;
9353 
9354   // Return if target type is a safe conversion.
9355   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9356       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9357     return;
9358 
9359   SourceLocation Loc = E->getSourceRange().getBegin();
9360 
9361   // Venture through the macro stacks to get to the source of macro arguments.
9362   // The new location is a better location than the complete location that was
9363   // passed in.
9364   while (S.SourceMgr.isMacroArgExpansion(Loc))
9365     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9366 
9367   while (S.SourceMgr.isMacroArgExpansion(CC))
9368     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9369 
9370   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9371   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9372     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9373         Loc, S.SourceMgr, S.getLangOpts());
9374     if (MacroName == "NULL")
9375       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9376   }
9377 
9378   // Only warn if the null and context location are in the same macro expansion.
9379   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9380     return;
9381 
9382   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9383       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9384       << FixItHint::CreateReplacement(Loc,
9385                                       S.getFixItZeroLiteralForType(T, Loc));
9386 }
9387 
9388 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9389                            ObjCArrayLiteral *ArrayLiteral);
9390 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9391                                 ObjCDictionaryLiteral *DictionaryLiteral);
9392 
9393 /// Check a single element within a collection literal against the
9394 /// target element type.
9395 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9396                                        Expr *Element, unsigned ElementKind) {
9397   // Skip a bitcast to 'id' or qualified 'id'.
9398   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9399     if (ICE->getCastKind() == CK_BitCast &&
9400         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9401       Element = ICE->getSubExpr();
9402   }
9403 
9404   QualType ElementType = Element->getType();
9405   ExprResult ElementResult(Element);
9406   if (ElementType->getAs<ObjCObjectPointerType>() &&
9407       S.CheckSingleAssignmentConstraints(TargetElementType,
9408                                          ElementResult,
9409                                          false, false)
9410         != Sema::Compatible) {
9411     S.Diag(Element->getLocStart(),
9412            diag::warn_objc_collection_literal_element)
9413       << ElementType << ElementKind << TargetElementType
9414       << Element->getSourceRange();
9415   }
9416 
9417   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9418     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9419   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9420     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9421 }
9422 
9423 /// Check an Objective-C array literal being converted to the given
9424 /// target type.
9425 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9426                            ObjCArrayLiteral *ArrayLiteral) {
9427   if (!S.NSArrayDecl)
9428     return;
9429 
9430   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9431   if (!TargetObjCPtr)
9432     return;
9433 
9434   if (TargetObjCPtr->isUnspecialized() ||
9435       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9436         != S.NSArrayDecl->getCanonicalDecl())
9437     return;
9438 
9439   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9440   if (TypeArgs.size() != 1)
9441     return;
9442 
9443   QualType TargetElementType = TypeArgs[0];
9444   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9445     checkObjCCollectionLiteralElement(S, TargetElementType,
9446                                       ArrayLiteral->getElement(I),
9447                                       0);
9448   }
9449 }
9450 
9451 /// Check an Objective-C dictionary literal being converted to the given
9452 /// target type.
9453 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9454                                 ObjCDictionaryLiteral *DictionaryLiteral) {
9455   if (!S.NSDictionaryDecl)
9456     return;
9457 
9458   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9459   if (!TargetObjCPtr)
9460     return;
9461 
9462   if (TargetObjCPtr->isUnspecialized() ||
9463       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9464         != S.NSDictionaryDecl->getCanonicalDecl())
9465     return;
9466 
9467   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9468   if (TypeArgs.size() != 2)
9469     return;
9470 
9471   QualType TargetKeyType = TypeArgs[0];
9472   QualType TargetObjectType = TypeArgs[1];
9473   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9474     auto Element = DictionaryLiteral->getKeyValueElement(I);
9475     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9476     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9477   }
9478 }
9479 
9480 // Helper function to filter out cases for constant width constant conversion.
9481 // Don't warn on char array initialization or for non-decimal values.
9482 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9483                                    SourceLocation CC) {
9484   // If initializing from a constant, and the constant starts with '0',
9485   // then it is a binary, octal, or hexadecimal.  Allow these constants
9486   // to fill all the bits, even if there is a sign change.
9487   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9488     const char FirstLiteralCharacter =
9489         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9490     if (FirstLiteralCharacter == '0')
9491       return false;
9492   }
9493 
9494   // If the CC location points to a '{', and the type is char, then assume
9495   // assume it is an array initialization.
9496   if (CC.isValid() && T->isCharType()) {
9497     const char FirstContextCharacter =
9498         S.getSourceManager().getCharacterData(CC)[0];
9499     if (FirstContextCharacter == '{')
9500       return false;
9501   }
9502 
9503   return true;
9504 }
9505 
9506 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9507                              SourceLocation CC, bool *ICContext = nullptr) {
9508   if (E->isTypeDependent() || E->isValueDependent()) return;
9509 
9510   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9511   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9512   if (Source == Target) return;
9513   if (Target->isDependentType()) return;
9514 
9515   // If the conversion context location is invalid don't complain. We also
9516   // don't want to emit a warning if the issue occurs from the expansion of
9517   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9518   // delay this check as long as possible. Once we detect we are in that
9519   // scenario, we just return.
9520   if (CC.isInvalid())
9521     return;
9522 
9523   // Diagnose implicit casts to bool.
9524   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9525     if (isa<StringLiteral>(E))
9526       // Warn on string literal to bool.  Checks for string literals in logical
9527       // and expressions, for instance, assert(0 && "error here"), are
9528       // prevented by a check in AnalyzeImplicitConversions().
9529       return DiagnoseImpCast(S, E, T, CC,
9530                              diag::warn_impcast_string_literal_to_bool);
9531     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9532         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9533       // This covers the literal expressions that evaluate to Objective-C
9534       // objects.
9535       return DiagnoseImpCast(S, E, T, CC,
9536                              diag::warn_impcast_objective_c_literal_to_bool);
9537     }
9538     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9539       // Warn on pointer to bool conversion that is always true.
9540       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9541                                      SourceRange(CC));
9542     }
9543   }
9544 
9545   // Check implicit casts from Objective-C collection literals to specialized
9546   // collection types, e.g., NSArray<NSString *> *.
9547   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9548     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9549   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9550     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9551 
9552   // Strip vector types.
9553   if (isa<VectorType>(Source)) {
9554     if (!isa<VectorType>(Target)) {
9555       if (S.SourceMgr.isInSystemMacro(CC))
9556         return;
9557       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9558     }
9559 
9560     // If the vector cast is cast between two vectors of the same size, it is
9561     // a bitcast, not a conversion.
9562     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9563       return;
9564 
9565     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9566     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9567   }
9568   if (auto VecTy = dyn_cast<VectorType>(Target))
9569     Target = VecTy->getElementType().getTypePtr();
9570 
9571   // Strip complex types.
9572   if (isa<ComplexType>(Source)) {
9573     if (!isa<ComplexType>(Target)) {
9574       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9575         return;
9576 
9577       return DiagnoseImpCast(S, E, T, CC,
9578                              S.getLangOpts().CPlusPlus
9579                                  ? diag::err_impcast_complex_scalar
9580                                  : diag::warn_impcast_complex_scalar);
9581     }
9582 
9583     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9584     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9585   }
9586 
9587   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9588   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9589 
9590   // If the source is floating point...
9591   if (SourceBT && SourceBT->isFloatingPoint()) {
9592     // ...and the target is floating point...
9593     if (TargetBT && TargetBT->isFloatingPoint()) {
9594       // ...then warn if we're dropping FP rank.
9595 
9596       // Builtin FP kinds are ordered by increasing FP rank.
9597       if (SourceBT->getKind() > TargetBT->getKind()) {
9598         // Don't warn about float constants that are precisely
9599         // representable in the target type.
9600         Expr::EvalResult result;
9601         if (E->EvaluateAsRValue(result, S.Context)) {
9602           // Value might be a float, a float vector, or a float complex.
9603           if (IsSameFloatAfterCast(result.Val,
9604                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9605                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9606             return;
9607         }
9608 
9609         if (S.SourceMgr.isInSystemMacro(CC))
9610           return;
9611 
9612         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9613       }
9614       // ... or possibly if we're increasing rank, too
9615       else if (TargetBT->getKind() > SourceBT->getKind()) {
9616         if (S.SourceMgr.isInSystemMacro(CC))
9617           return;
9618 
9619         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9620       }
9621       return;
9622     }
9623 
9624     // If the target is integral, always warn.
9625     if (TargetBT && TargetBT->isInteger()) {
9626       if (S.SourceMgr.isInSystemMacro(CC))
9627         return;
9628 
9629       DiagnoseFloatingImpCast(S, E, T, CC);
9630     }
9631 
9632     // Detect the case where a call result is converted from floating-point to
9633     // to bool, and the final argument to the call is converted from bool, to
9634     // discover this typo:
9635     //
9636     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9637     //
9638     // FIXME: This is an incredibly special case; is there some more general
9639     // way to detect this class of misplaced-parentheses bug?
9640     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9641       // Check last argument of function call to see if it is an
9642       // implicit cast from a type matching the type the result
9643       // is being cast to.
9644       CallExpr *CEx = cast<CallExpr>(E);
9645       if (unsigned NumArgs = CEx->getNumArgs()) {
9646         Expr *LastA = CEx->getArg(NumArgs - 1);
9647         Expr *InnerE = LastA->IgnoreParenImpCasts();
9648         if (isa<ImplicitCastExpr>(LastA) &&
9649             InnerE->getType()->isBooleanType()) {
9650           // Warn on this floating-point to bool conversion
9651           DiagnoseImpCast(S, E, T, CC,
9652                           diag::warn_impcast_floating_point_to_bool);
9653         }
9654       }
9655     }
9656     return;
9657   }
9658 
9659   DiagnoseNullConversion(S, E, T, CC);
9660 
9661   S.DiscardMisalignedMemberAddress(Target, E);
9662 
9663   if (!Source->isIntegerType() || !Target->isIntegerType())
9664     return;
9665 
9666   // TODO: remove this early return once the false positives for constant->bool
9667   // in templates, macros, etc, are reduced or removed.
9668   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9669     return;
9670 
9671   IntRange SourceRange = GetExprRange(S.Context, E);
9672   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9673 
9674   if (SourceRange.Width > TargetRange.Width) {
9675     // If the source is a constant, use a default-on diagnostic.
9676     // TODO: this should happen for bitfield stores, too.
9677     llvm::APSInt Value(32);
9678     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9679       if (S.SourceMgr.isInSystemMacro(CC))
9680         return;
9681 
9682       std::string PrettySourceValue = Value.toString(10);
9683       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9684 
9685       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9686         S.PDiag(diag::warn_impcast_integer_precision_constant)
9687             << PrettySourceValue << PrettyTargetValue
9688             << E->getType() << T << E->getSourceRange()
9689             << clang::SourceRange(CC));
9690       return;
9691     }
9692 
9693     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9694     if (S.SourceMgr.isInSystemMacro(CC))
9695       return;
9696 
9697     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9698       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9699                              /* pruneControlFlow */ true);
9700     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9701   }
9702 
9703   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9704       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9705     // Warn when doing a signed to signed conversion, warn if the positive
9706     // source value is exactly the width of the target type, which will
9707     // cause a negative value to be stored.
9708 
9709     llvm::APSInt Value;
9710     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9711         !S.SourceMgr.isInSystemMacro(CC)) {
9712       if (isSameWidthConstantConversion(S, E, T, CC)) {
9713         std::string PrettySourceValue = Value.toString(10);
9714         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9715 
9716         S.DiagRuntimeBehavior(
9717             E->getExprLoc(), E,
9718             S.PDiag(diag::warn_impcast_integer_precision_constant)
9719                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9720                 << E->getSourceRange() << clang::SourceRange(CC));
9721         return;
9722       }
9723     }
9724 
9725     // Fall through for non-constants to give a sign conversion warning.
9726   }
9727 
9728   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9729       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9730        SourceRange.Width == TargetRange.Width)) {
9731     if (S.SourceMgr.isInSystemMacro(CC))
9732       return;
9733 
9734     unsigned DiagID = diag::warn_impcast_integer_sign;
9735 
9736     // Traditionally, gcc has warned about this under -Wsign-compare.
9737     // We also want to warn about it in -Wconversion.
9738     // So if -Wconversion is off, use a completely identical diagnostic
9739     // in the sign-compare group.
9740     // The conditional-checking code will
9741     if (ICContext) {
9742       DiagID = diag::warn_impcast_integer_sign_conditional;
9743       *ICContext = true;
9744     }
9745 
9746     return DiagnoseImpCast(S, E, T, CC, DiagID);
9747   }
9748 
9749   // Diagnose conversions between different enumeration types.
9750   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9751   // type, to give us better diagnostics.
9752   QualType SourceType = E->getType();
9753   if (!S.getLangOpts().CPlusPlus) {
9754     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9755       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9756         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9757         SourceType = S.Context.getTypeDeclType(Enum);
9758         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9759       }
9760   }
9761 
9762   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9763     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9764       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9765           TargetEnum->getDecl()->hasNameForLinkage() &&
9766           SourceEnum != TargetEnum) {
9767         if (S.SourceMgr.isInSystemMacro(CC))
9768           return;
9769 
9770         return DiagnoseImpCast(S, E, SourceType, T, CC,
9771                                diag::warn_impcast_different_enum_types);
9772       }
9773 }
9774 
9775 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9776                               SourceLocation CC, QualType T);
9777 
9778 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9779                              SourceLocation CC, bool &ICContext) {
9780   E = E->IgnoreParenImpCasts();
9781 
9782   if (isa<ConditionalOperator>(E))
9783     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9784 
9785   AnalyzeImplicitConversions(S, E, CC);
9786   if (E->getType() != T)
9787     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9788 }
9789 
9790 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9791                               SourceLocation CC, QualType T) {
9792   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9793 
9794   bool Suspicious = false;
9795   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9796   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9797 
9798   // If -Wconversion would have warned about either of the candidates
9799   // for a signedness conversion to the context type...
9800   if (!Suspicious) return;
9801 
9802   // ...but it's currently ignored...
9803   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9804     return;
9805 
9806   // ...then check whether it would have warned about either of the
9807   // candidates for a signedness conversion to the condition type.
9808   if (E->getType() == T) return;
9809 
9810   Suspicious = false;
9811   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9812                           E->getType(), CC, &Suspicious);
9813   if (!Suspicious)
9814     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9815                             E->getType(), CC, &Suspicious);
9816 }
9817 
9818 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9819 /// Input argument E is a logical expression.
9820 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9821   if (S.getLangOpts().Bool)
9822     return;
9823   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9824 }
9825 
9826 /// AnalyzeImplicitConversions - Find and report any interesting
9827 /// implicit conversions in the given expression.  There are a couple
9828 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9829 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9830   QualType T = OrigE->getType();
9831   Expr *E = OrigE->IgnoreParenImpCasts();
9832 
9833   if (E->isTypeDependent() || E->isValueDependent())
9834     return;
9835 
9836   // For conditional operators, we analyze the arguments as if they
9837   // were being fed directly into the output.
9838   if (isa<ConditionalOperator>(E)) {
9839     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9840     CheckConditionalOperator(S, CO, CC, T);
9841     return;
9842   }
9843 
9844   // Check implicit argument conversions for function calls.
9845   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9846     CheckImplicitArgumentConversions(S, Call, CC);
9847 
9848   // Go ahead and check any implicit conversions we might have skipped.
9849   // The non-canonical typecheck is just an optimization;
9850   // CheckImplicitConversion will filter out dead implicit conversions.
9851   if (E->getType() != T)
9852     CheckImplicitConversion(S, E, T, CC);
9853 
9854   // Now continue drilling into this expression.
9855 
9856   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9857     // The bound subexpressions in a PseudoObjectExpr are not reachable
9858     // as transitive children.
9859     // FIXME: Use a more uniform representation for this.
9860     for (auto *SE : POE->semantics())
9861       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9862         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9863   }
9864 
9865   // Skip past explicit casts.
9866   if (isa<ExplicitCastExpr>(E)) {
9867     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9868     return AnalyzeImplicitConversions(S, E, CC);
9869   }
9870 
9871   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9872     // Do a somewhat different check with comparison operators.
9873     if (BO->isComparisonOp())
9874       return AnalyzeComparison(S, BO);
9875 
9876     // And with simple assignments.
9877     if (BO->getOpcode() == BO_Assign)
9878       return AnalyzeAssignment(S, BO);
9879   }
9880 
9881   // These break the otherwise-useful invariant below.  Fortunately,
9882   // we don't really need to recurse into them, because any internal
9883   // expressions should have been analyzed already when they were
9884   // built into statements.
9885   if (isa<StmtExpr>(E)) return;
9886 
9887   // Don't descend into unevaluated contexts.
9888   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9889 
9890   // Now just recurse over the expression's children.
9891   CC = E->getExprLoc();
9892   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9893   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9894   for (Stmt *SubStmt : E->children()) {
9895     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9896     if (!ChildExpr)
9897       continue;
9898 
9899     if (IsLogicalAndOperator &&
9900         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9901       // Ignore checking string literals that are in logical and operators.
9902       // This is a common pattern for asserts.
9903       continue;
9904     AnalyzeImplicitConversions(S, ChildExpr, CC);
9905   }
9906 
9907   if (BO && BO->isLogicalOp()) {
9908     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9909     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9910       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9911 
9912     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9913     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9914       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9915   }
9916 
9917   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9918     if (U->getOpcode() == UO_LNot)
9919       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9920 }
9921 
9922 } // end anonymous namespace
9923 
9924 /// Diagnose integer type and any valid implicit convertion to it.
9925 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9926   // Taking into account implicit conversions,
9927   // allow any integer.
9928   if (!E->getType()->isIntegerType()) {
9929     S.Diag(E->getLocStart(),
9930            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9931     return true;
9932   }
9933   // Potentially emit standard warnings for implicit conversions if enabled
9934   // using -Wconversion.
9935   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9936   return false;
9937 }
9938 
9939 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9940 // Returns true when emitting a warning about taking the address of a reference.
9941 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9942                               const PartialDiagnostic &PD) {
9943   E = E->IgnoreParenImpCasts();
9944 
9945   const FunctionDecl *FD = nullptr;
9946 
9947   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9948     if (!DRE->getDecl()->getType()->isReferenceType())
9949       return false;
9950   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9951     if (!M->getMemberDecl()->getType()->isReferenceType())
9952       return false;
9953   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9954     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9955       return false;
9956     FD = Call->getDirectCallee();
9957   } else {
9958     return false;
9959   }
9960 
9961   SemaRef.Diag(E->getExprLoc(), PD);
9962 
9963   // If possible, point to location of function.
9964   if (FD) {
9965     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9966   }
9967 
9968   return true;
9969 }
9970 
9971 // Returns true if the SourceLocation is expanded from any macro body.
9972 // Returns false if the SourceLocation is invalid, is from not in a macro
9973 // expansion, or is from expanded from a top-level macro argument.
9974 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9975   if (Loc.isInvalid())
9976     return false;
9977 
9978   while (Loc.isMacroID()) {
9979     if (SM.isMacroBodyExpansion(Loc))
9980       return true;
9981     Loc = SM.getImmediateMacroCallerLoc(Loc);
9982   }
9983 
9984   return false;
9985 }
9986 
9987 /// \brief Diagnose pointers that are always non-null.
9988 /// \param E the expression containing the pointer
9989 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9990 /// compared to a null pointer
9991 /// \param IsEqual True when the comparison is equal to a null pointer
9992 /// \param Range Extra SourceRange to highlight in the diagnostic
9993 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9994                                         Expr::NullPointerConstantKind NullKind,
9995                                         bool IsEqual, SourceRange Range) {
9996   if (!E)
9997     return;
9998 
9999   // Don't warn inside macros.
10000   if (E->getExprLoc().isMacroID()) {
10001     const SourceManager &SM = getSourceManager();
10002     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
10003         IsInAnyMacroBody(SM, Range.getBegin()))
10004       return;
10005   }
10006   E = E->IgnoreImpCasts();
10007 
10008   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
10009 
10010   if (isa<CXXThisExpr>(E)) {
10011     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
10012                                 : diag::warn_this_bool_conversion;
10013     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
10014     return;
10015   }
10016 
10017   bool IsAddressOf = false;
10018 
10019   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10020     if (UO->getOpcode() != UO_AddrOf)
10021       return;
10022     IsAddressOf = true;
10023     E = UO->getSubExpr();
10024   }
10025 
10026   if (IsAddressOf) {
10027     unsigned DiagID = IsCompare
10028                           ? diag::warn_address_of_reference_null_compare
10029                           : diag::warn_address_of_reference_bool_conversion;
10030     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
10031                                          << IsEqual;
10032     if (CheckForReference(*this, E, PD)) {
10033       return;
10034     }
10035   }
10036 
10037   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
10038     bool IsParam = isa<NonNullAttr>(NonnullAttr);
10039     std::string Str;
10040     llvm::raw_string_ostream S(Str);
10041     E->printPretty(S, nullptr, getPrintingPolicy());
10042     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
10043                                 : diag::warn_cast_nonnull_to_bool;
10044     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
10045       << E->getSourceRange() << Range << IsEqual;
10046     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
10047   };
10048 
10049   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
10050   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
10051     if (auto *Callee = Call->getDirectCallee()) {
10052       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
10053         ComplainAboutNonnullParamOrCall(A);
10054         return;
10055       }
10056     }
10057   }
10058 
10059   // Expect to find a single Decl.  Skip anything more complicated.
10060   ValueDecl *D = nullptr;
10061   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
10062     D = R->getDecl();
10063   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
10064     D = M->getMemberDecl();
10065   }
10066 
10067   // Weak Decls can be null.
10068   if (!D || D->isWeak())
10069     return;
10070 
10071   // Check for parameter decl with nonnull attribute
10072   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10073     if (getCurFunction() &&
10074         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10075       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10076         ComplainAboutNonnullParamOrCall(A);
10077         return;
10078       }
10079 
10080       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10081         auto ParamIter = llvm::find(FD->parameters(), PV);
10082         assert(ParamIter != FD->param_end());
10083         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10084 
10085         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10086           if (!NonNull->args_size()) {
10087               ComplainAboutNonnullParamOrCall(NonNull);
10088               return;
10089           }
10090 
10091           for (unsigned ArgNo : NonNull->args()) {
10092             if (ArgNo == ParamNo) {
10093               ComplainAboutNonnullParamOrCall(NonNull);
10094               return;
10095             }
10096           }
10097         }
10098       }
10099     }
10100   }
10101 
10102   QualType T = D->getType();
10103   const bool IsArray = T->isArrayType();
10104   const bool IsFunction = T->isFunctionType();
10105 
10106   // Address of function is used to silence the function warning.
10107   if (IsAddressOf && IsFunction) {
10108     return;
10109   }
10110 
10111   // Found nothing.
10112   if (!IsAddressOf && !IsFunction && !IsArray)
10113     return;
10114 
10115   // Pretty print the expression for the diagnostic.
10116   std::string Str;
10117   llvm::raw_string_ostream S(Str);
10118   E->printPretty(S, nullptr, getPrintingPolicy());
10119 
10120   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10121                               : diag::warn_impcast_pointer_to_bool;
10122   enum {
10123     AddressOf,
10124     FunctionPointer,
10125     ArrayPointer
10126   } DiagType;
10127   if (IsAddressOf)
10128     DiagType = AddressOf;
10129   else if (IsFunction)
10130     DiagType = FunctionPointer;
10131   else if (IsArray)
10132     DiagType = ArrayPointer;
10133   else
10134     llvm_unreachable("Could not determine diagnostic.");
10135   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10136                                 << Range << IsEqual;
10137 
10138   if (!IsFunction)
10139     return;
10140 
10141   // Suggest '&' to silence the function warning.
10142   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10143       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10144 
10145   // Check to see if '()' fixit should be emitted.
10146   QualType ReturnType;
10147   UnresolvedSet<4> NonTemplateOverloads;
10148   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10149   if (ReturnType.isNull())
10150     return;
10151 
10152   if (IsCompare) {
10153     // There are two cases here.  If there is null constant, the only suggest
10154     // for a pointer return type.  If the null is 0, then suggest if the return
10155     // type is a pointer or an integer type.
10156     if (!ReturnType->isPointerType()) {
10157       if (NullKind == Expr::NPCK_ZeroExpression ||
10158           NullKind == Expr::NPCK_ZeroLiteral) {
10159         if (!ReturnType->isIntegerType())
10160           return;
10161       } else {
10162         return;
10163       }
10164     }
10165   } else { // !IsCompare
10166     // For function to bool, only suggest if the function pointer has bool
10167     // return type.
10168     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10169       return;
10170   }
10171   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10172       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10173 }
10174 
10175 /// Diagnoses "dangerous" implicit conversions within the given
10176 /// expression (which is a full expression).  Implements -Wconversion
10177 /// and -Wsign-compare.
10178 ///
10179 /// \param CC the "context" location of the implicit conversion, i.e.
10180 ///   the most location of the syntactic entity requiring the implicit
10181 ///   conversion
10182 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10183   // Don't diagnose in unevaluated contexts.
10184   if (isUnevaluatedContext())
10185     return;
10186 
10187   // Don't diagnose for value- or type-dependent expressions.
10188   if (E->isTypeDependent() || E->isValueDependent())
10189     return;
10190 
10191   // Check for array bounds violations in cases where the check isn't triggered
10192   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10193   // ArraySubscriptExpr is on the RHS of a variable initialization.
10194   CheckArrayAccess(E);
10195 
10196   // This is not the right CC for (e.g.) a variable initialization.
10197   AnalyzeImplicitConversions(*this, E, CC);
10198 }
10199 
10200 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10201 /// Input argument E is a logical expression.
10202 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10203   ::CheckBoolLikeConversion(*this, E, CC);
10204 }
10205 
10206 /// Diagnose when expression is an integer constant expression and its evaluation
10207 /// results in integer overflow
10208 void Sema::CheckForIntOverflow (Expr *E) {
10209   // Use a work list to deal with nested struct initializers.
10210   SmallVector<Expr *, 2> Exprs(1, E);
10211 
10212   do {
10213     Expr *E = Exprs.pop_back_val();
10214 
10215     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10216       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10217       continue;
10218     }
10219 
10220     if (auto InitList = dyn_cast<InitListExpr>(E))
10221       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10222 
10223     if (isa<ObjCBoxedExpr>(E))
10224       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10225   } while (!Exprs.empty());
10226 }
10227 
10228 namespace {
10229 /// \brief Visitor for expressions which looks for unsequenced operations on the
10230 /// same object.
10231 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10232   typedef EvaluatedExprVisitor<SequenceChecker> Base;
10233 
10234   /// \brief A tree of sequenced regions within an expression. Two regions are
10235   /// unsequenced if one is an ancestor or a descendent of the other. When we
10236   /// finish processing an expression with sequencing, such as a comma
10237   /// expression, we fold its tree nodes into its parent, since they are
10238   /// unsequenced with respect to nodes we will visit later.
10239   class SequenceTree {
10240     struct Value {
10241       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10242       unsigned Parent : 31;
10243       unsigned Merged : 1;
10244     };
10245     SmallVector<Value, 8> Values;
10246 
10247   public:
10248     /// \brief A region within an expression which may be sequenced with respect
10249     /// to some other region.
10250     class Seq {
10251       explicit Seq(unsigned N) : Index(N) {}
10252       unsigned Index;
10253       friend class SequenceTree;
10254     public:
10255       Seq() : Index(0) {}
10256     };
10257 
10258     SequenceTree() { Values.push_back(Value(0)); }
10259     Seq root() const { return Seq(0); }
10260 
10261     /// \brief Create a new sequence of operations, which is an unsequenced
10262     /// subset of \p Parent. This sequence of operations is sequenced with
10263     /// respect to other children of \p Parent.
10264     Seq allocate(Seq Parent) {
10265       Values.push_back(Value(Parent.Index));
10266       return Seq(Values.size() - 1);
10267     }
10268 
10269     /// \brief Merge a sequence of operations into its parent.
10270     void merge(Seq S) {
10271       Values[S.Index].Merged = true;
10272     }
10273 
10274     /// \brief Determine whether two operations are unsequenced. This operation
10275     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10276     /// should have been merged into its parent as appropriate.
10277     bool isUnsequenced(Seq Cur, Seq Old) {
10278       unsigned C = representative(Cur.Index);
10279       unsigned Target = representative(Old.Index);
10280       while (C >= Target) {
10281         if (C == Target)
10282           return true;
10283         C = Values[C].Parent;
10284       }
10285       return false;
10286     }
10287 
10288   private:
10289     /// \brief Pick a representative for a sequence.
10290     unsigned representative(unsigned K) {
10291       if (Values[K].Merged)
10292         // Perform path compression as we go.
10293         return Values[K].Parent = representative(Values[K].Parent);
10294       return K;
10295     }
10296   };
10297 
10298   /// An object for which we can track unsequenced uses.
10299   typedef NamedDecl *Object;
10300 
10301   /// Different flavors of object usage which we track. We only track the
10302   /// least-sequenced usage of each kind.
10303   enum UsageKind {
10304     /// A read of an object. Multiple unsequenced reads are OK.
10305     UK_Use,
10306     /// A modification of an object which is sequenced before the value
10307     /// computation of the expression, such as ++n in C++.
10308     UK_ModAsValue,
10309     /// A modification of an object which is not sequenced before the value
10310     /// computation of the expression, such as n++.
10311     UK_ModAsSideEffect,
10312 
10313     UK_Count = UK_ModAsSideEffect + 1
10314   };
10315 
10316   struct Usage {
10317     Usage() : Use(nullptr), Seq() {}
10318     Expr *Use;
10319     SequenceTree::Seq Seq;
10320   };
10321 
10322   struct UsageInfo {
10323     UsageInfo() : Diagnosed(false) {}
10324     Usage Uses[UK_Count];
10325     /// Have we issued a diagnostic for this variable already?
10326     bool Diagnosed;
10327   };
10328   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10329 
10330   Sema &SemaRef;
10331   /// Sequenced regions within the expression.
10332   SequenceTree Tree;
10333   /// Declaration modifications and references which we have seen.
10334   UsageInfoMap UsageMap;
10335   /// The region we are currently within.
10336   SequenceTree::Seq Region;
10337   /// Filled in with declarations which were modified as a side-effect
10338   /// (that is, post-increment operations).
10339   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10340   /// Expressions to check later. We defer checking these to reduce
10341   /// stack usage.
10342   SmallVectorImpl<Expr *> &WorkList;
10343 
10344   /// RAII object wrapping the visitation of a sequenced subexpression of an
10345   /// expression. At the end of this process, the side-effects of the evaluation
10346   /// become sequenced with respect to the value computation of the result, so
10347   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10348   /// UK_ModAsValue.
10349   struct SequencedSubexpression {
10350     SequencedSubexpression(SequenceChecker &Self)
10351       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10352       Self.ModAsSideEffect = &ModAsSideEffect;
10353     }
10354     ~SequencedSubexpression() {
10355       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10356         UsageInfo &U = Self.UsageMap[M.first];
10357         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10358         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10359         SideEffectUsage = M.second;
10360       }
10361       Self.ModAsSideEffect = OldModAsSideEffect;
10362     }
10363 
10364     SequenceChecker &Self;
10365     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10366     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10367   };
10368 
10369   /// RAII object wrapping the visitation of a subexpression which we might
10370   /// choose to evaluate as a constant. If any subexpression is evaluated and
10371   /// found to be non-constant, this allows us to suppress the evaluation of
10372   /// the outer expression.
10373   class EvaluationTracker {
10374   public:
10375     EvaluationTracker(SequenceChecker &Self)
10376         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10377       Self.EvalTracker = this;
10378     }
10379     ~EvaluationTracker() {
10380       Self.EvalTracker = Prev;
10381       if (Prev)
10382         Prev->EvalOK &= EvalOK;
10383     }
10384 
10385     bool evaluate(const Expr *E, bool &Result) {
10386       if (!EvalOK || E->isValueDependent())
10387         return false;
10388       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10389       return EvalOK;
10390     }
10391 
10392   private:
10393     SequenceChecker &Self;
10394     EvaluationTracker *Prev;
10395     bool EvalOK;
10396   } *EvalTracker;
10397 
10398   /// \brief Find the object which is produced by the specified expression,
10399   /// if any.
10400   Object getObject(Expr *E, bool Mod) const {
10401     E = E->IgnoreParenCasts();
10402     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10403       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10404         return getObject(UO->getSubExpr(), Mod);
10405     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10406       if (BO->getOpcode() == BO_Comma)
10407         return getObject(BO->getRHS(), Mod);
10408       if (Mod && BO->isAssignmentOp())
10409         return getObject(BO->getLHS(), Mod);
10410     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10411       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10412       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10413         return ME->getMemberDecl();
10414     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10415       // FIXME: If this is a reference, map through to its value.
10416       return DRE->getDecl();
10417     return nullptr;
10418   }
10419 
10420   /// \brief Note that an object was modified or used by an expression.
10421   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10422     Usage &U = UI.Uses[UK];
10423     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10424       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10425         ModAsSideEffect->push_back(std::make_pair(O, U));
10426       U.Use = Ref;
10427       U.Seq = Region;
10428     }
10429   }
10430   /// \brief Check whether a modification or use conflicts with a prior usage.
10431   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10432                   bool IsModMod) {
10433     if (UI.Diagnosed)
10434       return;
10435 
10436     const Usage &U = UI.Uses[OtherKind];
10437     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10438       return;
10439 
10440     Expr *Mod = U.Use;
10441     Expr *ModOrUse = Ref;
10442     if (OtherKind == UK_Use)
10443       std::swap(Mod, ModOrUse);
10444 
10445     SemaRef.Diag(Mod->getExprLoc(),
10446                  IsModMod ? diag::warn_unsequenced_mod_mod
10447                           : diag::warn_unsequenced_mod_use)
10448       << O << SourceRange(ModOrUse->getExprLoc());
10449     UI.Diagnosed = true;
10450   }
10451 
10452   void notePreUse(Object O, Expr *Use) {
10453     UsageInfo &U = UsageMap[O];
10454     // Uses conflict with other modifications.
10455     checkUsage(O, U, Use, UK_ModAsValue, false);
10456   }
10457   void notePostUse(Object O, Expr *Use) {
10458     UsageInfo &U = UsageMap[O];
10459     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10460     addUsage(U, O, Use, UK_Use);
10461   }
10462 
10463   void notePreMod(Object O, Expr *Mod) {
10464     UsageInfo &U = UsageMap[O];
10465     // Modifications conflict with other modifications and with uses.
10466     checkUsage(O, U, Mod, UK_ModAsValue, true);
10467     checkUsage(O, U, Mod, UK_Use, false);
10468   }
10469   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10470     UsageInfo &U = UsageMap[O];
10471     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10472     addUsage(U, O, Use, UK);
10473   }
10474 
10475 public:
10476   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10477       : Base(S.Context), SemaRef(S), Region(Tree.root()),
10478         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10479     Visit(E);
10480   }
10481 
10482   void VisitStmt(Stmt *S) {
10483     // Skip all statements which aren't expressions for now.
10484   }
10485 
10486   void VisitExpr(Expr *E) {
10487     // By default, just recurse to evaluated subexpressions.
10488     Base::VisitStmt(E);
10489   }
10490 
10491   void VisitCastExpr(CastExpr *E) {
10492     Object O = Object();
10493     if (E->getCastKind() == CK_LValueToRValue)
10494       O = getObject(E->getSubExpr(), false);
10495 
10496     if (O)
10497       notePreUse(O, E);
10498     VisitExpr(E);
10499     if (O)
10500       notePostUse(O, E);
10501   }
10502 
10503   void VisitBinComma(BinaryOperator *BO) {
10504     // C++11 [expr.comma]p1:
10505     //   Every value computation and side effect associated with the left
10506     //   expression is sequenced before every value computation and side
10507     //   effect associated with the right expression.
10508     SequenceTree::Seq LHS = Tree.allocate(Region);
10509     SequenceTree::Seq RHS = Tree.allocate(Region);
10510     SequenceTree::Seq OldRegion = Region;
10511 
10512     {
10513       SequencedSubexpression SeqLHS(*this);
10514       Region = LHS;
10515       Visit(BO->getLHS());
10516     }
10517 
10518     Region = RHS;
10519     Visit(BO->getRHS());
10520 
10521     Region = OldRegion;
10522 
10523     // Forget that LHS and RHS are sequenced. They are both unsequenced
10524     // with respect to other stuff.
10525     Tree.merge(LHS);
10526     Tree.merge(RHS);
10527   }
10528 
10529   void VisitBinAssign(BinaryOperator *BO) {
10530     // The modification is sequenced after the value computation of the LHS
10531     // and RHS, so check it before inspecting the operands and update the
10532     // map afterwards.
10533     Object O = getObject(BO->getLHS(), true);
10534     if (!O)
10535       return VisitExpr(BO);
10536 
10537     notePreMod(O, BO);
10538 
10539     // C++11 [expr.ass]p7:
10540     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10541     //   only once.
10542     //
10543     // Therefore, for a compound assignment operator, O is considered used
10544     // everywhere except within the evaluation of E1 itself.
10545     if (isa<CompoundAssignOperator>(BO))
10546       notePreUse(O, BO);
10547 
10548     Visit(BO->getLHS());
10549 
10550     if (isa<CompoundAssignOperator>(BO))
10551       notePostUse(O, BO);
10552 
10553     Visit(BO->getRHS());
10554 
10555     // C++11 [expr.ass]p1:
10556     //   the assignment is sequenced [...] before the value computation of the
10557     //   assignment expression.
10558     // C11 6.5.16/3 has no such rule.
10559     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10560                                                        : UK_ModAsSideEffect);
10561   }
10562 
10563   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10564     VisitBinAssign(CAO);
10565   }
10566 
10567   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10568   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10569   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10570     Object O = getObject(UO->getSubExpr(), true);
10571     if (!O)
10572       return VisitExpr(UO);
10573 
10574     notePreMod(O, UO);
10575     Visit(UO->getSubExpr());
10576     // C++11 [expr.pre.incr]p1:
10577     //   the expression ++x is equivalent to x+=1
10578     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10579                                                        : UK_ModAsSideEffect);
10580   }
10581 
10582   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10583   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10584   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10585     Object O = getObject(UO->getSubExpr(), true);
10586     if (!O)
10587       return VisitExpr(UO);
10588 
10589     notePreMod(O, UO);
10590     Visit(UO->getSubExpr());
10591     notePostMod(O, UO, UK_ModAsSideEffect);
10592   }
10593 
10594   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10595   void VisitBinLOr(BinaryOperator *BO) {
10596     // The side-effects of the LHS of an '&&' are sequenced before the
10597     // value computation of the RHS, and hence before the value computation
10598     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10599     // as if they were unconditionally sequenced.
10600     EvaluationTracker Eval(*this);
10601     {
10602       SequencedSubexpression Sequenced(*this);
10603       Visit(BO->getLHS());
10604     }
10605 
10606     bool Result;
10607     if (Eval.evaluate(BO->getLHS(), Result)) {
10608       if (!Result)
10609         Visit(BO->getRHS());
10610     } else {
10611       // Check for unsequenced operations in the RHS, treating it as an
10612       // entirely separate evaluation.
10613       //
10614       // FIXME: If there are operations in the RHS which are unsequenced
10615       // with respect to operations outside the RHS, and those operations
10616       // are unconditionally evaluated, diagnose them.
10617       WorkList.push_back(BO->getRHS());
10618     }
10619   }
10620   void VisitBinLAnd(BinaryOperator *BO) {
10621     EvaluationTracker Eval(*this);
10622     {
10623       SequencedSubexpression Sequenced(*this);
10624       Visit(BO->getLHS());
10625     }
10626 
10627     bool Result;
10628     if (Eval.evaluate(BO->getLHS(), Result)) {
10629       if (Result)
10630         Visit(BO->getRHS());
10631     } else {
10632       WorkList.push_back(BO->getRHS());
10633     }
10634   }
10635 
10636   // Only visit the condition, unless we can be sure which subexpression will
10637   // be chosen.
10638   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10639     EvaluationTracker Eval(*this);
10640     {
10641       SequencedSubexpression Sequenced(*this);
10642       Visit(CO->getCond());
10643     }
10644 
10645     bool Result;
10646     if (Eval.evaluate(CO->getCond(), Result))
10647       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10648     else {
10649       WorkList.push_back(CO->getTrueExpr());
10650       WorkList.push_back(CO->getFalseExpr());
10651     }
10652   }
10653 
10654   void VisitCallExpr(CallExpr *CE) {
10655     // C++11 [intro.execution]p15:
10656     //   When calling a function [...], every value computation and side effect
10657     //   associated with any argument expression, or with the postfix expression
10658     //   designating the called function, is sequenced before execution of every
10659     //   expression or statement in the body of the function [and thus before
10660     //   the value computation of its result].
10661     SequencedSubexpression Sequenced(*this);
10662     Base::VisitCallExpr(CE);
10663 
10664     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10665   }
10666 
10667   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10668     // This is a call, so all subexpressions are sequenced before the result.
10669     SequencedSubexpression Sequenced(*this);
10670 
10671     if (!CCE->isListInitialization())
10672       return VisitExpr(CCE);
10673 
10674     // In C++11, list initializations are sequenced.
10675     SmallVector<SequenceTree::Seq, 32> Elts;
10676     SequenceTree::Seq Parent = Region;
10677     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10678                                         E = CCE->arg_end();
10679          I != E; ++I) {
10680       Region = Tree.allocate(Parent);
10681       Elts.push_back(Region);
10682       Visit(*I);
10683     }
10684 
10685     // Forget that the initializers are sequenced.
10686     Region = Parent;
10687     for (unsigned I = 0; I < Elts.size(); ++I)
10688       Tree.merge(Elts[I]);
10689   }
10690 
10691   void VisitInitListExpr(InitListExpr *ILE) {
10692     if (!SemaRef.getLangOpts().CPlusPlus11)
10693       return VisitExpr(ILE);
10694 
10695     // In C++11, list initializations are sequenced.
10696     SmallVector<SequenceTree::Seq, 32> Elts;
10697     SequenceTree::Seq Parent = Region;
10698     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10699       Expr *E = ILE->getInit(I);
10700       if (!E) continue;
10701       Region = Tree.allocate(Parent);
10702       Elts.push_back(Region);
10703       Visit(E);
10704     }
10705 
10706     // Forget that the initializers are sequenced.
10707     Region = Parent;
10708     for (unsigned I = 0; I < Elts.size(); ++I)
10709       Tree.merge(Elts[I]);
10710   }
10711 };
10712 } // end anonymous namespace
10713 
10714 void Sema::CheckUnsequencedOperations(Expr *E) {
10715   SmallVector<Expr *, 8> WorkList;
10716   WorkList.push_back(E);
10717   while (!WorkList.empty()) {
10718     Expr *Item = WorkList.pop_back_val();
10719     SequenceChecker(*this, Item, WorkList);
10720   }
10721 }
10722 
10723 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10724                               bool IsConstexpr) {
10725   CheckImplicitConversions(E, CheckLoc);
10726   if (!E->isInstantiationDependent())
10727     CheckUnsequencedOperations(E);
10728   if (!IsConstexpr && !E->isValueDependent())
10729     CheckForIntOverflow(E);
10730   DiagnoseMisalignedMembers();
10731 }
10732 
10733 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10734                                        FieldDecl *BitField,
10735                                        Expr *Init) {
10736   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10737 }
10738 
10739 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10740                                          SourceLocation Loc) {
10741   if (!PType->isVariablyModifiedType())
10742     return;
10743   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10744     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10745     return;
10746   }
10747   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10748     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10749     return;
10750   }
10751   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10752     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10753     return;
10754   }
10755 
10756   const ArrayType *AT = S.Context.getAsArrayType(PType);
10757   if (!AT)
10758     return;
10759 
10760   if (AT->getSizeModifier() != ArrayType::Star) {
10761     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10762     return;
10763   }
10764 
10765   S.Diag(Loc, diag::err_array_star_in_function_definition);
10766 }
10767 
10768 /// CheckParmsForFunctionDef - Check that the parameters of the given
10769 /// function are appropriate for the definition of a function. This
10770 /// takes care of any checks that cannot be performed on the
10771 /// declaration itself, e.g., that the types of each of the function
10772 /// parameters are complete.
10773 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10774                                     bool CheckParameterNames) {
10775   bool HasInvalidParm = false;
10776   for (ParmVarDecl *Param : Parameters) {
10777     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10778     // function declarator that is part of a function definition of
10779     // that function shall not have incomplete type.
10780     //
10781     // This is also C++ [dcl.fct]p6.
10782     if (!Param->isInvalidDecl() &&
10783         RequireCompleteType(Param->getLocation(), Param->getType(),
10784                             diag::err_typecheck_decl_incomplete_type)) {
10785       Param->setInvalidDecl();
10786       HasInvalidParm = true;
10787     }
10788 
10789     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10790     // declaration of each parameter shall include an identifier.
10791     if (CheckParameterNames &&
10792         Param->getIdentifier() == nullptr &&
10793         !Param->isImplicit() &&
10794         !getLangOpts().CPlusPlus)
10795       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10796 
10797     // C99 6.7.5.3p12:
10798     //   If the function declarator is not part of a definition of that
10799     //   function, parameters may have incomplete type and may use the [*]
10800     //   notation in their sequences of declarator specifiers to specify
10801     //   variable length array types.
10802     QualType PType = Param->getOriginalType();
10803     // FIXME: This diagnostic should point the '[*]' if source-location
10804     // information is added for it.
10805     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10806 
10807     // MSVC destroys objects passed by value in the callee.  Therefore a
10808     // function definition which takes such a parameter must be able to call the
10809     // object's destructor.  However, we don't perform any direct access check
10810     // on the dtor.
10811     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10812                                        .getCXXABI()
10813                                        .areArgsDestroyedLeftToRightInCallee()) {
10814       if (!Param->isInvalidDecl()) {
10815         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10816           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10817           if (!ClassDecl->isInvalidDecl() &&
10818               !ClassDecl->hasIrrelevantDestructor() &&
10819               !ClassDecl->isDependentContext()) {
10820             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10821             MarkFunctionReferenced(Param->getLocation(), Destructor);
10822             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10823           }
10824         }
10825       }
10826     }
10827 
10828     // Parameters with the pass_object_size attribute only need to be marked
10829     // constant at function definitions. Because we lack information about
10830     // whether we're on a declaration or definition when we're instantiating the
10831     // attribute, we need to check for constness here.
10832     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10833       if (!Param->getType().isConstQualified())
10834         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10835             << Attr->getSpelling() << 1;
10836   }
10837 
10838   return HasInvalidParm;
10839 }
10840 
10841 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10842 /// or MemberExpr.
10843 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10844                               ASTContext &Context) {
10845   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10846     return Context.getDeclAlign(DRE->getDecl());
10847 
10848   if (const auto *ME = dyn_cast<MemberExpr>(E))
10849     return Context.getDeclAlign(ME->getMemberDecl());
10850 
10851   return TypeAlign;
10852 }
10853 
10854 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10855 /// pointer cast increases the alignment requirements.
10856 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10857   // This is actually a lot of work to potentially be doing on every
10858   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10859   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10860     return;
10861 
10862   // Ignore dependent types.
10863   if (T->isDependentType() || Op->getType()->isDependentType())
10864     return;
10865 
10866   // Require that the destination be a pointer type.
10867   const PointerType *DestPtr = T->getAs<PointerType>();
10868   if (!DestPtr) return;
10869 
10870   // If the destination has alignment 1, we're done.
10871   QualType DestPointee = DestPtr->getPointeeType();
10872   if (DestPointee->isIncompleteType()) return;
10873   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10874   if (DestAlign.isOne()) return;
10875 
10876   // Require that the source be a pointer type.
10877   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10878   if (!SrcPtr) return;
10879   QualType SrcPointee = SrcPtr->getPointeeType();
10880 
10881   // Whitelist casts from cv void*.  We already implicitly
10882   // whitelisted casts to cv void*, since they have alignment 1.
10883   // Also whitelist casts involving incomplete types, which implicitly
10884   // includes 'void'.
10885   if (SrcPointee->isIncompleteType()) return;
10886 
10887   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10888 
10889   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10890     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10891       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10892   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10893     if (UO->getOpcode() == UO_AddrOf)
10894       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10895   }
10896 
10897   if (SrcAlign >= DestAlign) return;
10898 
10899   Diag(TRange.getBegin(), diag::warn_cast_align)
10900     << Op->getType() << T
10901     << static_cast<unsigned>(SrcAlign.getQuantity())
10902     << static_cast<unsigned>(DestAlign.getQuantity())
10903     << TRange << Op->getSourceRange();
10904 }
10905 
10906 /// \brief Check whether this array fits the idiom of a size-one tail padded
10907 /// array member of a struct.
10908 ///
10909 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10910 /// commonly used to emulate flexible arrays in C89 code.
10911 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10912                                     const NamedDecl *ND) {
10913   if (Size != 1 || !ND) return false;
10914 
10915   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10916   if (!FD) return false;
10917 
10918   // Don't consider sizes resulting from macro expansions or template argument
10919   // substitution to form C89 tail-padded arrays.
10920 
10921   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10922   while (TInfo) {
10923     TypeLoc TL = TInfo->getTypeLoc();
10924     // Look through typedefs.
10925     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10926       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10927       TInfo = TDL->getTypeSourceInfo();
10928       continue;
10929     }
10930     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10931       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10932       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10933         return false;
10934     }
10935     break;
10936   }
10937 
10938   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10939   if (!RD) return false;
10940   if (RD->isUnion()) return false;
10941   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10942     if (!CRD->isStandardLayout()) return false;
10943   }
10944 
10945   // See if this is the last field decl in the record.
10946   const Decl *D = FD;
10947   while ((D = D->getNextDeclInContext()))
10948     if (isa<FieldDecl>(D))
10949       return false;
10950   return true;
10951 }
10952 
10953 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10954                             const ArraySubscriptExpr *ASE,
10955                             bool AllowOnePastEnd, bool IndexNegated) {
10956   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10957   if (IndexExpr->isValueDependent())
10958     return;
10959 
10960   const Type *EffectiveType =
10961       BaseExpr->getType()->getPointeeOrArrayElementType();
10962   BaseExpr = BaseExpr->IgnoreParenCasts();
10963   const ConstantArrayType *ArrayTy =
10964     Context.getAsConstantArrayType(BaseExpr->getType());
10965   if (!ArrayTy)
10966     return;
10967 
10968   llvm::APSInt index;
10969   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10970     return;
10971   if (IndexNegated)
10972     index = -index;
10973 
10974   const NamedDecl *ND = nullptr;
10975   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10976     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10977   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10978     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10979 
10980   if (index.isUnsigned() || !index.isNegative()) {
10981     llvm::APInt size = ArrayTy->getSize();
10982     if (!size.isStrictlyPositive())
10983       return;
10984 
10985     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10986     if (BaseType != EffectiveType) {
10987       // Make sure we're comparing apples to apples when comparing index to size
10988       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10989       uint64_t array_typesize = Context.getTypeSize(BaseType);
10990       // Handle ptrarith_typesize being zero, such as when casting to void*
10991       if (!ptrarith_typesize) ptrarith_typesize = 1;
10992       if (ptrarith_typesize != array_typesize) {
10993         // There's a cast to a different size type involved
10994         uint64_t ratio = array_typesize / ptrarith_typesize;
10995         // TODO: Be smarter about handling cases where array_typesize is not a
10996         // multiple of ptrarith_typesize
10997         if (ptrarith_typesize * ratio == array_typesize)
10998           size *= llvm::APInt(size.getBitWidth(), ratio);
10999       }
11000     }
11001 
11002     if (size.getBitWidth() > index.getBitWidth())
11003       index = index.zext(size.getBitWidth());
11004     else if (size.getBitWidth() < index.getBitWidth())
11005       size = size.zext(index.getBitWidth());
11006 
11007     // For array subscripting the index must be less than size, but for pointer
11008     // arithmetic also allow the index (offset) to be equal to size since
11009     // computing the next address after the end of the array is legal and
11010     // commonly done e.g. in C++ iterators and range-based for loops.
11011     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
11012       return;
11013 
11014     // Also don't warn for arrays of size 1 which are members of some
11015     // structure. These are often used to approximate flexible arrays in C89
11016     // code.
11017     if (IsTailPaddedMemberArray(*this, size, ND))
11018       return;
11019 
11020     // Suppress the warning if the subscript expression (as identified by the
11021     // ']' location) and the index expression are both from macro expansions
11022     // within a system header.
11023     if (ASE) {
11024       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
11025           ASE->getRBracketLoc());
11026       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
11027         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
11028             IndexExpr->getLocStart());
11029         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
11030           return;
11031       }
11032     }
11033 
11034     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
11035     if (ASE)
11036       DiagID = diag::warn_array_index_exceeds_bounds;
11037 
11038     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11039                         PDiag(DiagID) << index.toString(10, true)
11040                           << size.toString(10, true)
11041                           << (unsigned)size.getLimitedValue(~0U)
11042                           << IndexExpr->getSourceRange());
11043   } else {
11044     unsigned DiagID = diag::warn_array_index_precedes_bounds;
11045     if (!ASE) {
11046       DiagID = diag::warn_ptr_arith_precedes_bounds;
11047       if (index.isNegative()) index = -index;
11048     }
11049 
11050     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
11051                         PDiag(DiagID) << index.toString(10, true)
11052                           << IndexExpr->getSourceRange());
11053   }
11054 
11055   if (!ND) {
11056     // Try harder to find a NamedDecl to point at in the note.
11057     while (const ArraySubscriptExpr *ASE =
11058            dyn_cast<ArraySubscriptExpr>(BaseExpr))
11059       BaseExpr = ASE->getBase()->IgnoreParenCasts();
11060     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
11061       ND = dyn_cast<NamedDecl>(DRE->getDecl());
11062     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
11063       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
11064   }
11065 
11066   if (ND)
11067     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
11068                         PDiag(diag::note_array_index_out_of_bounds)
11069                           << ND->getDeclName());
11070 }
11071 
11072 void Sema::CheckArrayAccess(const Expr *expr) {
11073   int AllowOnePastEnd = 0;
11074   while (expr) {
11075     expr = expr->IgnoreParenImpCasts();
11076     switch (expr->getStmtClass()) {
11077       case Stmt::ArraySubscriptExprClass: {
11078         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11079         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11080                          AllowOnePastEnd > 0);
11081         return;
11082       }
11083       case Stmt::OMPArraySectionExprClass: {
11084         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11085         if (ASE->getLowerBound())
11086           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11087                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11088         return;
11089       }
11090       case Stmt::UnaryOperatorClass: {
11091         // Only unwrap the * and & unary operators
11092         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11093         expr = UO->getSubExpr();
11094         switch (UO->getOpcode()) {
11095           case UO_AddrOf:
11096             AllowOnePastEnd++;
11097             break;
11098           case UO_Deref:
11099             AllowOnePastEnd--;
11100             break;
11101           default:
11102             return;
11103         }
11104         break;
11105       }
11106       case Stmt::ConditionalOperatorClass: {
11107         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11108         if (const Expr *lhs = cond->getLHS())
11109           CheckArrayAccess(lhs);
11110         if (const Expr *rhs = cond->getRHS())
11111           CheckArrayAccess(rhs);
11112         return;
11113       }
11114       case Stmt::CXXOperatorCallExprClass: {
11115         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11116         for (const auto *Arg : OCE->arguments())
11117           CheckArrayAccess(Arg);
11118         return;
11119       }
11120       default:
11121         return;
11122     }
11123   }
11124 }
11125 
11126 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11127 
11128 namespace {
11129   struct RetainCycleOwner {
11130     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
11131     VarDecl *Variable;
11132     SourceRange Range;
11133     SourceLocation Loc;
11134     bool Indirect;
11135 
11136     void setLocsFrom(Expr *e) {
11137       Loc = e->getExprLoc();
11138       Range = e->getSourceRange();
11139     }
11140   };
11141 } // end anonymous namespace
11142 
11143 /// Consider whether capturing the given variable can possibly lead to
11144 /// a retain cycle.
11145 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11146   // In ARC, it's captured strongly iff the variable has __strong
11147   // lifetime.  In MRR, it's captured strongly if the variable is
11148   // __block and has an appropriate type.
11149   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11150     return false;
11151 
11152   owner.Variable = var;
11153   if (ref)
11154     owner.setLocsFrom(ref);
11155   return true;
11156 }
11157 
11158 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11159   while (true) {
11160     e = e->IgnoreParens();
11161     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11162       switch (cast->getCastKind()) {
11163       case CK_BitCast:
11164       case CK_LValueBitCast:
11165       case CK_LValueToRValue:
11166       case CK_ARCReclaimReturnedObject:
11167         e = cast->getSubExpr();
11168         continue;
11169 
11170       default:
11171         return false;
11172       }
11173     }
11174 
11175     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11176       ObjCIvarDecl *ivar = ref->getDecl();
11177       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11178         return false;
11179 
11180       // Try to find a retain cycle in the base.
11181       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11182         return false;
11183 
11184       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11185       owner.Indirect = true;
11186       return true;
11187     }
11188 
11189     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11190       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11191       if (!var) return false;
11192       return considerVariable(var, ref, owner);
11193     }
11194 
11195     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11196       if (member->isArrow()) return false;
11197 
11198       // Don't count this as an indirect ownership.
11199       e = member->getBase();
11200       continue;
11201     }
11202 
11203     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11204       // Only pay attention to pseudo-objects on property references.
11205       ObjCPropertyRefExpr *pre
11206         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11207                                               ->IgnoreParens());
11208       if (!pre) return false;
11209       if (pre->isImplicitProperty()) return false;
11210       ObjCPropertyDecl *property = pre->getExplicitProperty();
11211       if (!property->isRetaining() &&
11212           !(property->getPropertyIvarDecl() &&
11213             property->getPropertyIvarDecl()->getType()
11214               .getObjCLifetime() == Qualifiers::OCL_Strong))
11215           return false;
11216 
11217       owner.Indirect = true;
11218       if (pre->isSuperReceiver()) {
11219         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11220         if (!owner.Variable)
11221           return false;
11222         owner.Loc = pre->getLocation();
11223         owner.Range = pre->getSourceRange();
11224         return true;
11225       }
11226       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11227                               ->getSourceExpr());
11228       continue;
11229     }
11230 
11231     // Array ivars?
11232 
11233     return false;
11234   }
11235 }
11236 
11237 namespace {
11238   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11239     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11240       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11241         Context(Context), Variable(variable), Capturer(nullptr),
11242         VarWillBeReased(false) {}
11243     ASTContext &Context;
11244     VarDecl *Variable;
11245     Expr *Capturer;
11246     bool VarWillBeReased;
11247 
11248     void VisitDeclRefExpr(DeclRefExpr *ref) {
11249       if (ref->getDecl() == Variable && !Capturer)
11250         Capturer = ref;
11251     }
11252 
11253     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11254       if (Capturer) return;
11255       Visit(ref->getBase());
11256       if (Capturer && ref->isFreeIvar())
11257         Capturer = ref;
11258     }
11259 
11260     void VisitBlockExpr(BlockExpr *block) {
11261       // Look inside nested blocks
11262       if (block->getBlockDecl()->capturesVariable(Variable))
11263         Visit(block->getBlockDecl()->getBody());
11264     }
11265 
11266     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11267       if (Capturer) return;
11268       if (OVE->getSourceExpr())
11269         Visit(OVE->getSourceExpr());
11270     }
11271     void VisitBinaryOperator(BinaryOperator *BinOp) {
11272       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11273         return;
11274       Expr *LHS = BinOp->getLHS();
11275       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11276         if (DRE->getDecl() != Variable)
11277           return;
11278         if (Expr *RHS = BinOp->getRHS()) {
11279           RHS = RHS->IgnoreParenCasts();
11280           llvm::APSInt Value;
11281           VarWillBeReased =
11282             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11283         }
11284       }
11285     }
11286   };
11287 } // end anonymous namespace
11288 
11289 /// Check whether the given argument is a block which captures a
11290 /// variable.
11291 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11292   assert(owner.Variable && owner.Loc.isValid());
11293 
11294   e = e->IgnoreParenCasts();
11295 
11296   // Look through [^{...} copy] and Block_copy(^{...}).
11297   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11298     Selector Cmd = ME->getSelector();
11299     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11300       e = ME->getInstanceReceiver();
11301       if (!e)
11302         return nullptr;
11303       e = e->IgnoreParenCasts();
11304     }
11305   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11306     if (CE->getNumArgs() == 1) {
11307       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11308       if (Fn) {
11309         const IdentifierInfo *FnI = Fn->getIdentifier();
11310         if (FnI && FnI->isStr("_Block_copy")) {
11311           e = CE->getArg(0)->IgnoreParenCasts();
11312         }
11313       }
11314     }
11315   }
11316 
11317   BlockExpr *block = dyn_cast<BlockExpr>(e);
11318   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11319     return nullptr;
11320 
11321   FindCaptureVisitor visitor(S.Context, owner.Variable);
11322   visitor.Visit(block->getBlockDecl()->getBody());
11323   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11324 }
11325 
11326 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11327                                 RetainCycleOwner &owner) {
11328   assert(capturer);
11329   assert(owner.Variable && owner.Loc.isValid());
11330 
11331   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11332     << owner.Variable << capturer->getSourceRange();
11333   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11334     << owner.Indirect << owner.Range;
11335 }
11336 
11337 /// Check for a keyword selector that starts with the word 'add' or
11338 /// 'set'.
11339 static bool isSetterLikeSelector(Selector sel) {
11340   if (sel.isUnarySelector()) return false;
11341 
11342   StringRef str = sel.getNameForSlot(0);
11343   while (!str.empty() && str.front() == '_') str = str.substr(1);
11344   if (str.startswith("set"))
11345     str = str.substr(3);
11346   else if (str.startswith("add")) {
11347     // Specially whitelist 'addOperationWithBlock:'.
11348     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11349       return false;
11350     str = str.substr(3);
11351   }
11352   else
11353     return false;
11354 
11355   if (str.empty()) return true;
11356   return !isLowercase(str.front());
11357 }
11358 
11359 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11360                                                     ObjCMessageExpr *Message) {
11361   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11362                                                 Message->getReceiverInterface(),
11363                                                 NSAPI::ClassId_NSMutableArray);
11364   if (!IsMutableArray) {
11365     return None;
11366   }
11367 
11368   Selector Sel = Message->getSelector();
11369 
11370   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11371     S.NSAPIObj->getNSArrayMethodKind(Sel);
11372   if (!MKOpt) {
11373     return None;
11374   }
11375 
11376   NSAPI::NSArrayMethodKind MK = *MKOpt;
11377 
11378   switch (MK) {
11379     case NSAPI::NSMutableArr_addObject:
11380     case NSAPI::NSMutableArr_insertObjectAtIndex:
11381     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11382       return 0;
11383     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11384       return 1;
11385 
11386     default:
11387       return None;
11388   }
11389 
11390   return None;
11391 }
11392 
11393 static
11394 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11395                                                   ObjCMessageExpr *Message) {
11396   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11397                                             Message->getReceiverInterface(),
11398                                             NSAPI::ClassId_NSMutableDictionary);
11399   if (!IsMutableDictionary) {
11400     return None;
11401   }
11402 
11403   Selector Sel = Message->getSelector();
11404 
11405   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11406     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11407   if (!MKOpt) {
11408     return None;
11409   }
11410 
11411   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11412 
11413   switch (MK) {
11414     case NSAPI::NSMutableDict_setObjectForKey:
11415     case NSAPI::NSMutableDict_setValueForKey:
11416     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11417       return 0;
11418 
11419     default:
11420       return None;
11421   }
11422 
11423   return None;
11424 }
11425 
11426 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11427   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11428                                                 Message->getReceiverInterface(),
11429                                                 NSAPI::ClassId_NSMutableSet);
11430 
11431   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11432                                             Message->getReceiverInterface(),
11433                                             NSAPI::ClassId_NSMutableOrderedSet);
11434   if (!IsMutableSet && !IsMutableOrderedSet) {
11435     return None;
11436   }
11437 
11438   Selector Sel = Message->getSelector();
11439 
11440   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11441   if (!MKOpt) {
11442     return None;
11443   }
11444 
11445   NSAPI::NSSetMethodKind MK = *MKOpt;
11446 
11447   switch (MK) {
11448     case NSAPI::NSMutableSet_addObject:
11449     case NSAPI::NSOrderedSet_setObjectAtIndex:
11450     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11451     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11452       return 0;
11453     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11454       return 1;
11455   }
11456 
11457   return None;
11458 }
11459 
11460 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11461   if (!Message->isInstanceMessage()) {
11462     return;
11463   }
11464 
11465   Optional<int> ArgOpt;
11466 
11467   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11468       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11469       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11470     return;
11471   }
11472 
11473   int ArgIndex = *ArgOpt;
11474 
11475   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11476   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11477     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11478   }
11479 
11480   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11481     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11482       if (ArgRE->isObjCSelfExpr()) {
11483         Diag(Message->getSourceRange().getBegin(),
11484              diag::warn_objc_circular_container)
11485           << ArgRE->getDecl()->getName() << StringRef("super");
11486       }
11487     }
11488   } else {
11489     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11490 
11491     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11492       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11493     }
11494 
11495     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11496       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11497         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11498           ValueDecl *Decl = ReceiverRE->getDecl();
11499           Diag(Message->getSourceRange().getBegin(),
11500                diag::warn_objc_circular_container)
11501             << Decl->getName() << Decl->getName();
11502           if (!ArgRE->isObjCSelfExpr()) {
11503             Diag(Decl->getLocation(),
11504                  diag::note_objc_circular_container_declared_here)
11505               << Decl->getName();
11506           }
11507         }
11508       }
11509     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11510       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11511         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11512           ObjCIvarDecl *Decl = IvarRE->getDecl();
11513           Diag(Message->getSourceRange().getBegin(),
11514                diag::warn_objc_circular_container)
11515             << Decl->getName() << Decl->getName();
11516           Diag(Decl->getLocation(),
11517                diag::note_objc_circular_container_declared_here)
11518             << Decl->getName();
11519         }
11520       }
11521     }
11522   }
11523 }
11524 
11525 /// Check a message send to see if it's likely to cause a retain cycle.
11526 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11527   // Only check instance methods whose selector looks like a setter.
11528   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11529     return;
11530 
11531   // Try to find a variable that the receiver is strongly owned by.
11532   RetainCycleOwner owner;
11533   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11534     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11535       return;
11536   } else {
11537     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11538     owner.Variable = getCurMethodDecl()->getSelfDecl();
11539     owner.Loc = msg->getSuperLoc();
11540     owner.Range = msg->getSuperLoc();
11541   }
11542 
11543   // Check whether the receiver is captured by any of the arguments.
11544   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11545     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11546       return diagnoseRetainCycle(*this, capturer, owner);
11547 }
11548 
11549 /// Check a property assign to see if it's likely to cause a retain cycle.
11550 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11551   RetainCycleOwner owner;
11552   if (!findRetainCycleOwner(*this, receiver, owner))
11553     return;
11554 
11555   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11556     diagnoseRetainCycle(*this, capturer, owner);
11557 }
11558 
11559 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11560   RetainCycleOwner Owner;
11561   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11562     return;
11563 
11564   // Because we don't have an expression for the variable, we have to set the
11565   // location explicitly here.
11566   Owner.Loc = Var->getLocation();
11567   Owner.Range = Var->getSourceRange();
11568 
11569   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11570     diagnoseRetainCycle(*this, Capturer, Owner);
11571 }
11572 
11573 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11574                                      Expr *RHS, bool isProperty) {
11575   // Check if RHS is an Objective-C object literal, which also can get
11576   // immediately zapped in a weak reference.  Note that we explicitly
11577   // allow ObjCStringLiterals, since those are designed to never really die.
11578   RHS = RHS->IgnoreParenImpCasts();
11579 
11580   // This enum needs to match with the 'select' in
11581   // warn_objc_arc_literal_assign (off-by-1).
11582   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11583   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11584     return false;
11585 
11586   S.Diag(Loc, diag::warn_arc_literal_assign)
11587     << (unsigned) Kind
11588     << (isProperty ? 0 : 1)
11589     << RHS->getSourceRange();
11590 
11591   return true;
11592 }
11593 
11594 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11595                                     Qualifiers::ObjCLifetime LT,
11596                                     Expr *RHS, bool isProperty) {
11597   // Strip off any implicit cast added to get to the one ARC-specific.
11598   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11599     if (cast->getCastKind() == CK_ARCConsumeObject) {
11600       S.Diag(Loc, diag::warn_arc_retained_assign)
11601         << (LT == Qualifiers::OCL_ExplicitNone)
11602         << (isProperty ? 0 : 1)
11603         << RHS->getSourceRange();
11604       return true;
11605     }
11606     RHS = cast->getSubExpr();
11607   }
11608 
11609   if (LT == Qualifiers::OCL_Weak &&
11610       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11611     return true;
11612 
11613   return false;
11614 }
11615 
11616 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11617                               QualType LHS, Expr *RHS) {
11618   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11619 
11620   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11621     return false;
11622 
11623   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11624     return true;
11625 
11626   return false;
11627 }
11628 
11629 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11630                               Expr *LHS, Expr *RHS) {
11631   QualType LHSType;
11632   // PropertyRef on LHS type need be directly obtained from
11633   // its declaration as it has a PseudoType.
11634   ObjCPropertyRefExpr *PRE
11635     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11636   if (PRE && !PRE->isImplicitProperty()) {
11637     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11638     if (PD)
11639       LHSType = PD->getType();
11640   }
11641 
11642   if (LHSType.isNull())
11643     LHSType = LHS->getType();
11644 
11645   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11646 
11647   if (LT == Qualifiers::OCL_Weak) {
11648     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11649       getCurFunction()->markSafeWeakUse(LHS);
11650   }
11651 
11652   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11653     return;
11654 
11655   // FIXME. Check for other life times.
11656   if (LT != Qualifiers::OCL_None)
11657     return;
11658 
11659   if (PRE) {
11660     if (PRE->isImplicitProperty())
11661       return;
11662     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11663     if (!PD)
11664       return;
11665 
11666     unsigned Attributes = PD->getPropertyAttributes();
11667     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11668       // when 'assign' attribute was not explicitly specified
11669       // by user, ignore it and rely on property type itself
11670       // for lifetime info.
11671       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11672       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11673           LHSType->isObjCRetainableType())
11674         return;
11675 
11676       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11677         if (cast->getCastKind() == CK_ARCConsumeObject) {
11678           Diag(Loc, diag::warn_arc_retained_property_assign)
11679           << RHS->getSourceRange();
11680           return;
11681         }
11682         RHS = cast->getSubExpr();
11683       }
11684     }
11685     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11686       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11687         return;
11688     }
11689   }
11690 }
11691 
11692 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11693 
11694 namespace {
11695 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11696                                  SourceLocation StmtLoc,
11697                                  const NullStmt *Body) {
11698   // Do not warn if the body is a macro that expands to nothing, e.g:
11699   //
11700   // #define CALL(x)
11701   // if (condition)
11702   //   CALL(0);
11703   //
11704   if (Body->hasLeadingEmptyMacro())
11705     return false;
11706 
11707   // Get line numbers of statement and body.
11708   bool StmtLineInvalid;
11709   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11710                                                       &StmtLineInvalid);
11711   if (StmtLineInvalid)
11712     return false;
11713 
11714   bool BodyLineInvalid;
11715   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11716                                                       &BodyLineInvalid);
11717   if (BodyLineInvalid)
11718     return false;
11719 
11720   // Warn if null statement and body are on the same line.
11721   if (StmtLine != BodyLine)
11722     return false;
11723 
11724   return true;
11725 }
11726 } // end anonymous namespace
11727 
11728 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11729                                  const Stmt *Body,
11730                                  unsigned DiagID) {
11731   // Since this is a syntactic check, don't emit diagnostic for template
11732   // instantiations, this just adds noise.
11733   if (CurrentInstantiationScope)
11734     return;
11735 
11736   // The body should be a null statement.
11737   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11738   if (!NBody)
11739     return;
11740 
11741   // Do the usual checks.
11742   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11743     return;
11744 
11745   Diag(NBody->getSemiLoc(), DiagID);
11746   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11747 }
11748 
11749 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11750                                  const Stmt *PossibleBody) {
11751   assert(!CurrentInstantiationScope); // Ensured by caller
11752 
11753   SourceLocation StmtLoc;
11754   const Stmt *Body;
11755   unsigned DiagID;
11756   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11757     StmtLoc = FS->getRParenLoc();
11758     Body = FS->getBody();
11759     DiagID = diag::warn_empty_for_body;
11760   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11761     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11762     Body = WS->getBody();
11763     DiagID = diag::warn_empty_while_body;
11764   } else
11765     return; // Neither `for' nor `while'.
11766 
11767   // The body should be a null statement.
11768   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11769   if (!NBody)
11770     return;
11771 
11772   // Skip expensive checks if diagnostic is disabled.
11773   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11774     return;
11775 
11776   // Do the usual checks.
11777   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11778     return;
11779 
11780   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11781   // noise level low, emit diagnostics only if for/while is followed by a
11782   // CompoundStmt, e.g.:
11783   //    for (int i = 0; i < n; i++);
11784   //    {
11785   //      a(i);
11786   //    }
11787   // or if for/while is followed by a statement with more indentation
11788   // than for/while itself:
11789   //    for (int i = 0; i < n; i++);
11790   //      a(i);
11791   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11792   if (!ProbableTypo) {
11793     bool BodyColInvalid;
11794     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11795                              PossibleBody->getLocStart(),
11796                              &BodyColInvalid);
11797     if (BodyColInvalid)
11798       return;
11799 
11800     bool StmtColInvalid;
11801     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11802                              S->getLocStart(),
11803                              &StmtColInvalid);
11804     if (StmtColInvalid)
11805       return;
11806 
11807     if (BodyCol > StmtCol)
11808       ProbableTypo = true;
11809   }
11810 
11811   if (ProbableTypo) {
11812     Diag(NBody->getSemiLoc(), DiagID);
11813     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11814   }
11815 }
11816 
11817 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11818 
11819 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11820 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11821                              SourceLocation OpLoc) {
11822   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11823     return;
11824 
11825   if (inTemplateInstantiation())
11826     return;
11827 
11828   // Strip parens and casts away.
11829   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11830   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11831 
11832   // Check for a call expression
11833   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11834   if (!CE || CE->getNumArgs() != 1)
11835     return;
11836 
11837   // Check for a call to std::move
11838   if (!CE->isCallToStdMove())
11839     return;
11840 
11841   // Get argument from std::move
11842   RHSExpr = CE->getArg(0);
11843 
11844   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11845   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11846 
11847   // Two DeclRefExpr's, check that the decls are the same.
11848   if (LHSDeclRef && RHSDeclRef) {
11849     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11850       return;
11851     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11852         RHSDeclRef->getDecl()->getCanonicalDecl())
11853       return;
11854 
11855     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11856                                         << LHSExpr->getSourceRange()
11857                                         << RHSExpr->getSourceRange();
11858     return;
11859   }
11860 
11861   // Member variables require a different approach to check for self moves.
11862   // MemberExpr's are the same if every nested MemberExpr refers to the same
11863   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11864   // the base Expr's are CXXThisExpr's.
11865   const Expr *LHSBase = LHSExpr;
11866   const Expr *RHSBase = RHSExpr;
11867   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11868   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11869   if (!LHSME || !RHSME)
11870     return;
11871 
11872   while (LHSME && RHSME) {
11873     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11874         RHSME->getMemberDecl()->getCanonicalDecl())
11875       return;
11876 
11877     LHSBase = LHSME->getBase();
11878     RHSBase = RHSME->getBase();
11879     LHSME = dyn_cast<MemberExpr>(LHSBase);
11880     RHSME = dyn_cast<MemberExpr>(RHSBase);
11881   }
11882 
11883   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11884   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11885   if (LHSDeclRef && RHSDeclRef) {
11886     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11887       return;
11888     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11889         RHSDeclRef->getDecl()->getCanonicalDecl())
11890       return;
11891 
11892     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11893                                         << LHSExpr->getSourceRange()
11894                                         << RHSExpr->getSourceRange();
11895     return;
11896   }
11897 
11898   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11899     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11900                                         << LHSExpr->getSourceRange()
11901                                         << RHSExpr->getSourceRange();
11902 }
11903 
11904 //===--- Layout compatibility ----------------------------------------------//
11905 
11906 namespace {
11907 
11908 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11909 
11910 /// \brief Check if two enumeration types are layout-compatible.
11911 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11912   // C++11 [dcl.enum] p8:
11913   // Two enumeration types are layout-compatible if they have the same
11914   // underlying type.
11915   return ED1->isComplete() && ED2->isComplete() &&
11916          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11917 }
11918 
11919 /// \brief Check if two fields are layout-compatible.
11920 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11921   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11922     return false;
11923 
11924   if (Field1->isBitField() != Field2->isBitField())
11925     return false;
11926 
11927   if (Field1->isBitField()) {
11928     // Make sure that the bit-fields are the same length.
11929     unsigned Bits1 = Field1->getBitWidthValue(C);
11930     unsigned Bits2 = Field2->getBitWidthValue(C);
11931 
11932     if (Bits1 != Bits2)
11933       return false;
11934   }
11935 
11936   return true;
11937 }
11938 
11939 /// \brief Check if two standard-layout structs are layout-compatible.
11940 /// (C++11 [class.mem] p17)
11941 bool isLayoutCompatibleStruct(ASTContext &C,
11942                               RecordDecl *RD1,
11943                               RecordDecl *RD2) {
11944   // If both records are C++ classes, check that base classes match.
11945   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11946     // If one of records is a CXXRecordDecl we are in C++ mode,
11947     // thus the other one is a CXXRecordDecl, too.
11948     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11949     // Check number of base classes.
11950     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11951       return false;
11952 
11953     // Check the base classes.
11954     for (CXXRecordDecl::base_class_const_iterator
11955                Base1 = D1CXX->bases_begin(),
11956            BaseEnd1 = D1CXX->bases_end(),
11957               Base2 = D2CXX->bases_begin();
11958          Base1 != BaseEnd1;
11959          ++Base1, ++Base2) {
11960       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11961         return false;
11962     }
11963   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11964     // If only RD2 is a C++ class, it should have zero base classes.
11965     if (D2CXX->getNumBases() > 0)
11966       return false;
11967   }
11968 
11969   // Check the fields.
11970   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11971                              Field2End = RD2->field_end(),
11972                              Field1 = RD1->field_begin(),
11973                              Field1End = RD1->field_end();
11974   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11975     if (!isLayoutCompatible(C, *Field1, *Field2))
11976       return false;
11977   }
11978   if (Field1 != Field1End || Field2 != Field2End)
11979     return false;
11980 
11981   return true;
11982 }
11983 
11984 /// \brief Check if two standard-layout unions are layout-compatible.
11985 /// (C++11 [class.mem] p18)
11986 bool isLayoutCompatibleUnion(ASTContext &C,
11987                              RecordDecl *RD1,
11988                              RecordDecl *RD2) {
11989   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11990   for (auto *Field2 : RD2->fields())
11991     UnmatchedFields.insert(Field2);
11992 
11993   for (auto *Field1 : RD1->fields()) {
11994     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11995         I = UnmatchedFields.begin(),
11996         E = UnmatchedFields.end();
11997 
11998     for ( ; I != E; ++I) {
11999       if (isLayoutCompatible(C, Field1, *I)) {
12000         bool Result = UnmatchedFields.erase(*I);
12001         (void) Result;
12002         assert(Result);
12003         break;
12004       }
12005     }
12006     if (I == E)
12007       return false;
12008   }
12009 
12010   return UnmatchedFields.empty();
12011 }
12012 
12013 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
12014   if (RD1->isUnion() != RD2->isUnion())
12015     return false;
12016 
12017   if (RD1->isUnion())
12018     return isLayoutCompatibleUnion(C, RD1, RD2);
12019   else
12020     return isLayoutCompatibleStruct(C, RD1, RD2);
12021 }
12022 
12023 /// \brief Check if two types are layout-compatible in C++11 sense.
12024 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
12025   if (T1.isNull() || T2.isNull())
12026     return false;
12027 
12028   // C++11 [basic.types] p11:
12029   // If two types T1 and T2 are the same type, then T1 and T2 are
12030   // layout-compatible types.
12031   if (C.hasSameType(T1, T2))
12032     return true;
12033 
12034   T1 = T1.getCanonicalType().getUnqualifiedType();
12035   T2 = T2.getCanonicalType().getUnqualifiedType();
12036 
12037   const Type::TypeClass TC1 = T1->getTypeClass();
12038   const Type::TypeClass TC2 = T2->getTypeClass();
12039 
12040   if (TC1 != TC2)
12041     return false;
12042 
12043   if (TC1 == Type::Enum) {
12044     return isLayoutCompatible(C,
12045                               cast<EnumType>(T1)->getDecl(),
12046                               cast<EnumType>(T2)->getDecl());
12047   } else if (TC1 == Type::Record) {
12048     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
12049       return false;
12050 
12051     return isLayoutCompatible(C,
12052                               cast<RecordType>(T1)->getDecl(),
12053                               cast<RecordType>(T2)->getDecl());
12054   }
12055 
12056   return false;
12057 }
12058 } // end anonymous namespace
12059 
12060 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
12061 
12062 namespace {
12063 /// \brief Given a type tag expression find the type tag itself.
12064 ///
12065 /// \param TypeExpr Type tag expression, as it appears in user's code.
12066 ///
12067 /// \param VD Declaration of an identifier that appears in a type tag.
12068 ///
12069 /// \param MagicValue Type tag magic value.
12070 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12071                      const ValueDecl **VD, uint64_t *MagicValue) {
12072   while(true) {
12073     if (!TypeExpr)
12074       return false;
12075 
12076     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12077 
12078     switch (TypeExpr->getStmtClass()) {
12079     case Stmt::UnaryOperatorClass: {
12080       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12081       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12082         TypeExpr = UO->getSubExpr();
12083         continue;
12084       }
12085       return false;
12086     }
12087 
12088     case Stmt::DeclRefExprClass: {
12089       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12090       *VD = DRE->getDecl();
12091       return true;
12092     }
12093 
12094     case Stmt::IntegerLiteralClass: {
12095       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12096       llvm::APInt MagicValueAPInt = IL->getValue();
12097       if (MagicValueAPInt.getActiveBits() <= 64) {
12098         *MagicValue = MagicValueAPInt.getZExtValue();
12099         return true;
12100       } else
12101         return false;
12102     }
12103 
12104     case Stmt::BinaryConditionalOperatorClass:
12105     case Stmt::ConditionalOperatorClass: {
12106       const AbstractConditionalOperator *ACO =
12107           cast<AbstractConditionalOperator>(TypeExpr);
12108       bool Result;
12109       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12110         if (Result)
12111           TypeExpr = ACO->getTrueExpr();
12112         else
12113           TypeExpr = ACO->getFalseExpr();
12114         continue;
12115       }
12116       return false;
12117     }
12118 
12119     case Stmt::BinaryOperatorClass: {
12120       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12121       if (BO->getOpcode() == BO_Comma) {
12122         TypeExpr = BO->getRHS();
12123         continue;
12124       }
12125       return false;
12126     }
12127 
12128     default:
12129       return false;
12130     }
12131   }
12132 }
12133 
12134 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12135 ///
12136 /// \param TypeExpr Expression that specifies a type tag.
12137 ///
12138 /// \param MagicValues Registered magic values.
12139 ///
12140 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12141 ///        kind.
12142 ///
12143 /// \param TypeInfo Information about the corresponding C type.
12144 ///
12145 /// \returns true if the corresponding C type was found.
12146 bool GetMatchingCType(
12147         const IdentifierInfo *ArgumentKind,
12148         const Expr *TypeExpr, const ASTContext &Ctx,
12149         const llvm::DenseMap<Sema::TypeTagMagicValue,
12150                              Sema::TypeTagData> *MagicValues,
12151         bool &FoundWrongKind,
12152         Sema::TypeTagData &TypeInfo) {
12153   FoundWrongKind = false;
12154 
12155   // Variable declaration that has type_tag_for_datatype attribute.
12156   const ValueDecl *VD = nullptr;
12157 
12158   uint64_t MagicValue;
12159 
12160   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12161     return false;
12162 
12163   if (VD) {
12164     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12165       if (I->getArgumentKind() != ArgumentKind) {
12166         FoundWrongKind = true;
12167         return false;
12168       }
12169       TypeInfo.Type = I->getMatchingCType();
12170       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12171       TypeInfo.MustBeNull = I->getMustBeNull();
12172       return true;
12173     }
12174     return false;
12175   }
12176 
12177   if (!MagicValues)
12178     return false;
12179 
12180   llvm::DenseMap<Sema::TypeTagMagicValue,
12181                  Sema::TypeTagData>::const_iterator I =
12182       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12183   if (I == MagicValues->end())
12184     return false;
12185 
12186   TypeInfo = I->second;
12187   return true;
12188 }
12189 } // end anonymous namespace
12190 
12191 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12192                                       uint64_t MagicValue, QualType Type,
12193                                       bool LayoutCompatible,
12194                                       bool MustBeNull) {
12195   if (!TypeTagForDatatypeMagicValues)
12196     TypeTagForDatatypeMagicValues.reset(
12197         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12198 
12199   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12200   (*TypeTagForDatatypeMagicValues)[Magic] =
12201       TypeTagData(Type, LayoutCompatible, MustBeNull);
12202 }
12203 
12204 namespace {
12205 bool IsSameCharType(QualType T1, QualType T2) {
12206   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12207   if (!BT1)
12208     return false;
12209 
12210   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12211   if (!BT2)
12212     return false;
12213 
12214   BuiltinType::Kind T1Kind = BT1->getKind();
12215   BuiltinType::Kind T2Kind = BT2->getKind();
12216 
12217   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12218          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12219          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12220          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12221 }
12222 } // end anonymous namespace
12223 
12224 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12225                                     const Expr * const *ExprArgs) {
12226   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12227   bool IsPointerAttr = Attr->getIsPointer();
12228 
12229   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12230   bool FoundWrongKind;
12231   TypeTagData TypeInfo;
12232   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12233                         TypeTagForDatatypeMagicValues.get(),
12234                         FoundWrongKind, TypeInfo)) {
12235     if (FoundWrongKind)
12236       Diag(TypeTagExpr->getExprLoc(),
12237            diag::warn_type_tag_for_datatype_wrong_kind)
12238         << TypeTagExpr->getSourceRange();
12239     return;
12240   }
12241 
12242   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12243   if (IsPointerAttr) {
12244     // Skip implicit cast of pointer to `void *' (as a function argument).
12245     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12246       if (ICE->getType()->isVoidPointerType() &&
12247           ICE->getCastKind() == CK_BitCast)
12248         ArgumentExpr = ICE->getSubExpr();
12249   }
12250   QualType ArgumentType = ArgumentExpr->getType();
12251 
12252   // Passing a `void*' pointer shouldn't trigger a warning.
12253   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12254     return;
12255 
12256   if (TypeInfo.MustBeNull) {
12257     // Type tag with matching void type requires a null pointer.
12258     if (!ArgumentExpr->isNullPointerConstant(Context,
12259                                              Expr::NPC_ValueDependentIsNotNull)) {
12260       Diag(ArgumentExpr->getExprLoc(),
12261            diag::warn_type_safety_null_pointer_required)
12262           << ArgumentKind->getName()
12263           << ArgumentExpr->getSourceRange()
12264           << TypeTagExpr->getSourceRange();
12265     }
12266     return;
12267   }
12268 
12269   QualType RequiredType = TypeInfo.Type;
12270   if (IsPointerAttr)
12271     RequiredType = Context.getPointerType(RequiredType);
12272 
12273   bool mismatch = false;
12274   if (!TypeInfo.LayoutCompatible) {
12275     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12276 
12277     // C++11 [basic.fundamental] p1:
12278     // Plain char, signed char, and unsigned char are three distinct types.
12279     //
12280     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12281     // char' depending on the current char signedness mode.
12282     if (mismatch)
12283       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12284                                            RequiredType->getPointeeType())) ||
12285           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12286         mismatch = false;
12287   } else
12288     if (IsPointerAttr)
12289       mismatch = !isLayoutCompatible(Context,
12290                                      ArgumentType->getPointeeType(),
12291                                      RequiredType->getPointeeType());
12292     else
12293       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12294 
12295   if (mismatch)
12296     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12297         << ArgumentType << ArgumentKind
12298         << TypeInfo.LayoutCompatible << RequiredType
12299         << ArgumentExpr->getSourceRange()
12300         << TypeTagExpr->getSourceRange();
12301 }
12302 
12303 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12304                                          CharUnits Alignment) {
12305   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12306 }
12307 
12308 void Sema::DiagnoseMisalignedMembers() {
12309   for (MisalignedMember &m : MisalignedMembers) {
12310     const NamedDecl *ND = m.RD;
12311     if (ND->getName().empty()) {
12312       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12313         ND = TD;
12314     }
12315     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12316         << m.MD << ND << m.E->getSourceRange();
12317   }
12318   MisalignedMembers.clear();
12319 }
12320 
12321 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12322   E = E->IgnoreParens();
12323   if (!T->isPointerType() && !T->isIntegerType())
12324     return;
12325   if (isa<UnaryOperator>(E) &&
12326       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12327     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12328     if (isa<MemberExpr>(Op)) {
12329       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12330                           MisalignedMember(Op));
12331       if (MA != MisalignedMembers.end() &&
12332           (T->isIntegerType() ||
12333            (T->isPointerType() &&
12334             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12335         MisalignedMembers.erase(MA);
12336     }
12337   }
12338 }
12339 
12340 void Sema::RefersToMemberWithReducedAlignment(
12341     Expr *E,
12342     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12343         Action) {
12344   const auto *ME = dyn_cast<MemberExpr>(E);
12345   if (!ME)
12346     return;
12347 
12348   // No need to check expressions with an __unaligned-qualified type.
12349   if (E->getType().getQualifiers().hasUnaligned())
12350     return;
12351 
12352   // For a chain of MemberExpr like "a.b.c.d" this list
12353   // will keep FieldDecl's like [d, c, b].
12354   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12355   const MemberExpr *TopME = nullptr;
12356   bool AnyIsPacked = false;
12357   do {
12358     QualType BaseType = ME->getBase()->getType();
12359     if (ME->isArrow())
12360       BaseType = BaseType->getPointeeType();
12361     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12362     if (RD->isInvalidDecl())
12363       return;
12364 
12365     ValueDecl *MD = ME->getMemberDecl();
12366     auto *FD = dyn_cast<FieldDecl>(MD);
12367     // We do not care about non-data members.
12368     if (!FD || FD->isInvalidDecl())
12369       return;
12370 
12371     AnyIsPacked =
12372         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12373     ReverseMemberChain.push_back(FD);
12374 
12375     TopME = ME;
12376     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12377   } while (ME);
12378   assert(TopME && "We did not compute a topmost MemberExpr!");
12379 
12380   // Not the scope of this diagnostic.
12381   if (!AnyIsPacked)
12382     return;
12383 
12384   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12385   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12386   // TODO: The innermost base of the member expression may be too complicated.
12387   // For now, just disregard these cases. This is left for future
12388   // improvement.
12389   if (!DRE && !isa<CXXThisExpr>(TopBase))
12390       return;
12391 
12392   // Alignment expected by the whole expression.
12393   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12394 
12395   // No need to do anything else with this case.
12396   if (ExpectedAlignment.isOne())
12397     return;
12398 
12399   // Synthesize offset of the whole access.
12400   CharUnits Offset;
12401   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12402        I++) {
12403     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12404   }
12405 
12406   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12407   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12408       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12409 
12410   // The base expression of the innermost MemberExpr may give
12411   // stronger guarantees than the class containing the member.
12412   if (DRE && !TopME->isArrow()) {
12413     const ValueDecl *VD = DRE->getDecl();
12414     if (!VD->getType()->isReferenceType())
12415       CompleteObjectAlignment =
12416           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12417   }
12418 
12419   // Check if the synthesized offset fulfills the alignment.
12420   if (Offset % ExpectedAlignment != 0 ||
12421       // It may fulfill the offset it but the effective alignment may still be
12422       // lower than the expected expression alignment.
12423       CompleteObjectAlignment < ExpectedAlignment) {
12424     // If this happens, we want to determine a sensible culprit of this.
12425     // Intuitively, watching the chain of member expressions from right to
12426     // left, we start with the required alignment (as required by the field
12427     // type) but some packed attribute in that chain has reduced the alignment.
12428     // It may happen that another packed structure increases it again. But if
12429     // we are here such increase has not been enough. So pointing the first
12430     // FieldDecl that either is packed or else its RecordDecl is,
12431     // seems reasonable.
12432     FieldDecl *FD = nullptr;
12433     CharUnits Alignment;
12434     for (FieldDecl *FDI : ReverseMemberChain) {
12435       if (FDI->hasAttr<PackedAttr>() ||
12436           FDI->getParent()->hasAttr<PackedAttr>()) {
12437         FD = FDI;
12438         Alignment = std::min(
12439             Context.getTypeAlignInChars(FD->getType()),
12440             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12441         break;
12442       }
12443     }
12444     assert(FD && "We did not find a packed FieldDecl!");
12445     Action(E, FD->getParent(), FD, Alignment);
12446   }
12447 }
12448 
12449 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12450   using namespace std::placeholders;
12451   RefersToMemberWithReducedAlignment(
12452       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12453                      _2, _3, _4));
12454 }
12455 
12456