1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/EvaluatedExprVisitor.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprObjC.h"
23 #include "clang/AST/ExprOpenMP.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Analysis/Analyses/FormatString.h"
27 #include "clang/Basic/CharInfo.h"
28 #include "clang/Basic/SyncScope.h"
29 #include "clang/Basic/TargetBuiltins.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallBitVector.h"
39 #include "llvm/ADT/SmallString.h"
40 #include "llvm/Support/ConvertUTF.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/Locale.h"
43 #include "llvm/Support/raw_ostream.h"
44 
45 using namespace clang;
46 using namespace sema;
47 
48 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
49                                                     unsigned ByteNo) const {
50   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
51                                Context.getTargetInfo());
52 }
53 
54 /// Checks that a call expression's argument count is the desired number.
55 /// This is useful when doing custom type-checking.  Returns true on error.
56 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
57   unsigned argCount = call->getNumArgs();
58   if (argCount == desiredArgCount) return false;
59 
60   if (argCount < desiredArgCount)
61     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
62         << 0 /*function call*/ << desiredArgCount << argCount
63         << call->getSourceRange();
64 
65   // Highlight all the excess arguments.
66   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
67                     call->getArg(argCount - 1)->getLocEnd());
68 
69   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
70     << 0 /*function call*/ << desiredArgCount << argCount
71     << call->getArg(1)->getSourceRange();
72 }
73 
74 /// Check that the first argument to __builtin_annotation is an integer
75 /// and the second argument is a non-wide string literal.
76 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
77   if (checkArgCount(S, TheCall, 2))
78     return true;
79 
80   // First argument should be an integer.
81   Expr *ValArg = TheCall->getArg(0);
82   QualType Ty = ValArg->getType();
83   if (!Ty->isIntegerType()) {
84     S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
85       << ValArg->getSourceRange();
86     return true;
87   }
88 
89   // Second argument should be a constant string.
90   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
91   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
92   if (!Literal || !Literal->isAscii()) {
93     S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
94       << StrArg->getSourceRange();
95     return true;
96   }
97 
98   TheCall->setType(Ty);
99   return false;
100 }
101 
102 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
103   // We need at least one argument.
104   if (TheCall->getNumArgs() < 1) {
105     S.Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
106         << 0 << 1 << TheCall->getNumArgs()
107         << TheCall->getCallee()->getSourceRange();
108     return true;
109   }
110 
111   // All arguments should be wide string literals.
112   for (Expr *Arg : TheCall->arguments()) {
113     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
114     if (!Literal || !Literal->isWide()) {
115       S.Diag(Arg->getLocStart(), diag::err_msvc_annotation_wide_str)
116           << Arg->getSourceRange();
117       return true;
118     }
119   }
120 
121   return false;
122 }
123 
124 /// Check that the argument to __builtin_addressof is a glvalue, and set the
125 /// result type to the corresponding pointer type.
126 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
127   if (checkArgCount(S, TheCall, 1))
128     return true;
129 
130   ExprResult Arg(TheCall->getArg(0));
131   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
132   if (ResultType.isNull())
133     return true;
134 
135   TheCall->setArg(0, Arg.get());
136   TheCall->setType(ResultType);
137   return false;
138 }
139 
140 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
141   if (checkArgCount(S, TheCall, 3))
142     return true;
143 
144   // First two arguments should be integers.
145   for (unsigned I = 0; I < 2; ++I) {
146     Expr *Arg = TheCall->getArg(I);
147     QualType Ty = Arg->getType();
148     if (!Ty->isIntegerType()) {
149       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
150           << Ty << Arg->getSourceRange();
151       return true;
152     }
153   }
154 
155   // Third argument should be a pointer to a non-const integer.
156   // IRGen correctly handles volatile, restrict, and address spaces, and
157   // the other qualifiers aren't possible.
158   {
159     Expr *Arg = TheCall->getArg(2);
160     QualType Ty = Arg->getType();
161     const auto *PtrTy = Ty->getAs<PointerType>();
162     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
163           !PtrTy->getPointeeType().isConstQualified())) {
164       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
165           << Ty << Arg->getSourceRange();
166       return true;
167     }
168   }
169 
170   return false;
171 }
172 
173 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
174 		                  CallExpr *TheCall, unsigned SizeIdx,
175                                   unsigned DstSizeIdx) {
176   if (TheCall->getNumArgs() <= SizeIdx ||
177       TheCall->getNumArgs() <= DstSizeIdx)
178     return;
179 
180   const Expr *SizeArg = TheCall->getArg(SizeIdx);
181   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
182 
183   llvm::APSInt Size, DstSize;
184 
185   // find out if both sizes are known at compile time
186   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
187       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
188     return;
189 
190   if (Size.ule(DstSize))
191     return;
192 
193   // confirmed overflow so generate the diagnostic.
194   IdentifierInfo *FnName = FDecl->getIdentifier();
195   SourceLocation SL = TheCall->getLocStart();
196   SourceRange SR = TheCall->getSourceRange();
197 
198   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
199 }
200 
201 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
202   if (checkArgCount(S, BuiltinCall, 2))
203     return true;
204 
205   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
206   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
207   Expr *Call = BuiltinCall->getArg(0);
208   Expr *Chain = BuiltinCall->getArg(1);
209 
210   if (Call->getStmtClass() != Stmt::CallExprClass) {
211     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
212         << Call->getSourceRange();
213     return true;
214   }
215 
216   auto CE = cast<CallExpr>(Call);
217   if (CE->getCallee()->getType()->isBlockPointerType()) {
218     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
219         << Call->getSourceRange();
220     return true;
221   }
222 
223   const Decl *TargetDecl = CE->getCalleeDecl();
224   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
225     if (FD->getBuiltinID()) {
226       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
227           << Call->getSourceRange();
228       return true;
229     }
230 
231   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
232     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
233         << Call->getSourceRange();
234     return true;
235   }
236 
237   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
238   if (ChainResult.isInvalid())
239     return true;
240   if (!ChainResult.get()->getType()->isPointerType()) {
241     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
242         << Chain->getSourceRange();
243     return true;
244   }
245 
246   QualType ReturnTy = CE->getCallReturnType(S.Context);
247   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
248   QualType BuiltinTy = S.Context.getFunctionType(
249       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
250   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
251 
252   Builtin =
253       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
254 
255   BuiltinCall->setType(CE->getType());
256   BuiltinCall->setValueKind(CE->getValueKind());
257   BuiltinCall->setObjectKind(CE->getObjectKind());
258   BuiltinCall->setCallee(Builtin);
259   BuiltinCall->setArg(1, ChainResult.get());
260 
261   return false;
262 }
263 
264 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
265                                      Scope::ScopeFlags NeededScopeFlags,
266                                      unsigned DiagID) {
267   // Scopes aren't available during instantiation. Fortunately, builtin
268   // functions cannot be template args so they cannot be formed through template
269   // instantiation. Therefore checking once during the parse is sufficient.
270   if (SemaRef.inTemplateInstantiation())
271     return false;
272 
273   Scope *S = SemaRef.getCurScope();
274   while (S && !S->isSEHExceptScope())
275     S = S->getParent();
276   if (!S || !(S->getFlags() & NeededScopeFlags)) {
277     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
278     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
279         << DRE->getDecl()->getIdentifier();
280     return true;
281   }
282 
283   return false;
284 }
285 
286 static inline bool isBlockPointer(Expr *Arg) {
287   return Arg->getType()->isBlockPointerType();
288 }
289 
290 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
291 /// void*, which is a requirement of device side enqueue.
292 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
293   const BlockPointerType *BPT =
294       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
295   ArrayRef<QualType> Params =
296       BPT->getPointeeType()->getAs<FunctionProtoType>()->getParamTypes();
297   unsigned ArgCounter = 0;
298   bool IllegalParams = false;
299   // Iterate through the block parameters until either one is found that is not
300   // a local void*, or the block is valid.
301   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
302        I != E; ++I, ++ArgCounter) {
303     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
304         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
305             LangAS::opencl_local) {
306       // Get the location of the error. If a block literal has been passed
307       // (BlockExpr) then we can point straight to the offending argument,
308       // else we just point to the variable reference.
309       SourceLocation ErrorLoc;
310       if (isa<BlockExpr>(BlockArg)) {
311         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
312         ErrorLoc = BD->getParamDecl(ArgCounter)->getLocStart();
313       } else if (isa<DeclRefExpr>(BlockArg)) {
314         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
315       }
316       S.Diag(ErrorLoc,
317              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
318       IllegalParams = true;
319     }
320   }
321 
322   return IllegalParams;
323 }
324 
325 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
326   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
327     S.Diag(Call->getLocStart(), diag::err_opencl_requires_extension)
328           << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
329     return true;
330   }
331   return false;
332 }
333 
334 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
335   if (checkArgCount(S, TheCall, 2))
336     return true;
337 
338   if (checkOpenCLSubgroupExt(S, TheCall))
339     return true;
340 
341   // First argument is an ndrange_t type.
342   Expr *NDRangeArg = TheCall->getArg(0);
343   if (NDRangeArg->getType().getAsString() != "ndrange_t") {
344     S.Diag(NDRangeArg->getLocStart(),
345            diag::err_opencl_builtin_expected_type)
346         << TheCall->getDirectCallee() << "'ndrange_t'";
347     return true;
348   }
349 
350   Expr *BlockArg = TheCall->getArg(1);
351   if (!isBlockPointer(BlockArg)) {
352     S.Diag(BlockArg->getLocStart(),
353            diag::err_opencl_builtin_expected_type)
354         << TheCall->getDirectCallee() << "block";
355     return true;
356   }
357   return checkOpenCLBlockArgs(S, BlockArg);
358 }
359 
360 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
361 /// get_kernel_work_group_size
362 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
363 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
364   if (checkArgCount(S, TheCall, 1))
365     return true;
366 
367   Expr *BlockArg = TheCall->getArg(0);
368   if (!isBlockPointer(BlockArg)) {
369     S.Diag(BlockArg->getLocStart(),
370            diag::err_opencl_builtin_expected_type)
371         << TheCall->getDirectCallee() << "block";
372     return true;
373   }
374   return checkOpenCLBlockArgs(S, BlockArg);
375 }
376 
377 /// Diagnose integer type and any valid implicit conversion to it.
378 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
379                                       const QualType &IntType);
380 
381 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
382                                             unsigned Start, unsigned End) {
383   bool IllegalParams = false;
384   for (unsigned I = Start; I <= End; ++I)
385     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
386                                               S.Context.getSizeType());
387   return IllegalParams;
388 }
389 
390 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
391 /// 'local void*' parameter of passed block.
392 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
393                                            Expr *BlockArg,
394                                            unsigned NumNonVarArgs) {
395   const BlockPointerType *BPT =
396       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
397   unsigned NumBlockParams =
398       BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams();
399   unsigned TotalNumArgs = TheCall->getNumArgs();
400 
401   // For each argument passed to the block, a corresponding uint needs to
402   // be passed to describe the size of the local memory.
403   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
404     S.Diag(TheCall->getLocStart(),
405            diag::err_opencl_enqueue_kernel_local_size_args);
406     return true;
407   }
408 
409   // Check that the sizes of the local memory are specified by integers.
410   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
411                                          TotalNumArgs - 1);
412 }
413 
414 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
415 /// overload formats specified in Table 6.13.17.1.
416 /// int enqueue_kernel(queue_t queue,
417 ///                    kernel_enqueue_flags_t flags,
418 ///                    const ndrange_t ndrange,
419 ///                    void (^block)(void))
420 /// int enqueue_kernel(queue_t queue,
421 ///                    kernel_enqueue_flags_t flags,
422 ///                    const ndrange_t ndrange,
423 ///                    uint num_events_in_wait_list,
424 ///                    clk_event_t *event_wait_list,
425 ///                    clk_event_t *event_ret,
426 ///                    void (^block)(void))
427 /// int enqueue_kernel(queue_t queue,
428 ///                    kernel_enqueue_flags_t flags,
429 ///                    const ndrange_t ndrange,
430 ///                    void (^block)(local void*, ...),
431 ///                    uint size0, ...)
432 /// int enqueue_kernel(queue_t queue,
433 ///                    kernel_enqueue_flags_t flags,
434 ///                    const ndrange_t ndrange,
435 ///                    uint num_events_in_wait_list,
436 ///                    clk_event_t *event_wait_list,
437 ///                    clk_event_t *event_ret,
438 ///                    void (^block)(local void*, ...),
439 ///                    uint size0, ...)
440 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
441   unsigned NumArgs = TheCall->getNumArgs();
442 
443   if (NumArgs < 4) {
444     S.Diag(TheCall->getLocStart(), diag::err_typecheck_call_too_few_args);
445     return true;
446   }
447 
448   Expr *Arg0 = TheCall->getArg(0);
449   Expr *Arg1 = TheCall->getArg(1);
450   Expr *Arg2 = TheCall->getArg(2);
451   Expr *Arg3 = TheCall->getArg(3);
452 
453   // First argument always needs to be a queue_t type.
454   if (!Arg0->getType()->isQueueT()) {
455     S.Diag(TheCall->getArg(0)->getLocStart(),
456            diag::err_opencl_builtin_expected_type)
457         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
458     return true;
459   }
460 
461   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
462   if (!Arg1->getType()->isIntegerType()) {
463     S.Diag(TheCall->getArg(1)->getLocStart(),
464            diag::err_opencl_builtin_expected_type)
465         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
466     return true;
467   }
468 
469   // Third argument is always an ndrange_t type.
470   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
471     S.Diag(TheCall->getArg(2)->getLocStart(),
472            diag::err_opencl_builtin_expected_type)
473         << TheCall->getDirectCallee() << "'ndrange_t'";
474     return true;
475   }
476 
477   // With four arguments, there is only one form that the function could be
478   // called in: no events and no variable arguments.
479   if (NumArgs == 4) {
480     // check that the last argument is the right block type.
481     if (!isBlockPointer(Arg3)) {
482       S.Diag(Arg3->getLocStart(), diag::err_opencl_builtin_expected_type)
483           << TheCall->getDirectCallee() << "block";
484       return true;
485     }
486     // we have a block type, check the prototype
487     const BlockPointerType *BPT =
488         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
489     if (BPT->getPointeeType()->getAs<FunctionProtoType>()->getNumParams() > 0) {
490       S.Diag(Arg3->getLocStart(),
491              diag::err_opencl_enqueue_kernel_blocks_no_args);
492       return true;
493     }
494     return false;
495   }
496   // we can have block + varargs.
497   if (isBlockPointer(Arg3))
498     return (checkOpenCLBlockArgs(S, Arg3) ||
499             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
500   // last two cases with either exactly 7 args or 7 args and varargs.
501   if (NumArgs >= 7) {
502     // check common block argument.
503     Expr *Arg6 = TheCall->getArg(6);
504     if (!isBlockPointer(Arg6)) {
505       S.Diag(Arg6->getLocStart(), diag::err_opencl_builtin_expected_type)
506           << TheCall->getDirectCallee() << "block";
507       return true;
508     }
509     if (checkOpenCLBlockArgs(S, Arg6))
510       return true;
511 
512     // Forth argument has to be any integer type.
513     if (!Arg3->getType()->isIntegerType()) {
514       S.Diag(TheCall->getArg(3)->getLocStart(),
515              diag::err_opencl_builtin_expected_type)
516           << TheCall->getDirectCallee() << "integer";
517       return true;
518     }
519     // check remaining common arguments.
520     Expr *Arg4 = TheCall->getArg(4);
521     Expr *Arg5 = TheCall->getArg(5);
522 
523     // Fifth argument is always passed as a pointer to clk_event_t.
524     if (!Arg4->isNullPointerConstant(S.Context,
525                                      Expr::NPC_ValueDependentIsNotNull) &&
526         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
527       S.Diag(TheCall->getArg(4)->getLocStart(),
528              diag::err_opencl_builtin_expected_type)
529           << TheCall->getDirectCallee()
530           << S.Context.getPointerType(S.Context.OCLClkEventTy);
531       return true;
532     }
533 
534     // Sixth argument is always passed as a pointer to clk_event_t.
535     if (!Arg5->isNullPointerConstant(S.Context,
536                                      Expr::NPC_ValueDependentIsNotNull) &&
537         !(Arg5->getType()->isPointerType() &&
538           Arg5->getType()->getPointeeType()->isClkEventT())) {
539       S.Diag(TheCall->getArg(5)->getLocStart(),
540              diag::err_opencl_builtin_expected_type)
541           << TheCall->getDirectCallee()
542           << S.Context.getPointerType(S.Context.OCLClkEventTy);
543       return true;
544     }
545 
546     if (NumArgs == 7)
547       return false;
548 
549     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
550   }
551 
552   // None of the specific case has been detected, give generic error
553   S.Diag(TheCall->getLocStart(),
554          diag::err_opencl_enqueue_kernel_incorrect_args);
555   return true;
556 }
557 
558 /// Returns OpenCL access qual.
559 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
560     return D->getAttr<OpenCLAccessAttr>();
561 }
562 
563 /// Returns true if pipe element type is different from the pointer.
564 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
565   const Expr *Arg0 = Call->getArg(0);
566   // First argument type should always be pipe.
567   if (!Arg0->getType()->isPipeType()) {
568     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
569         << Call->getDirectCallee() << Arg0->getSourceRange();
570     return true;
571   }
572   OpenCLAccessAttr *AccessQual =
573       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
574   // Validates the access qualifier is compatible with the call.
575   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
576   // read_only and write_only, and assumed to be read_only if no qualifier is
577   // specified.
578   switch (Call->getDirectCallee()->getBuiltinID()) {
579   case Builtin::BIread_pipe:
580   case Builtin::BIreserve_read_pipe:
581   case Builtin::BIcommit_read_pipe:
582   case Builtin::BIwork_group_reserve_read_pipe:
583   case Builtin::BIsub_group_reserve_read_pipe:
584   case Builtin::BIwork_group_commit_read_pipe:
585   case Builtin::BIsub_group_commit_read_pipe:
586     if (!(!AccessQual || AccessQual->isReadOnly())) {
587       S.Diag(Arg0->getLocStart(),
588              diag::err_opencl_builtin_pipe_invalid_access_modifier)
589           << "read_only" << Arg0->getSourceRange();
590       return true;
591     }
592     break;
593   case Builtin::BIwrite_pipe:
594   case Builtin::BIreserve_write_pipe:
595   case Builtin::BIcommit_write_pipe:
596   case Builtin::BIwork_group_reserve_write_pipe:
597   case Builtin::BIsub_group_reserve_write_pipe:
598   case Builtin::BIwork_group_commit_write_pipe:
599   case Builtin::BIsub_group_commit_write_pipe:
600     if (!(AccessQual && AccessQual->isWriteOnly())) {
601       S.Diag(Arg0->getLocStart(),
602              diag::err_opencl_builtin_pipe_invalid_access_modifier)
603           << "write_only" << Arg0->getSourceRange();
604       return true;
605     }
606     break;
607   default:
608     break;
609   }
610   return false;
611 }
612 
613 /// Returns true if pipe element type is different from the pointer.
614 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
615   const Expr *Arg0 = Call->getArg(0);
616   const Expr *ArgIdx = Call->getArg(Idx);
617   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
618   const QualType EltTy = PipeTy->getElementType();
619   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
620   // The Idx argument should be a pointer and the type of the pointer and
621   // the type of pipe element should also be the same.
622   if (!ArgTy ||
623       !S.Context.hasSameType(
624           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
625     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
626         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
627         << ArgIdx->getType() << ArgIdx->getSourceRange();
628     return true;
629   }
630   return false;
631 }
632 
633 // \brief Performs semantic analysis for the read/write_pipe call.
634 // \param S Reference to the semantic analyzer.
635 // \param Call A pointer to the builtin call.
636 // \return True if a semantic error has been found, false otherwise.
637 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
638   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
639   // functions have two forms.
640   switch (Call->getNumArgs()) {
641   case 2: {
642     if (checkOpenCLPipeArg(S, Call))
643       return true;
644     // The call with 2 arguments should be
645     // read/write_pipe(pipe T, T*).
646     // Check packet type T.
647     if (checkOpenCLPipePacketType(S, Call, 1))
648       return true;
649   } break;
650 
651   case 4: {
652     if (checkOpenCLPipeArg(S, Call))
653       return true;
654     // The call with 4 arguments should be
655     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
656     // Check reserve_id_t.
657     if (!Call->getArg(1)->getType()->isReserveIDT()) {
658       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
659           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
660           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
661       return true;
662     }
663 
664     // Check the index.
665     const Expr *Arg2 = Call->getArg(2);
666     if (!Arg2->getType()->isIntegerType() &&
667         !Arg2->getType()->isUnsignedIntegerType()) {
668       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
669           << Call->getDirectCallee() << S.Context.UnsignedIntTy
670           << Arg2->getType() << Arg2->getSourceRange();
671       return true;
672     }
673 
674     // Check packet type T.
675     if (checkOpenCLPipePacketType(S, Call, 3))
676       return true;
677   } break;
678   default:
679     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
680         << Call->getDirectCallee() << Call->getSourceRange();
681     return true;
682   }
683 
684   return false;
685 }
686 
687 // \brief Performs a semantic analysis on the {work_group_/sub_group_
688 //        /_}reserve_{read/write}_pipe
689 // \param S Reference to the semantic analyzer.
690 // \param Call The call to the builtin function to be analyzed.
691 // \return True if a semantic error was found, false otherwise.
692 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
693   if (checkArgCount(S, Call, 2))
694     return true;
695 
696   if (checkOpenCLPipeArg(S, Call))
697     return true;
698 
699   // Check the reserve size.
700   if (!Call->getArg(1)->getType()->isIntegerType() &&
701       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
702     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
703         << Call->getDirectCallee() << S.Context.UnsignedIntTy
704         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
705     return true;
706   }
707 
708   // Since return type of reserve_read/write_pipe built-in function is
709   // reserve_id_t, which is not defined in the builtin def file , we used int
710   // as return type and need to override the return type of these functions.
711   Call->setType(S.Context.OCLReserveIDTy);
712 
713   return false;
714 }
715 
716 // \brief Performs a semantic analysis on {work_group_/sub_group_
717 //        /_}commit_{read/write}_pipe
718 // \param S Reference to the semantic analyzer.
719 // \param Call The call to the builtin function to be analyzed.
720 // \return True if a semantic error was found, false otherwise.
721 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
722   if (checkArgCount(S, Call, 2))
723     return true;
724 
725   if (checkOpenCLPipeArg(S, Call))
726     return true;
727 
728   // Check reserve_id_t.
729   if (!Call->getArg(1)->getType()->isReserveIDT()) {
730     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
731         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
732         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
733     return true;
734   }
735 
736   return false;
737 }
738 
739 // \brief Performs a semantic analysis on the call to built-in Pipe
740 //        Query Functions.
741 // \param S Reference to the semantic analyzer.
742 // \param Call The call to the builtin function to be analyzed.
743 // \return True if a semantic error was found, false otherwise.
744 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
745   if (checkArgCount(S, Call, 1))
746     return true;
747 
748   if (!Call->getArg(0)->getType()->isPipeType()) {
749     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
750         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
751     return true;
752   }
753 
754   return false;
755 }
756 // \brief OpenCL v2.0 s6.13.9 - Address space qualifier functions.
757 // \brief Performs semantic analysis for the to_global/local/private call.
758 // \param S Reference to the semantic analyzer.
759 // \param BuiltinID ID of the builtin function.
760 // \param Call A pointer to the builtin call.
761 // \return True if a semantic error has been found, false otherwise.
762 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
763                                     CallExpr *Call) {
764   if (Call->getNumArgs() != 1) {
765     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_arg_num)
766         << Call->getDirectCallee() << Call->getSourceRange();
767     return true;
768   }
769 
770   auto RT = Call->getArg(0)->getType();
771   if (!RT->isPointerType() || RT->getPointeeType()
772       .getAddressSpace() == LangAS::opencl_constant) {
773     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
774         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
775     return true;
776   }
777 
778   RT = RT->getPointeeType();
779   auto Qual = RT.getQualifiers();
780   switch (BuiltinID) {
781   case Builtin::BIto_global:
782     Qual.setAddressSpace(LangAS::opencl_global);
783     break;
784   case Builtin::BIto_local:
785     Qual.setAddressSpace(LangAS::opencl_local);
786     break;
787   default:
788     Qual.removeAddressSpace();
789   }
790   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
791       RT.getUnqualifiedType(), Qual)));
792 
793   return false;
794 }
795 
796 ExprResult
797 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
798                                CallExpr *TheCall) {
799   ExprResult TheCallResult(TheCall);
800 
801   // Find out if any arguments are required to be integer constant expressions.
802   unsigned ICEArguments = 0;
803   ASTContext::GetBuiltinTypeError Error;
804   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
805   if (Error != ASTContext::GE_None)
806     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
807 
808   // If any arguments are required to be ICE's, check and diagnose.
809   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
810     // Skip arguments not required to be ICE's.
811     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
812 
813     llvm::APSInt Result;
814     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
815       return true;
816     ICEArguments &= ~(1 << ArgNo);
817   }
818 
819   switch (BuiltinID) {
820   case Builtin::BI__builtin___CFStringMakeConstantString:
821     assert(TheCall->getNumArgs() == 1 &&
822            "Wrong # arguments to builtin CFStringMakeConstantString");
823     if (CheckObjCString(TheCall->getArg(0)))
824       return ExprError();
825     break;
826   case Builtin::BI__builtin_ms_va_start:
827   case Builtin::BI__builtin_stdarg_start:
828   case Builtin::BI__builtin_va_start:
829     if (SemaBuiltinVAStart(BuiltinID, TheCall))
830       return ExprError();
831     break;
832   case Builtin::BI__va_start: {
833     switch (Context.getTargetInfo().getTriple().getArch()) {
834     case llvm::Triple::arm:
835     case llvm::Triple::thumb:
836       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
837         return ExprError();
838       break;
839     default:
840       if (SemaBuiltinVAStart(BuiltinID, TheCall))
841         return ExprError();
842       break;
843     }
844     break;
845   }
846   case Builtin::BI__builtin_isgreater:
847   case Builtin::BI__builtin_isgreaterequal:
848   case Builtin::BI__builtin_isless:
849   case Builtin::BI__builtin_islessequal:
850   case Builtin::BI__builtin_islessgreater:
851   case Builtin::BI__builtin_isunordered:
852     if (SemaBuiltinUnorderedCompare(TheCall))
853       return ExprError();
854     break;
855   case Builtin::BI__builtin_fpclassify:
856     if (SemaBuiltinFPClassification(TheCall, 6))
857       return ExprError();
858     break;
859   case Builtin::BI__builtin_isfinite:
860   case Builtin::BI__builtin_isinf:
861   case Builtin::BI__builtin_isinf_sign:
862   case Builtin::BI__builtin_isnan:
863   case Builtin::BI__builtin_isnormal:
864     if (SemaBuiltinFPClassification(TheCall, 1))
865       return ExprError();
866     break;
867   case Builtin::BI__builtin_shufflevector:
868     return SemaBuiltinShuffleVector(TheCall);
869     // TheCall will be freed by the smart pointer here, but that's fine, since
870     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
871   case Builtin::BI__builtin_prefetch:
872     if (SemaBuiltinPrefetch(TheCall))
873       return ExprError();
874     break;
875   case Builtin::BI__builtin_alloca_with_align:
876     if (SemaBuiltinAllocaWithAlign(TheCall))
877       return ExprError();
878     break;
879   case Builtin::BI__assume:
880   case Builtin::BI__builtin_assume:
881     if (SemaBuiltinAssume(TheCall))
882       return ExprError();
883     break;
884   case Builtin::BI__builtin_assume_aligned:
885     if (SemaBuiltinAssumeAligned(TheCall))
886       return ExprError();
887     break;
888   case Builtin::BI__builtin_object_size:
889     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
890       return ExprError();
891     break;
892   case Builtin::BI__builtin_longjmp:
893     if (SemaBuiltinLongjmp(TheCall))
894       return ExprError();
895     break;
896   case Builtin::BI__builtin_setjmp:
897     if (SemaBuiltinSetjmp(TheCall))
898       return ExprError();
899     break;
900   case Builtin::BI_setjmp:
901   case Builtin::BI_setjmpex:
902     if (checkArgCount(*this, TheCall, 1))
903       return true;
904     break;
905 
906   case Builtin::BI__builtin_classify_type:
907     if (checkArgCount(*this, TheCall, 1)) return true;
908     TheCall->setType(Context.IntTy);
909     break;
910   case Builtin::BI__builtin_constant_p:
911     if (checkArgCount(*this, TheCall, 1)) return true;
912     TheCall->setType(Context.IntTy);
913     break;
914   case Builtin::BI__sync_fetch_and_add:
915   case Builtin::BI__sync_fetch_and_add_1:
916   case Builtin::BI__sync_fetch_and_add_2:
917   case Builtin::BI__sync_fetch_and_add_4:
918   case Builtin::BI__sync_fetch_and_add_8:
919   case Builtin::BI__sync_fetch_and_add_16:
920   case Builtin::BI__sync_fetch_and_sub:
921   case Builtin::BI__sync_fetch_and_sub_1:
922   case Builtin::BI__sync_fetch_and_sub_2:
923   case Builtin::BI__sync_fetch_and_sub_4:
924   case Builtin::BI__sync_fetch_and_sub_8:
925   case Builtin::BI__sync_fetch_and_sub_16:
926   case Builtin::BI__sync_fetch_and_or:
927   case Builtin::BI__sync_fetch_and_or_1:
928   case Builtin::BI__sync_fetch_and_or_2:
929   case Builtin::BI__sync_fetch_and_or_4:
930   case Builtin::BI__sync_fetch_and_or_8:
931   case Builtin::BI__sync_fetch_and_or_16:
932   case Builtin::BI__sync_fetch_and_and:
933   case Builtin::BI__sync_fetch_and_and_1:
934   case Builtin::BI__sync_fetch_and_and_2:
935   case Builtin::BI__sync_fetch_and_and_4:
936   case Builtin::BI__sync_fetch_and_and_8:
937   case Builtin::BI__sync_fetch_and_and_16:
938   case Builtin::BI__sync_fetch_and_xor:
939   case Builtin::BI__sync_fetch_and_xor_1:
940   case Builtin::BI__sync_fetch_and_xor_2:
941   case Builtin::BI__sync_fetch_and_xor_4:
942   case Builtin::BI__sync_fetch_and_xor_8:
943   case Builtin::BI__sync_fetch_and_xor_16:
944   case Builtin::BI__sync_fetch_and_nand:
945   case Builtin::BI__sync_fetch_and_nand_1:
946   case Builtin::BI__sync_fetch_and_nand_2:
947   case Builtin::BI__sync_fetch_and_nand_4:
948   case Builtin::BI__sync_fetch_and_nand_8:
949   case Builtin::BI__sync_fetch_and_nand_16:
950   case Builtin::BI__sync_add_and_fetch:
951   case Builtin::BI__sync_add_and_fetch_1:
952   case Builtin::BI__sync_add_and_fetch_2:
953   case Builtin::BI__sync_add_and_fetch_4:
954   case Builtin::BI__sync_add_and_fetch_8:
955   case Builtin::BI__sync_add_and_fetch_16:
956   case Builtin::BI__sync_sub_and_fetch:
957   case Builtin::BI__sync_sub_and_fetch_1:
958   case Builtin::BI__sync_sub_and_fetch_2:
959   case Builtin::BI__sync_sub_and_fetch_4:
960   case Builtin::BI__sync_sub_and_fetch_8:
961   case Builtin::BI__sync_sub_and_fetch_16:
962   case Builtin::BI__sync_and_and_fetch:
963   case Builtin::BI__sync_and_and_fetch_1:
964   case Builtin::BI__sync_and_and_fetch_2:
965   case Builtin::BI__sync_and_and_fetch_4:
966   case Builtin::BI__sync_and_and_fetch_8:
967   case Builtin::BI__sync_and_and_fetch_16:
968   case Builtin::BI__sync_or_and_fetch:
969   case Builtin::BI__sync_or_and_fetch_1:
970   case Builtin::BI__sync_or_and_fetch_2:
971   case Builtin::BI__sync_or_and_fetch_4:
972   case Builtin::BI__sync_or_and_fetch_8:
973   case Builtin::BI__sync_or_and_fetch_16:
974   case Builtin::BI__sync_xor_and_fetch:
975   case Builtin::BI__sync_xor_and_fetch_1:
976   case Builtin::BI__sync_xor_and_fetch_2:
977   case Builtin::BI__sync_xor_and_fetch_4:
978   case Builtin::BI__sync_xor_and_fetch_8:
979   case Builtin::BI__sync_xor_and_fetch_16:
980   case Builtin::BI__sync_nand_and_fetch:
981   case Builtin::BI__sync_nand_and_fetch_1:
982   case Builtin::BI__sync_nand_and_fetch_2:
983   case Builtin::BI__sync_nand_and_fetch_4:
984   case Builtin::BI__sync_nand_and_fetch_8:
985   case Builtin::BI__sync_nand_and_fetch_16:
986   case Builtin::BI__sync_val_compare_and_swap:
987   case Builtin::BI__sync_val_compare_and_swap_1:
988   case Builtin::BI__sync_val_compare_and_swap_2:
989   case Builtin::BI__sync_val_compare_and_swap_4:
990   case Builtin::BI__sync_val_compare_and_swap_8:
991   case Builtin::BI__sync_val_compare_and_swap_16:
992   case Builtin::BI__sync_bool_compare_and_swap:
993   case Builtin::BI__sync_bool_compare_and_swap_1:
994   case Builtin::BI__sync_bool_compare_and_swap_2:
995   case Builtin::BI__sync_bool_compare_and_swap_4:
996   case Builtin::BI__sync_bool_compare_and_swap_8:
997   case Builtin::BI__sync_bool_compare_and_swap_16:
998   case Builtin::BI__sync_lock_test_and_set:
999   case Builtin::BI__sync_lock_test_and_set_1:
1000   case Builtin::BI__sync_lock_test_and_set_2:
1001   case Builtin::BI__sync_lock_test_and_set_4:
1002   case Builtin::BI__sync_lock_test_and_set_8:
1003   case Builtin::BI__sync_lock_test_and_set_16:
1004   case Builtin::BI__sync_lock_release:
1005   case Builtin::BI__sync_lock_release_1:
1006   case Builtin::BI__sync_lock_release_2:
1007   case Builtin::BI__sync_lock_release_4:
1008   case Builtin::BI__sync_lock_release_8:
1009   case Builtin::BI__sync_lock_release_16:
1010   case Builtin::BI__sync_swap:
1011   case Builtin::BI__sync_swap_1:
1012   case Builtin::BI__sync_swap_2:
1013   case Builtin::BI__sync_swap_4:
1014   case Builtin::BI__sync_swap_8:
1015   case Builtin::BI__sync_swap_16:
1016     return SemaBuiltinAtomicOverloaded(TheCallResult);
1017   case Builtin::BI__builtin_nontemporal_load:
1018   case Builtin::BI__builtin_nontemporal_store:
1019     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1020 #define BUILTIN(ID, TYPE, ATTRS)
1021 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1022   case Builtin::BI##ID: \
1023     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1024 #include "clang/Basic/Builtins.def"
1025   case Builtin::BI__annotation:
1026     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1027       return ExprError();
1028     break;
1029   case Builtin::BI__builtin_annotation:
1030     if (SemaBuiltinAnnotation(*this, TheCall))
1031       return ExprError();
1032     break;
1033   case Builtin::BI__builtin_addressof:
1034     if (SemaBuiltinAddressof(*this, TheCall))
1035       return ExprError();
1036     break;
1037   case Builtin::BI__builtin_add_overflow:
1038   case Builtin::BI__builtin_sub_overflow:
1039   case Builtin::BI__builtin_mul_overflow:
1040     if (SemaBuiltinOverflow(*this, TheCall))
1041       return ExprError();
1042     break;
1043   case Builtin::BI__builtin_operator_new:
1044   case Builtin::BI__builtin_operator_delete:
1045     if (!getLangOpts().CPlusPlus) {
1046       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
1047         << (BuiltinID == Builtin::BI__builtin_operator_new
1048                 ? "__builtin_operator_new"
1049                 : "__builtin_operator_delete")
1050         << "C++";
1051       return ExprError();
1052     }
1053     // CodeGen assumes it can find the global new and delete to call,
1054     // so ensure that they are declared.
1055     DeclareGlobalNewDelete();
1056     break;
1057 
1058   // check secure string manipulation functions where overflows
1059   // are detectable at compile time
1060   case Builtin::BI__builtin___memcpy_chk:
1061   case Builtin::BI__builtin___memmove_chk:
1062   case Builtin::BI__builtin___memset_chk:
1063   case Builtin::BI__builtin___strlcat_chk:
1064   case Builtin::BI__builtin___strlcpy_chk:
1065   case Builtin::BI__builtin___strncat_chk:
1066   case Builtin::BI__builtin___strncpy_chk:
1067   case Builtin::BI__builtin___stpncpy_chk:
1068     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
1069     break;
1070   case Builtin::BI__builtin___memccpy_chk:
1071     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
1072     break;
1073   case Builtin::BI__builtin___snprintf_chk:
1074   case Builtin::BI__builtin___vsnprintf_chk:
1075     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
1076     break;
1077   case Builtin::BI__builtin_call_with_static_chain:
1078     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1079       return ExprError();
1080     break;
1081   case Builtin::BI__exception_code:
1082   case Builtin::BI_exception_code:
1083     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1084                                  diag::err_seh___except_block))
1085       return ExprError();
1086     break;
1087   case Builtin::BI__exception_info:
1088   case Builtin::BI_exception_info:
1089     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1090                                  diag::err_seh___except_filter))
1091       return ExprError();
1092     break;
1093   case Builtin::BI__GetExceptionInfo:
1094     if (checkArgCount(*this, TheCall, 1))
1095       return ExprError();
1096 
1097     if (CheckCXXThrowOperand(
1098             TheCall->getLocStart(),
1099             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1100             TheCall))
1101       return ExprError();
1102 
1103     TheCall->setType(Context.VoidPtrTy);
1104     break;
1105   // OpenCL v2.0, s6.13.16 - Pipe functions
1106   case Builtin::BIread_pipe:
1107   case Builtin::BIwrite_pipe:
1108     // Since those two functions are declared with var args, we need a semantic
1109     // check for the argument.
1110     if (SemaBuiltinRWPipe(*this, TheCall))
1111       return ExprError();
1112     TheCall->setType(Context.IntTy);
1113     break;
1114   case Builtin::BIreserve_read_pipe:
1115   case Builtin::BIreserve_write_pipe:
1116   case Builtin::BIwork_group_reserve_read_pipe:
1117   case Builtin::BIwork_group_reserve_write_pipe:
1118     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1119       return ExprError();
1120     break;
1121   case Builtin::BIsub_group_reserve_read_pipe:
1122   case Builtin::BIsub_group_reserve_write_pipe:
1123     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1124         SemaBuiltinReserveRWPipe(*this, TheCall))
1125       return ExprError();
1126     break;
1127   case Builtin::BIcommit_read_pipe:
1128   case Builtin::BIcommit_write_pipe:
1129   case Builtin::BIwork_group_commit_read_pipe:
1130   case Builtin::BIwork_group_commit_write_pipe:
1131     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1132       return ExprError();
1133     break;
1134   case Builtin::BIsub_group_commit_read_pipe:
1135   case Builtin::BIsub_group_commit_write_pipe:
1136     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1137         SemaBuiltinCommitRWPipe(*this, TheCall))
1138       return ExprError();
1139     break;
1140   case Builtin::BIget_pipe_num_packets:
1141   case Builtin::BIget_pipe_max_packets:
1142     if (SemaBuiltinPipePackets(*this, TheCall))
1143       return ExprError();
1144     TheCall->setType(Context.UnsignedIntTy);
1145     break;
1146   case Builtin::BIto_global:
1147   case Builtin::BIto_local:
1148   case Builtin::BIto_private:
1149     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1150       return ExprError();
1151     break;
1152   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1153   case Builtin::BIenqueue_kernel:
1154     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1155       return ExprError();
1156     break;
1157   case Builtin::BIget_kernel_work_group_size:
1158   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1159     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1160       return ExprError();
1161     break;
1162     break;
1163   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1164   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1165     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1166       return ExprError();
1167     break;
1168   case Builtin::BI__builtin_os_log_format:
1169   case Builtin::BI__builtin_os_log_format_buffer_size:
1170     if (SemaBuiltinOSLogFormat(TheCall)) {
1171       return ExprError();
1172     }
1173     break;
1174   }
1175 
1176   // Since the target specific builtins for each arch overlap, only check those
1177   // of the arch we are compiling for.
1178   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1179     switch (Context.getTargetInfo().getTriple().getArch()) {
1180       case llvm::Triple::arm:
1181       case llvm::Triple::armeb:
1182       case llvm::Triple::thumb:
1183       case llvm::Triple::thumbeb:
1184         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1185           return ExprError();
1186         break;
1187       case llvm::Triple::aarch64:
1188       case llvm::Triple::aarch64_be:
1189         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1190           return ExprError();
1191         break;
1192       case llvm::Triple::mips:
1193       case llvm::Triple::mipsel:
1194       case llvm::Triple::mips64:
1195       case llvm::Triple::mips64el:
1196         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1197           return ExprError();
1198         break;
1199       case llvm::Triple::systemz:
1200         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1201           return ExprError();
1202         break;
1203       case llvm::Triple::x86:
1204       case llvm::Triple::x86_64:
1205         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1206           return ExprError();
1207         break;
1208       case llvm::Triple::ppc:
1209       case llvm::Triple::ppc64:
1210       case llvm::Triple::ppc64le:
1211         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1212           return ExprError();
1213         break;
1214       default:
1215         break;
1216     }
1217   }
1218 
1219   return TheCallResult;
1220 }
1221 
1222 // Get the valid immediate range for the specified NEON type code.
1223 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1224   NeonTypeFlags Type(t);
1225   int IsQuad = ForceQuad ? true : Type.isQuad();
1226   switch (Type.getEltType()) {
1227   case NeonTypeFlags::Int8:
1228   case NeonTypeFlags::Poly8:
1229     return shift ? 7 : (8 << IsQuad) - 1;
1230   case NeonTypeFlags::Int16:
1231   case NeonTypeFlags::Poly16:
1232     return shift ? 15 : (4 << IsQuad) - 1;
1233   case NeonTypeFlags::Int32:
1234     return shift ? 31 : (2 << IsQuad) - 1;
1235   case NeonTypeFlags::Int64:
1236   case NeonTypeFlags::Poly64:
1237     return shift ? 63 : (1 << IsQuad) - 1;
1238   case NeonTypeFlags::Poly128:
1239     return shift ? 127 : (1 << IsQuad) - 1;
1240   case NeonTypeFlags::Float16:
1241     assert(!shift && "cannot shift float types!");
1242     return (4 << IsQuad) - 1;
1243   case NeonTypeFlags::Float32:
1244     assert(!shift && "cannot shift float types!");
1245     return (2 << IsQuad) - 1;
1246   case NeonTypeFlags::Float64:
1247     assert(!shift && "cannot shift float types!");
1248     return (1 << IsQuad) - 1;
1249   }
1250   llvm_unreachable("Invalid NeonTypeFlag!");
1251 }
1252 
1253 /// getNeonEltType - Return the QualType corresponding to the elements of
1254 /// the vector type specified by the NeonTypeFlags.  This is used to check
1255 /// the pointer arguments for Neon load/store intrinsics.
1256 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
1257                                bool IsPolyUnsigned, bool IsInt64Long) {
1258   switch (Flags.getEltType()) {
1259   case NeonTypeFlags::Int8:
1260     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
1261   case NeonTypeFlags::Int16:
1262     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
1263   case NeonTypeFlags::Int32:
1264     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
1265   case NeonTypeFlags::Int64:
1266     if (IsInt64Long)
1267       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
1268     else
1269       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
1270                                 : Context.LongLongTy;
1271   case NeonTypeFlags::Poly8:
1272     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
1273   case NeonTypeFlags::Poly16:
1274     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
1275   case NeonTypeFlags::Poly64:
1276     if (IsInt64Long)
1277       return Context.UnsignedLongTy;
1278     else
1279       return Context.UnsignedLongLongTy;
1280   case NeonTypeFlags::Poly128:
1281     break;
1282   case NeonTypeFlags::Float16:
1283     return Context.HalfTy;
1284   case NeonTypeFlags::Float32:
1285     return Context.FloatTy;
1286   case NeonTypeFlags::Float64:
1287     return Context.DoubleTy;
1288   }
1289   llvm_unreachable("Invalid NeonTypeFlag!");
1290 }
1291 
1292 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1293   llvm::APSInt Result;
1294   uint64_t mask = 0;
1295   unsigned TV = 0;
1296   int PtrArgNum = -1;
1297   bool HasConstPtr = false;
1298   switch (BuiltinID) {
1299 #define GET_NEON_OVERLOAD_CHECK
1300 #include "clang/Basic/arm_neon.inc"
1301 #undef GET_NEON_OVERLOAD_CHECK
1302   }
1303 
1304   // For NEON intrinsics which are overloaded on vector element type, validate
1305   // the immediate which specifies which variant to emit.
1306   unsigned ImmArg = TheCall->getNumArgs()-1;
1307   if (mask) {
1308     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1309       return true;
1310 
1311     TV = Result.getLimitedValue(64);
1312     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1313       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
1314         << TheCall->getArg(ImmArg)->getSourceRange();
1315   }
1316 
1317   if (PtrArgNum >= 0) {
1318     // Check that pointer arguments have the specified type.
1319     Expr *Arg = TheCall->getArg(PtrArgNum);
1320     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
1321       Arg = ICE->getSubExpr();
1322     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1323     QualType RHSTy = RHS.get()->getType();
1324 
1325     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
1326     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1327                           Arch == llvm::Triple::aarch64_be;
1328     bool IsInt64Long =
1329         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
1330     QualType EltTy =
1331         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
1332     if (HasConstPtr)
1333       EltTy = EltTy.withConst();
1334     QualType LHSTy = Context.getPointerType(EltTy);
1335     AssignConvertType ConvTy;
1336     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1337     if (RHS.isInvalid())
1338       return true;
1339     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
1340                                  RHS.get(), AA_Assigning))
1341       return true;
1342   }
1343 
1344   // For NEON intrinsics which take an immediate value as part of the
1345   // instruction, range check them here.
1346   unsigned i = 0, l = 0, u = 0;
1347   switch (BuiltinID) {
1348   default:
1349     return false;
1350 #define GET_NEON_IMMEDIATE_CHECK
1351 #include "clang/Basic/arm_neon.inc"
1352 #undef GET_NEON_IMMEDIATE_CHECK
1353   }
1354 
1355   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1356 }
1357 
1358 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
1359                                         unsigned MaxWidth) {
1360   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1361           BuiltinID == ARM::BI__builtin_arm_ldaex ||
1362           BuiltinID == ARM::BI__builtin_arm_strex ||
1363           BuiltinID == ARM::BI__builtin_arm_stlex ||
1364           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1365           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1366           BuiltinID == AArch64::BI__builtin_arm_strex ||
1367           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1368          "unexpected ARM builtin");
1369   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1370                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
1371                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1372                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
1373 
1374   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1375 
1376   // Ensure that we have the proper number of arguments.
1377   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
1378     return true;
1379 
1380   // Inspect the pointer argument of the atomic builtin.  This should always be
1381   // a pointer type, whose element is an integral scalar or pointer type.
1382   // Because it is a pointer type, we don't have to worry about any implicit
1383   // casts here.
1384   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1385   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1386   if (PointerArgRes.isInvalid())
1387     return true;
1388   PointerArg = PointerArgRes.get();
1389 
1390   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1391   if (!pointerType) {
1392     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1393       << PointerArg->getType() << PointerArg->getSourceRange();
1394     return true;
1395   }
1396 
1397   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1398   // task is to insert the appropriate casts into the AST. First work out just
1399   // what the appropriate type is.
1400   QualType ValType = pointerType->getPointeeType();
1401   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1402   if (IsLdrex)
1403     AddrType.addConst();
1404 
1405   // Issue a warning if the cast is dodgy.
1406   CastKind CastNeeded = CK_NoOp;
1407   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1408     CastNeeded = CK_BitCast;
1409     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1410       << PointerArg->getType()
1411       << Context.getPointerType(AddrType)
1412       << AA_Passing << PointerArg->getSourceRange();
1413   }
1414 
1415   // Finally, do the cast and replace the argument with the corrected version.
1416   AddrType = Context.getPointerType(AddrType);
1417   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1418   if (PointerArgRes.isInvalid())
1419     return true;
1420   PointerArg = PointerArgRes.get();
1421 
1422   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1423 
1424   // In general, we allow ints, floats and pointers to be loaded and stored.
1425   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1426       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1427     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1428       << PointerArg->getType() << PointerArg->getSourceRange();
1429     return true;
1430   }
1431 
1432   // But ARM doesn't have instructions to deal with 128-bit versions.
1433   if (Context.getTypeSize(ValType) > MaxWidth) {
1434     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1435     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1436       << PointerArg->getType() << PointerArg->getSourceRange();
1437     return true;
1438   }
1439 
1440   switch (ValType.getObjCLifetime()) {
1441   case Qualifiers::OCL_None:
1442   case Qualifiers::OCL_ExplicitNone:
1443     // okay
1444     break;
1445 
1446   case Qualifiers::OCL_Weak:
1447   case Qualifiers::OCL_Strong:
1448   case Qualifiers::OCL_Autoreleasing:
1449     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1450       << ValType << PointerArg->getSourceRange();
1451     return true;
1452   }
1453 
1454   if (IsLdrex) {
1455     TheCall->setType(ValType);
1456     return false;
1457   }
1458 
1459   // Initialize the argument to be stored.
1460   ExprResult ValArg = TheCall->getArg(0);
1461   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1462       Context, ValType, /*consume*/ false);
1463   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1464   if (ValArg.isInvalid())
1465     return true;
1466   TheCall->setArg(0, ValArg.get());
1467 
1468   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1469   // but the custom checker bypasses all default analysis.
1470   TheCall->setType(Context.IntTy);
1471   return false;
1472 }
1473 
1474 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1475   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1476       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1477       BuiltinID == ARM::BI__builtin_arm_strex ||
1478       BuiltinID == ARM::BI__builtin_arm_stlex) {
1479     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1480   }
1481 
1482   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1483     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1484       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1485   }
1486 
1487   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1488       BuiltinID == ARM::BI__builtin_arm_wsr64)
1489     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1490 
1491   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1492       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1493       BuiltinID == ARM::BI__builtin_arm_wsr ||
1494       BuiltinID == ARM::BI__builtin_arm_wsrp)
1495     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1496 
1497   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1498     return true;
1499 
1500   // For intrinsics which take an immediate value as part of the instruction,
1501   // range check them here.
1502   unsigned i = 0, l = 0, u = 0;
1503   switch (BuiltinID) {
1504   default: return false;
1505   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1506   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1507   case ARM::BI__builtin_arm_vcvtr_f:
1508   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1509   case ARM::BI__builtin_arm_dmb:
1510   case ARM::BI__builtin_arm_dsb:
1511   case ARM::BI__builtin_arm_isb:
1512   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1513   }
1514 
1515   // FIXME: VFP Intrinsics should error if VFP not present.
1516   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1517 }
1518 
1519 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1520                                          CallExpr *TheCall) {
1521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1523       BuiltinID == AArch64::BI__builtin_arm_strex ||
1524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1526   }
1527 
1528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1533   }
1534 
1535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1538 
1539   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1540       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1541       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1542       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1543     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1544 
1545   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1546     return true;
1547 
1548   // For intrinsics which take an immediate value as part of the instruction,
1549   // range check them here.
1550   unsigned i = 0, l = 0, u = 0;
1551   switch (BuiltinID) {
1552   default: return false;
1553   case AArch64::BI__builtin_arm_dmb:
1554   case AArch64::BI__builtin_arm_dsb:
1555   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1556   }
1557 
1558   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1559 }
1560 
1561 // CheckMipsBuiltinFunctionCall - Checks the constant value passed to the
1562 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
1563 // ordering for DSP is unspecified. MSA is ordered by the data format used
1564 // by the underlying instruction i.e., df/m, df/n and then by size.
1565 //
1566 // FIXME: The size tests here should instead be tablegen'd along with the
1567 //        definitions from include/clang/Basic/BuiltinsMips.def.
1568 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
1569 //        be too.
1570 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1571   unsigned i = 0, l = 0, u = 0, m = 0;
1572   switch (BuiltinID) {
1573   default: return false;
1574   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1575   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1576   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1577   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1578   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1579   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1580   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1581   // MSA instrinsics. Instructions (which the intrinsics maps to) which use the
1582   // df/m field.
1583   // These intrinsics take an unsigned 3 bit immediate.
1584   case Mips::BI__builtin_msa_bclri_b:
1585   case Mips::BI__builtin_msa_bnegi_b:
1586   case Mips::BI__builtin_msa_bseti_b:
1587   case Mips::BI__builtin_msa_sat_s_b:
1588   case Mips::BI__builtin_msa_sat_u_b:
1589   case Mips::BI__builtin_msa_slli_b:
1590   case Mips::BI__builtin_msa_srai_b:
1591   case Mips::BI__builtin_msa_srari_b:
1592   case Mips::BI__builtin_msa_srli_b:
1593   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
1594   case Mips::BI__builtin_msa_binsli_b:
1595   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
1596   // These intrinsics take an unsigned 4 bit immediate.
1597   case Mips::BI__builtin_msa_bclri_h:
1598   case Mips::BI__builtin_msa_bnegi_h:
1599   case Mips::BI__builtin_msa_bseti_h:
1600   case Mips::BI__builtin_msa_sat_s_h:
1601   case Mips::BI__builtin_msa_sat_u_h:
1602   case Mips::BI__builtin_msa_slli_h:
1603   case Mips::BI__builtin_msa_srai_h:
1604   case Mips::BI__builtin_msa_srari_h:
1605   case Mips::BI__builtin_msa_srli_h:
1606   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
1607   case Mips::BI__builtin_msa_binsli_h:
1608   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
1609   // These intrinsics take an unsigned 5 bit immedate.
1610   // The first block of intrinsics actually have an unsigned 5 bit field,
1611   // not a df/n field.
1612   case Mips::BI__builtin_msa_clei_u_b:
1613   case Mips::BI__builtin_msa_clei_u_h:
1614   case Mips::BI__builtin_msa_clei_u_w:
1615   case Mips::BI__builtin_msa_clei_u_d:
1616   case Mips::BI__builtin_msa_clti_u_b:
1617   case Mips::BI__builtin_msa_clti_u_h:
1618   case Mips::BI__builtin_msa_clti_u_w:
1619   case Mips::BI__builtin_msa_clti_u_d:
1620   case Mips::BI__builtin_msa_maxi_u_b:
1621   case Mips::BI__builtin_msa_maxi_u_h:
1622   case Mips::BI__builtin_msa_maxi_u_w:
1623   case Mips::BI__builtin_msa_maxi_u_d:
1624   case Mips::BI__builtin_msa_mini_u_b:
1625   case Mips::BI__builtin_msa_mini_u_h:
1626   case Mips::BI__builtin_msa_mini_u_w:
1627   case Mips::BI__builtin_msa_mini_u_d:
1628   case Mips::BI__builtin_msa_addvi_b:
1629   case Mips::BI__builtin_msa_addvi_h:
1630   case Mips::BI__builtin_msa_addvi_w:
1631   case Mips::BI__builtin_msa_addvi_d:
1632   case Mips::BI__builtin_msa_bclri_w:
1633   case Mips::BI__builtin_msa_bnegi_w:
1634   case Mips::BI__builtin_msa_bseti_w:
1635   case Mips::BI__builtin_msa_sat_s_w:
1636   case Mips::BI__builtin_msa_sat_u_w:
1637   case Mips::BI__builtin_msa_slli_w:
1638   case Mips::BI__builtin_msa_srai_w:
1639   case Mips::BI__builtin_msa_srari_w:
1640   case Mips::BI__builtin_msa_srli_w:
1641   case Mips::BI__builtin_msa_srlri_w:
1642   case Mips::BI__builtin_msa_subvi_b:
1643   case Mips::BI__builtin_msa_subvi_h:
1644   case Mips::BI__builtin_msa_subvi_w:
1645   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
1646   case Mips::BI__builtin_msa_binsli_w:
1647   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
1648   // These intrinsics take an unsigned 6 bit immediate.
1649   case Mips::BI__builtin_msa_bclri_d:
1650   case Mips::BI__builtin_msa_bnegi_d:
1651   case Mips::BI__builtin_msa_bseti_d:
1652   case Mips::BI__builtin_msa_sat_s_d:
1653   case Mips::BI__builtin_msa_sat_u_d:
1654   case Mips::BI__builtin_msa_slli_d:
1655   case Mips::BI__builtin_msa_srai_d:
1656   case Mips::BI__builtin_msa_srari_d:
1657   case Mips::BI__builtin_msa_srli_d:
1658   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
1659   case Mips::BI__builtin_msa_binsli_d:
1660   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
1661   // These intrinsics take a signed 5 bit immediate.
1662   case Mips::BI__builtin_msa_ceqi_b:
1663   case Mips::BI__builtin_msa_ceqi_h:
1664   case Mips::BI__builtin_msa_ceqi_w:
1665   case Mips::BI__builtin_msa_ceqi_d:
1666   case Mips::BI__builtin_msa_clti_s_b:
1667   case Mips::BI__builtin_msa_clti_s_h:
1668   case Mips::BI__builtin_msa_clti_s_w:
1669   case Mips::BI__builtin_msa_clti_s_d:
1670   case Mips::BI__builtin_msa_clei_s_b:
1671   case Mips::BI__builtin_msa_clei_s_h:
1672   case Mips::BI__builtin_msa_clei_s_w:
1673   case Mips::BI__builtin_msa_clei_s_d:
1674   case Mips::BI__builtin_msa_maxi_s_b:
1675   case Mips::BI__builtin_msa_maxi_s_h:
1676   case Mips::BI__builtin_msa_maxi_s_w:
1677   case Mips::BI__builtin_msa_maxi_s_d:
1678   case Mips::BI__builtin_msa_mini_s_b:
1679   case Mips::BI__builtin_msa_mini_s_h:
1680   case Mips::BI__builtin_msa_mini_s_w:
1681   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
1682   // These intrinsics take an unsigned 8 bit immediate.
1683   case Mips::BI__builtin_msa_andi_b:
1684   case Mips::BI__builtin_msa_nori_b:
1685   case Mips::BI__builtin_msa_ori_b:
1686   case Mips::BI__builtin_msa_shf_b:
1687   case Mips::BI__builtin_msa_shf_h:
1688   case Mips::BI__builtin_msa_shf_w:
1689   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
1690   case Mips::BI__builtin_msa_bseli_b:
1691   case Mips::BI__builtin_msa_bmnzi_b:
1692   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
1693   // df/n format
1694   // These intrinsics take an unsigned 4 bit immediate.
1695   case Mips::BI__builtin_msa_copy_s_b:
1696   case Mips::BI__builtin_msa_copy_u_b:
1697   case Mips::BI__builtin_msa_insve_b:
1698   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
1699   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
1700   // These intrinsics take an unsigned 3 bit immediate.
1701   case Mips::BI__builtin_msa_copy_s_h:
1702   case Mips::BI__builtin_msa_copy_u_h:
1703   case Mips::BI__builtin_msa_insve_h:
1704   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
1705   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
1706   // These intrinsics take an unsigned 2 bit immediate.
1707   case Mips::BI__builtin_msa_copy_s_w:
1708   case Mips::BI__builtin_msa_copy_u_w:
1709   case Mips::BI__builtin_msa_insve_w:
1710   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
1711   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
1712   // These intrinsics take an unsigned 1 bit immediate.
1713   case Mips::BI__builtin_msa_copy_s_d:
1714   case Mips::BI__builtin_msa_copy_u_d:
1715   case Mips::BI__builtin_msa_insve_d:
1716   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
1717   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
1718   // Memory offsets and immediate loads.
1719   // These intrinsics take a signed 10 bit immediate.
1720   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
1721   case Mips::BI__builtin_msa_ldi_h:
1722   case Mips::BI__builtin_msa_ldi_w:
1723   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
1724   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16; break;
1725   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16; break;
1726   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16; break;
1727   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16; break;
1728   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16; break;
1729   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16; break;
1730   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16; break;
1731   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16; break;
1732   }
1733 
1734   if (!m)
1735     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1736 
1737   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1738          SemaBuiltinConstantArgMultiple(TheCall, i, m);
1739 }
1740 
1741 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1742   unsigned i = 0, l = 0, u = 0;
1743   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1744                       BuiltinID == PPC::BI__builtin_divdeu ||
1745                       BuiltinID == PPC::BI__builtin_bpermd;
1746   bool IsTarget64Bit = Context.getTargetInfo()
1747                               .getTypeWidth(Context
1748                                             .getTargetInfo()
1749                                             .getIntPtrType()) == 64;
1750   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1751                        BuiltinID == PPC::BI__builtin_divweu ||
1752                        BuiltinID == PPC::BI__builtin_divde ||
1753                        BuiltinID == PPC::BI__builtin_divdeu;
1754 
1755   if (Is64BitBltin && !IsTarget64Bit)
1756       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1757              << TheCall->getSourceRange();
1758 
1759   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1760       (BuiltinID == PPC::BI__builtin_bpermd &&
1761        !Context.getTargetInfo().hasFeature("bpermd")))
1762     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1763            << TheCall->getSourceRange();
1764 
1765   switch (BuiltinID) {
1766   default: return false;
1767   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1768   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1769     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1770            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1771   case PPC::BI__builtin_tbegin:
1772   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1773   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1774   case PPC::BI__builtin_tabortwc:
1775   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1776   case PPC::BI__builtin_tabortwci:
1777   case PPC::BI__builtin_tabortdci:
1778     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1779            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1780   case PPC::BI__builtin_vsx_xxpermdi:
1781   case PPC::BI__builtin_vsx_xxsldwi:
1782     return SemaBuiltinVSX(TheCall);
1783   }
1784   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1785 }
1786 
1787 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1788                                            CallExpr *TheCall) {
1789   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1790     Expr *Arg = TheCall->getArg(0);
1791     llvm::APSInt AbortCode(32);
1792     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1793         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1794       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1795              << Arg->getSourceRange();
1796   }
1797 
1798   // For intrinsics which take an immediate value as part of the instruction,
1799   // range check them here.
1800   unsigned i = 0, l = 0, u = 0;
1801   switch (BuiltinID) {
1802   default: return false;
1803   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1804   case SystemZ::BI__builtin_s390_verimb:
1805   case SystemZ::BI__builtin_s390_verimh:
1806   case SystemZ::BI__builtin_s390_verimf:
1807   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1808   case SystemZ::BI__builtin_s390_vfaeb:
1809   case SystemZ::BI__builtin_s390_vfaeh:
1810   case SystemZ::BI__builtin_s390_vfaef:
1811   case SystemZ::BI__builtin_s390_vfaebs:
1812   case SystemZ::BI__builtin_s390_vfaehs:
1813   case SystemZ::BI__builtin_s390_vfaefs:
1814   case SystemZ::BI__builtin_s390_vfaezb:
1815   case SystemZ::BI__builtin_s390_vfaezh:
1816   case SystemZ::BI__builtin_s390_vfaezf:
1817   case SystemZ::BI__builtin_s390_vfaezbs:
1818   case SystemZ::BI__builtin_s390_vfaezhs:
1819   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1820   case SystemZ::BI__builtin_s390_vfisb:
1821   case SystemZ::BI__builtin_s390_vfidb:
1822     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1823            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1824   case SystemZ::BI__builtin_s390_vftcisb:
1825   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1826   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1827   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1828   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1829   case SystemZ::BI__builtin_s390_vstrcb:
1830   case SystemZ::BI__builtin_s390_vstrch:
1831   case SystemZ::BI__builtin_s390_vstrcf:
1832   case SystemZ::BI__builtin_s390_vstrczb:
1833   case SystemZ::BI__builtin_s390_vstrczh:
1834   case SystemZ::BI__builtin_s390_vstrczf:
1835   case SystemZ::BI__builtin_s390_vstrcbs:
1836   case SystemZ::BI__builtin_s390_vstrchs:
1837   case SystemZ::BI__builtin_s390_vstrcfs:
1838   case SystemZ::BI__builtin_s390_vstrczbs:
1839   case SystemZ::BI__builtin_s390_vstrczhs:
1840   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1841   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
1842   case SystemZ::BI__builtin_s390_vfminsb:
1843   case SystemZ::BI__builtin_s390_vfmaxsb:
1844   case SystemZ::BI__builtin_s390_vfmindb:
1845   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
1846   }
1847   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1848 }
1849 
1850 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1851 /// This checks that the target supports __builtin_cpu_supports and
1852 /// that the string argument is constant and valid.
1853 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1854   Expr *Arg = TheCall->getArg(0);
1855 
1856   // Check if the argument is a string literal.
1857   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1858     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1859            << Arg->getSourceRange();
1860 
1861   // Check the contents of the string.
1862   StringRef Feature =
1863       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1864   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1865     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1866            << Arg->getSourceRange();
1867   return false;
1868 }
1869 
1870 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
1871 /// This checks that the target supports __builtin_cpu_is and
1872 /// that the string argument is constant and valid.
1873 static bool SemaBuiltinCpuIs(Sema &S, CallExpr *TheCall) {
1874   Expr *Arg = TheCall->getArg(0);
1875 
1876   // Check if the argument is a string literal.
1877   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1878     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1879            << Arg->getSourceRange();
1880 
1881   // Check the contents of the string.
1882   StringRef Feature =
1883       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1884   if (!S.Context.getTargetInfo().validateCpuIs(Feature))
1885     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_is)
1886            << Arg->getSourceRange();
1887   return false;
1888 }
1889 
1890 // Check if the rounding mode is legal.
1891 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
1892   // Indicates if this instruction has rounding control or just SAE.
1893   bool HasRC = false;
1894 
1895   unsigned ArgNum = 0;
1896   switch (BuiltinID) {
1897   default:
1898     return false;
1899   case X86::BI__builtin_ia32_vcvttsd2si32:
1900   case X86::BI__builtin_ia32_vcvttsd2si64:
1901   case X86::BI__builtin_ia32_vcvttsd2usi32:
1902   case X86::BI__builtin_ia32_vcvttsd2usi64:
1903   case X86::BI__builtin_ia32_vcvttss2si32:
1904   case X86::BI__builtin_ia32_vcvttss2si64:
1905   case X86::BI__builtin_ia32_vcvttss2usi32:
1906   case X86::BI__builtin_ia32_vcvttss2usi64:
1907     ArgNum = 1;
1908     break;
1909   case X86::BI__builtin_ia32_cvtps2pd512_mask:
1910   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1911   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1912   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1913   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1914   case X86::BI__builtin_ia32_cvttps2dq512_mask:
1915   case X86::BI__builtin_ia32_cvttps2qq512_mask:
1916   case X86::BI__builtin_ia32_cvttps2udq512_mask:
1917   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1918   case X86::BI__builtin_ia32_exp2pd_mask:
1919   case X86::BI__builtin_ia32_exp2ps_mask:
1920   case X86::BI__builtin_ia32_getexppd512_mask:
1921   case X86::BI__builtin_ia32_getexpps512_mask:
1922   case X86::BI__builtin_ia32_rcp28pd_mask:
1923   case X86::BI__builtin_ia32_rcp28ps_mask:
1924   case X86::BI__builtin_ia32_rsqrt28pd_mask:
1925   case X86::BI__builtin_ia32_rsqrt28ps_mask:
1926   case X86::BI__builtin_ia32_vcomisd:
1927   case X86::BI__builtin_ia32_vcomiss:
1928   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1929     ArgNum = 3;
1930     break;
1931   case X86::BI__builtin_ia32_cmppd512_mask:
1932   case X86::BI__builtin_ia32_cmpps512_mask:
1933   case X86::BI__builtin_ia32_cmpsd_mask:
1934   case X86::BI__builtin_ia32_cmpss_mask:
1935   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1936   case X86::BI__builtin_ia32_getexpsd128_round_mask:
1937   case X86::BI__builtin_ia32_getexpss128_round_mask:
1938   case X86::BI__builtin_ia32_maxpd512_mask:
1939   case X86::BI__builtin_ia32_maxps512_mask:
1940   case X86::BI__builtin_ia32_maxsd_round_mask:
1941   case X86::BI__builtin_ia32_maxss_round_mask:
1942   case X86::BI__builtin_ia32_minpd512_mask:
1943   case X86::BI__builtin_ia32_minps512_mask:
1944   case X86::BI__builtin_ia32_minsd_round_mask:
1945   case X86::BI__builtin_ia32_minss_round_mask:
1946   case X86::BI__builtin_ia32_rcp28sd_round_mask:
1947   case X86::BI__builtin_ia32_rcp28ss_round_mask:
1948   case X86::BI__builtin_ia32_reducepd512_mask:
1949   case X86::BI__builtin_ia32_reduceps512_mask:
1950   case X86::BI__builtin_ia32_rndscalepd_mask:
1951   case X86::BI__builtin_ia32_rndscaleps_mask:
1952   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1953   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1954     ArgNum = 4;
1955     break;
1956   case X86::BI__builtin_ia32_fixupimmpd512_mask:
1957   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1958   case X86::BI__builtin_ia32_fixupimmps512_mask:
1959   case X86::BI__builtin_ia32_fixupimmps512_maskz:
1960   case X86::BI__builtin_ia32_fixupimmsd_mask:
1961   case X86::BI__builtin_ia32_fixupimmsd_maskz:
1962   case X86::BI__builtin_ia32_fixupimmss_mask:
1963   case X86::BI__builtin_ia32_fixupimmss_maskz:
1964   case X86::BI__builtin_ia32_rangepd512_mask:
1965   case X86::BI__builtin_ia32_rangeps512_mask:
1966   case X86::BI__builtin_ia32_rangesd128_round_mask:
1967   case X86::BI__builtin_ia32_rangess128_round_mask:
1968   case X86::BI__builtin_ia32_reducesd_mask:
1969   case X86::BI__builtin_ia32_reducess_mask:
1970   case X86::BI__builtin_ia32_rndscalesd_round_mask:
1971   case X86::BI__builtin_ia32_rndscaless_round_mask:
1972     ArgNum = 5;
1973     break;
1974   case X86::BI__builtin_ia32_vcvtsd2si64:
1975   case X86::BI__builtin_ia32_vcvtsd2si32:
1976   case X86::BI__builtin_ia32_vcvtsd2usi32:
1977   case X86::BI__builtin_ia32_vcvtsd2usi64:
1978   case X86::BI__builtin_ia32_vcvtss2si32:
1979   case X86::BI__builtin_ia32_vcvtss2si64:
1980   case X86::BI__builtin_ia32_vcvtss2usi32:
1981   case X86::BI__builtin_ia32_vcvtss2usi64:
1982     ArgNum = 1;
1983     HasRC = true;
1984     break;
1985   case X86::BI__builtin_ia32_cvtsi2sd64:
1986   case X86::BI__builtin_ia32_cvtsi2ss32:
1987   case X86::BI__builtin_ia32_cvtsi2ss64:
1988   case X86::BI__builtin_ia32_cvtusi2sd64:
1989   case X86::BI__builtin_ia32_cvtusi2ss32:
1990   case X86::BI__builtin_ia32_cvtusi2ss64:
1991     ArgNum = 2;
1992     HasRC = true;
1993     break;
1994   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1995   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1996   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1997   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1998   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1999   case X86::BI__builtin_ia32_cvtps2qq512_mask:
2000   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
2001   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
2002   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
2003   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
2004   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
2005   case X86::BI__builtin_ia32_sqrtpd512_mask:
2006   case X86::BI__builtin_ia32_sqrtps512_mask:
2007     ArgNum = 3;
2008     HasRC = true;
2009     break;
2010   case X86::BI__builtin_ia32_addpd512_mask:
2011   case X86::BI__builtin_ia32_addps512_mask:
2012   case X86::BI__builtin_ia32_divpd512_mask:
2013   case X86::BI__builtin_ia32_divps512_mask:
2014   case X86::BI__builtin_ia32_mulpd512_mask:
2015   case X86::BI__builtin_ia32_mulps512_mask:
2016   case X86::BI__builtin_ia32_subpd512_mask:
2017   case X86::BI__builtin_ia32_subps512_mask:
2018   case X86::BI__builtin_ia32_addss_round_mask:
2019   case X86::BI__builtin_ia32_addsd_round_mask:
2020   case X86::BI__builtin_ia32_divss_round_mask:
2021   case X86::BI__builtin_ia32_divsd_round_mask:
2022   case X86::BI__builtin_ia32_mulss_round_mask:
2023   case X86::BI__builtin_ia32_mulsd_round_mask:
2024   case X86::BI__builtin_ia32_subss_round_mask:
2025   case X86::BI__builtin_ia32_subsd_round_mask:
2026   case X86::BI__builtin_ia32_scalefpd512_mask:
2027   case X86::BI__builtin_ia32_scalefps512_mask:
2028   case X86::BI__builtin_ia32_scalefsd_round_mask:
2029   case X86::BI__builtin_ia32_scalefss_round_mask:
2030   case X86::BI__builtin_ia32_getmantpd512_mask:
2031   case X86::BI__builtin_ia32_getmantps512_mask:
2032   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
2033   case X86::BI__builtin_ia32_sqrtsd_round_mask:
2034   case X86::BI__builtin_ia32_sqrtss_round_mask:
2035   case X86::BI__builtin_ia32_vfmaddpd512_mask:
2036   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
2037   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
2038   case X86::BI__builtin_ia32_vfmaddps512_mask:
2039   case X86::BI__builtin_ia32_vfmaddps512_mask3:
2040   case X86::BI__builtin_ia32_vfmaddps512_maskz:
2041   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
2042   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
2043   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
2044   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
2045   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
2046   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
2047   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
2048   case X86::BI__builtin_ia32_vfmsubps512_mask3:
2049   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
2050   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
2051   case X86::BI__builtin_ia32_vfnmaddpd512_mask:
2052   case X86::BI__builtin_ia32_vfnmaddps512_mask:
2053   case X86::BI__builtin_ia32_vfnmsubpd512_mask:
2054   case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
2055   case X86::BI__builtin_ia32_vfnmsubps512_mask:
2056   case X86::BI__builtin_ia32_vfnmsubps512_mask3:
2057   case X86::BI__builtin_ia32_vfmaddsd3_mask:
2058   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
2059   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
2060   case X86::BI__builtin_ia32_vfmaddss3_mask:
2061   case X86::BI__builtin_ia32_vfmaddss3_maskz:
2062   case X86::BI__builtin_ia32_vfmaddss3_mask3:
2063     ArgNum = 4;
2064     HasRC = true;
2065     break;
2066   case X86::BI__builtin_ia32_getmantsd_round_mask:
2067   case X86::BI__builtin_ia32_getmantss_round_mask:
2068     ArgNum = 5;
2069     HasRC = true;
2070     break;
2071   }
2072 
2073   llvm::APSInt Result;
2074 
2075   // We can't check the value of a dependent argument.
2076   Expr *Arg = TheCall->getArg(ArgNum);
2077   if (Arg->isTypeDependent() || Arg->isValueDependent())
2078     return false;
2079 
2080   // Check constant-ness first.
2081   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2082     return true;
2083 
2084   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
2085   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
2086   // combined with ROUND_NO_EXC.
2087   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
2088       Result == 8/*ROUND_NO_EXC*/ ||
2089       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
2090     return false;
2091 
2092   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_rounding)
2093     << Arg->getSourceRange();
2094 }
2095 
2096 // Check if the gather/scatter scale is legal.
2097 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
2098                                              CallExpr *TheCall) {
2099   unsigned ArgNum = 0;
2100   switch (BuiltinID) {
2101   default:
2102     return false;
2103   case X86::BI__builtin_ia32_gatherpfdpd:
2104   case X86::BI__builtin_ia32_gatherpfdps:
2105   case X86::BI__builtin_ia32_gatherpfqpd:
2106   case X86::BI__builtin_ia32_gatherpfqps:
2107   case X86::BI__builtin_ia32_scatterpfdpd:
2108   case X86::BI__builtin_ia32_scatterpfdps:
2109   case X86::BI__builtin_ia32_scatterpfqpd:
2110   case X86::BI__builtin_ia32_scatterpfqps:
2111     ArgNum = 3;
2112     break;
2113   case X86::BI__builtin_ia32_gatherd_pd:
2114   case X86::BI__builtin_ia32_gatherd_pd256:
2115   case X86::BI__builtin_ia32_gatherq_pd:
2116   case X86::BI__builtin_ia32_gatherq_pd256:
2117   case X86::BI__builtin_ia32_gatherd_ps:
2118   case X86::BI__builtin_ia32_gatherd_ps256:
2119   case X86::BI__builtin_ia32_gatherq_ps:
2120   case X86::BI__builtin_ia32_gatherq_ps256:
2121   case X86::BI__builtin_ia32_gatherd_q:
2122   case X86::BI__builtin_ia32_gatherd_q256:
2123   case X86::BI__builtin_ia32_gatherq_q:
2124   case X86::BI__builtin_ia32_gatherq_q256:
2125   case X86::BI__builtin_ia32_gatherd_d:
2126   case X86::BI__builtin_ia32_gatherd_d256:
2127   case X86::BI__builtin_ia32_gatherq_d:
2128   case X86::BI__builtin_ia32_gatherq_d256:
2129   case X86::BI__builtin_ia32_gather3div2df:
2130   case X86::BI__builtin_ia32_gather3div2di:
2131   case X86::BI__builtin_ia32_gather3div4df:
2132   case X86::BI__builtin_ia32_gather3div4di:
2133   case X86::BI__builtin_ia32_gather3div4sf:
2134   case X86::BI__builtin_ia32_gather3div4si:
2135   case X86::BI__builtin_ia32_gather3div8sf:
2136   case X86::BI__builtin_ia32_gather3div8si:
2137   case X86::BI__builtin_ia32_gather3siv2df:
2138   case X86::BI__builtin_ia32_gather3siv2di:
2139   case X86::BI__builtin_ia32_gather3siv4df:
2140   case X86::BI__builtin_ia32_gather3siv4di:
2141   case X86::BI__builtin_ia32_gather3siv4sf:
2142   case X86::BI__builtin_ia32_gather3siv4si:
2143   case X86::BI__builtin_ia32_gather3siv8sf:
2144   case X86::BI__builtin_ia32_gather3siv8si:
2145   case X86::BI__builtin_ia32_gathersiv8df:
2146   case X86::BI__builtin_ia32_gathersiv16sf:
2147   case X86::BI__builtin_ia32_gatherdiv8df:
2148   case X86::BI__builtin_ia32_gatherdiv16sf:
2149   case X86::BI__builtin_ia32_gathersiv8di:
2150   case X86::BI__builtin_ia32_gathersiv16si:
2151   case X86::BI__builtin_ia32_gatherdiv8di:
2152   case X86::BI__builtin_ia32_gatherdiv16si:
2153   case X86::BI__builtin_ia32_scatterdiv2df:
2154   case X86::BI__builtin_ia32_scatterdiv2di:
2155   case X86::BI__builtin_ia32_scatterdiv4df:
2156   case X86::BI__builtin_ia32_scatterdiv4di:
2157   case X86::BI__builtin_ia32_scatterdiv4sf:
2158   case X86::BI__builtin_ia32_scatterdiv4si:
2159   case X86::BI__builtin_ia32_scatterdiv8sf:
2160   case X86::BI__builtin_ia32_scatterdiv8si:
2161   case X86::BI__builtin_ia32_scattersiv2df:
2162   case X86::BI__builtin_ia32_scattersiv2di:
2163   case X86::BI__builtin_ia32_scattersiv4df:
2164   case X86::BI__builtin_ia32_scattersiv4di:
2165   case X86::BI__builtin_ia32_scattersiv4sf:
2166   case X86::BI__builtin_ia32_scattersiv4si:
2167   case X86::BI__builtin_ia32_scattersiv8sf:
2168   case X86::BI__builtin_ia32_scattersiv8si:
2169   case X86::BI__builtin_ia32_scattersiv8df:
2170   case X86::BI__builtin_ia32_scattersiv16sf:
2171   case X86::BI__builtin_ia32_scatterdiv8df:
2172   case X86::BI__builtin_ia32_scatterdiv16sf:
2173   case X86::BI__builtin_ia32_scattersiv8di:
2174   case X86::BI__builtin_ia32_scattersiv16si:
2175   case X86::BI__builtin_ia32_scatterdiv8di:
2176   case X86::BI__builtin_ia32_scatterdiv16si:
2177     ArgNum = 4;
2178     break;
2179   }
2180 
2181   llvm::APSInt Result;
2182 
2183   // We can't check the value of a dependent argument.
2184   Expr *Arg = TheCall->getArg(ArgNum);
2185   if (Arg->isTypeDependent() || Arg->isValueDependent())
2186     return false;
2187 
2188   // Check constant-ness first.
2189   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2190     return true;
2191 
2192   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2193     return false;
2194 
2195   return Diag(TheCall->getLocStart(), diag::err_x86_builtin_invalid_scale)
2196     << Arg->getSourceRange();
2197 }
2198 
2199 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2200   if (BuiltinID == X86::BI__builtin_cpu_supports)
2201     return SemaBuiltinCpuSupports(*this, TheCall);
2202 
2203   if (BuiltinID == X86::BI__builtin_cpu_is)
2204     return SemaBuiltinCpuIs(*this, TheCall);
2205 
2206   // If the intrinsic has rounding or SAE make sure its valid.
2207   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2208     return true;
2209 
2210   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
2211   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2212     return true;
2213 
2214   // For intrinsics which take an immediate value as part of the instruction,
2215   // range check them here.
2216   int i = 0, l = 0, u = 0;
2217   switch (BuiltinID) {
2218   default:
2219     return false;
2220   case X86::BI_mm_prefetch:
2221     i = 1; l = 0; u = 3;
2222     break;
2223   case X86::BI__builtin_ia32_sha1rnds4:
2224   case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2225   case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2226   case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2227   case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2228     i = 2; l = 0; u = 3;
2229     break;
2230   case X86::BI__builtin_ia32_vpermil2pd:
2231   case X86::BI__builtin_ia32_vpermil2pd256:
2232   case X86::BI__builtin_ia32_vpermil2ps:
2233   case X86::BI__builtin_ia32_vpermil2ps256:
2234     i = 3; l = 0; u = 3;
2235     break;
2236   case X86::BI__builtin_ia32_cmpb128_mask:
2237   case X86::BI__builtin_ia32_cmpw128_mask:
2238   case X86::BI__builtin_ia32_cmpd128_mask:
2239   case X86::BI__builtin_ia32_cmpq128_mask:
2240   case X86::BI__builtin_ia32_cmpb256_mask:
2241   case X86::BI__builtin_ia32_cmpw256_mask:
2242   case X86::BI__builtin_ia32_cmpd256_mask:
2243   case X86::BI__builtin_ia32_cmpq256_mask:
2244   case X86::BI__builtin_ia32_cmpb512_mask:
2245   case X86::BI__builtin_ia32_cmpw512_mask:
2246   case X86::BI__builtin_ia32_cmpd512_mask:
2247   case X86::BI__builtin_ia32_cmpq512_mask:
2248   case X86::BI__builtin_ia32_ucmpb128_mask:
2249   case X86::BI__builtin_ia32_ucmpw128_mask:
2250   case X86::BI__builtin_ia32_ucmpd128_mask:
2251   case X86::BI__builtin_ia32_ucmpq128_mask:
2252   case X86::BI__builtin_ia32_ucmpb256_mask:
2253   case X86::BI__builtin_ia32_ucmpw256_mask:
2254   case X86::BI__builtin_ia32_ucmpd256_mask:
2255   case X86::BI__builtin_ia32_ucmpq256_mask:
2256   case X86::BI__builtin_ia32_ucmpb512_mask:
2257   case X86::BI__builtin_ia32_ucmpw512_mask:
2258   case X86::BI__builtin_ia32_ucmpd512_mask:
2259   case X86::BI__builtin_ia32_ucmpq512_mask:
2260   case X86::BI__builtin_ia32_vpcomub:
2261   case X86::BI__builtin_ia32_vpcomuw:
2262   case X86::BI__builtin_ia32_vpcomud:
2263   case X86::BI__builtin_ia32_vpcomuq:
2264   case X86::BI__builtin_ia32_vpcomb:
2265   case X86::BI__builtin_ia32_vpcomw:
2266   case X86::BI__builtin_ia32_vpcomd:
2267   case X86::BI__builtin_ia32_vpcomq:
2268     i = 2; l = 0; u = 7;
2269     break;
2270   case X86::BI__builtin_ia32_roundps:
2271   case X86::BI__builtin_ia32_roundpd:
2272   case X86::BI__builtin_ia32_roundps256:
2273   case X86::BI__builtin_ia32_roundpd256:
2274     i = 1; l = 0; u = 15;
2275     break;
2276   case X86::BI__builtin_ia32_roundss:
2277   case X86::BI__builtin_ia32_roundsd:
2278   case X86::BI__builtin_ia32_rangepd128_mask:
2279   case X86::BI__builtin_ia32_rangepd256_mask:
2280   case X86::BI__builtin_ia32_rangepd512_mask:
2281   case X86::BI__builtin_ia32_rangeps128_mask:
2282   case X86::BI__builtin_ia32_rangeps256_mask:
2283   case X86::BI__builtin_ia32_rangeps512_mask:
2284   case X86::BI__builtin_ia32_getmantsd_round_mask:
2285   case X86::BI__builtin_ia32_getmantss_round_mask:
2286     i = 2; l = 0; u = 15;
2287     break;
2288   case X86::BI__builtin_ia32_cmpps:
2289   case X86::BI__builtin_ia32_cmpss:
2290   case X86::BI__builtin_ia32_cmppd:
2291   case X86::BI__builtin_ia32_cmpsd:
2292   case X86::BI__builtin_ia32_cmpps256:
2293   case X86::BI__builtin_ia32_cmppd256:
2294   case X86::BI__builtin_ia32_cmpps128_mask:
2295   case X86::BI__builtin_ia32_cmppd128_mask:
2296   case X86::BI__builtin_ia32_cmpps256_mask:
2297   case X86::BI__builtin_ia32_cmppd256_mask:
2298   case X86::BI__builtin_ia32_cmpps512_mask:
2299   case X86::BI__builtin_ia32_cmppd512_mask:
2300   case X86::BI__builtin_ia32_cmpsd_mask:
2301   case X86::BI__builtin_ia32_cmpss_mask:
2302     i = 2; l = 0; u = 31;
2303     break;
2304   case X86::BI__builtin_ia32_xabort:
2305     i = 0; l = -128; u = 255;
2306     break;
2307   case X86::BI__builtin_ia32_pshufw:
2308   case X86::BI__builtin_ia32_aeskeygenassist128:
2309     i = 1; l = -128; u = 255;
2310     break;
2311   case X86::BI__builtin_ia32_vcvtps2ph:
2312   case X86::BI__builtin_ia32_vcvtps2ph256:
2313   case X86::BI__builtin_ia32_rndscaleps_128_mask:
2314   case X86::BI__builtin_ia32_rndscalepd_128_mask:
2315   case X86::BI__builtin_ia32_rndscaleps_256_mask:
2316   case X86::BI__builtin_ia32_rndscalepd_256_mask:
2317   case X86::BI__builtin_ia32_rndscaleps_mask:
2318   case X86::BI__builtin_ia32_rndscalepd_mask:
2319   case X86::BI__builtin_ia32_reducepd128_mask:
2320   case X86::BI__builtin_ia32_reducepd256_mask:
2321   case X86::BI__builtin_ia32_reducepd512_mask:
2322   case X86::BI__builtin_ia32_reduceps128_mask:
2323   case X86::BI__builtin_ia32_reduceps256_mask:
2324   case X86::BI__builtin_ia32_reduceps512_mask:
2325   case X86::BI__builtin_ia32_prold512_mask:
2326   case X86::BI__builtin_ia32_prolq512_mask:
2327   case X86::BI__builtin_ia32_prold128_mask:
2328   case X86::BI__builtin_ia32_prold256_mask:
2329   case X86::BI__builtin_ia32_prolq128_mask:
2330   case X86::BI__builtin_ia32_prolq256_mask:
2331   case X86::BI__builtin_ia32_prord128_mask:
2332   case X86::BI__builtin_ia32_prord256_mask:
2333   case X86::BI__builtin_ia32_prorq128_mask:
2334   case X86::BI__builtin_ia32_prorq256_mask:
2335   case X86::BI__builtin_ia32_fpclasspd128_mask:
2336   case X86::BI__builtin_ia32_fpclasspd256_mask:
2337   case X86::BI__builtin_ia32_fpclassps128_mask:
2338   case X86::BI__builtin_ia32_fpclassps256_mask:
2339   case X86::BI__builtin_ia32_fpclassps512_mask:
2340   case X86::BI__builtin_ia32_fpclasspd512_mask:
2341   case X86::BI__builtin_ia32_fpclasssd_mask:
2342   case X86::BI__builtin_ia32_fpclassss_mask:
2343     i = 1; l = 0; u = 255;
2344     break;
2345   case X86::BI__builtin_ia32_palignr:
2346   case X86::BI__builtin_ia32_insertps128:
2347   case X86::BI__builtin_ia32_dpps:
2348   case X86::BI__builtin_ia32_dppd:
2349   case X86::BI__builtin_ia32_dpps256:
2350   case X86::BI__builtin_ia32_mpsadbw128:
2351   case X86::BI__builtin_ia32_mpsadbw256:
2352   case X86::BI__builtin_ia32_pcmpistrm128:
2353   case X86::BI__builtin_ia32_pcmpistri128:
2354   case X86::BI__builtin_ia32_pcmpistria128:
2355   case X86::BI__builtin_ia32_pcmpistric128:
2356   case X86::BI__builtin_ia32_pcmpistrio128:
2357   case X86::BI__builtin_ia32_pcmpistris128:
2358   case X86::BI__builtin_ia32_pcmpistriz128:
2359   case X86::BI__builtin_ia32_pclmulqdq128:
2360   case X86::BI__builtin_ia32_vperm2f128_pd256:
2361   case X86::BI__builtin_ia32_vperm2f128_ps256:
2362   case X86::BI__builtin_ia32_vperm2f128_si256:
2363   case X86::BI__builtin_ia32_permti256:
2364     i = 2; l = -128; u = 255;
2365     break;
2366   case X86::BI__builtin_ia32_palignr128:
2367   case X86::BI__builtin_ia32_palignr256:
2368   case X86::BI__builtin_ia32_palignr512_mask:
2369   case X86::BI__builtin_ia32_vcomisd:
2370   case X86::BI__builtin_ia32_vcomiss:
2371   case X86::BI__builtin_ia32_shuf_f32x4_mask:
2372   case X86::BI__builtin_ia32_shuf_f64x2_mask:
2373   case X86::BI__builtin_ia32_shuf_i32x4_mask:
2374   case X86::BI__builtin_ia32_shuf_i64x2_mask:
2375   case X86::BI__builtin_ia32_dbpsadbw128_mask:
2376   case X86::BI__builtin_ia32_dbpsadbw256_mask:
2377   case X86::BI__builtin_ia32_dbpsadbw512_mask:
2378     i = 2; l = 0; u = 255;
2379     break;
2380   case X86::BI__builtin_ia32_fixupimmpd512_mask:
2381   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2382   case X86::BI__builtin_ia32_fixupimmps512_mask:
2383   case X86::BI__builtin_ia32_fixupimmps512_maskz:
2384   case X86::BI__builtin_ia32_fixupimmsd_mask:
2385   case X86::BI__builtin_ia32_fixupimmsd_maskz:
2386   case X86::BI__builtin_ia32_fixupimmss_mask:
2387   case X86::BI__builtin_ia32_fixupimmss_maskz:
2388   case X86::BI__builtin_ia32_fixupimmpd128_mask:
2389   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2390   case X86::BI__builtin_ia32_fixupimmpd256_mask:
2391   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2392   case X86::BI__builtin_ia32_fixupimmps128_mask:
2393   case X86::BI__builtin_ia32_fixupimmps128_maskz:
2394   case X86::BI__builtin_ia32_fixupimmps256_mask:
2395   case X86::BI__builtin_ia32_fixupimmps256_maskz:
2396   case X86::BI__builtin_ia32_pternlogd512_mask:
2397   case X86::BI__builtin_ia32_pternlogd512_maskz:
2398   case X86::BI__builtin_ia32_pternlogq512_mask:
2399   case X86::BI__builtin_ia32_pternlogq512_maskz:
2400   case X86::BI__builtin_ia32_pternlogd128_mask:
2401   case X86::BI__builtin_ia32_pternlogd128_maskz:
2402   case X86::BI__builtin_ia32_pternlogd256_mask:
2403   case X86::BI__builtin_ia32_pternlogd256_maskz:
2404   case X86::BI__builtin_ia32_pternlogq128_mask:
2405   case X86::BI__builtin_ia32_pternlogq128_maskz:
2406   case X86::BI__builtin_ia32_pternlogq256_mask:
2407   case X86::BI__builtin_ia32_pternlogq256_maskz:
2408     i = 3; l = 0; u = 255;
2409     break;
2410   case X86::BI__builtin_ia32_gatherpfdpd:
2411   case X86::BI__builtin_ia32_gatherpfdps:
2412   case X86::BI__builtin_ia32_gatherpfqpd:
2413   case X86::BI__builtin_ia32_gatherpfqps:
2414   case X86::BI__builtin_ia32_scatterpfdpd:
2415   case X86::BI__builtin_ia32_scatterpfdps:
2416   case X86::BI__builtin_ia32_scatterpfqpd:
2417   case X86::BI__builtin_ia32_scatterpfqps:
2418     i = 4; l = 2; u = 3;
2419     break;
2420   case X86::BI__builtin_ia32_pcmpestrm128:
2421   case X86::BI__builtin_ia32_pcmpestri128:
2422   case X86::BI__builtin_ia32_pcmpestria128:
2423   case X86::BI__builtin_ia32_pcmpestric128:
2424   case X86::BI__builtin_ia32_pcmpestrio128:
2425   case X86::BI__builtin_ia32_pcmpestris128:
2426   case X86::BI__builtin_ia32_pcmpestriz128:
2427     i = 4; l = -128; u = 255;
2428     break;
2429   case X86::BI__builtin_ia32_rndscalesd_round_mask:
2430   case X86::BI__builtin_ia32_rndscaless_round_mask:
2431     i = 4; l = 0; u = 255;
2432     break;
2433   }
2434   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2435 }
2436 
2437 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
2438 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
2439 /// Returns true when the format fits the function and the FormatStringInfo has
2440 /// been populated.
2441 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
2442                                FormatStringInfo *FSI) {
2443   FSI->HasVAListArg = Format->getFirstArg() == 0;
2444   FSI->FormatIdx = Format->getFormatIdx() - 1;
2445   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2446 
2447   // The way the format attribute works in GCC, the implicit this argument
2448   // of member functions is counted. However, it doesn't appear in our own
2449   // lists, so decrement format_idx in that case.
2450   if (IsCXXMember) {
2451     if(FSI->FormatIdx == 0)
2452       return false;
2453     --FSI->FormatIdx;
2454     if (FSI->FirstDataArg != 0)
2455       --FSI->FirstDataArg;
2456   }
2457   return true;
2458 }
2459 
2460 /// Checks if a the given expression evaluates to null.
2461 ///
2462 /// \brief Returns true if the value evaluates to null.
2463 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
2464   // If the expression has non-null type, it doesn't evaluate to null.
2465   if (auto nullability
2466         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
2467     if (*nullability == NullabilityKind::NonNull)
2468       return false;
2469   }
2470 
2471   // As a special case, transparent unions initialized with zero are
2472   // considered null for the purposes of the nonnull attribute.
2473   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
2474     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2475       if (const CompoundLiteralExpr *CLE =
2476           dyn_cast<CompoundLiteralExpr>(Expr))
2477         if (const InitListExpr *ILE =
2478             dyn_cast<InitListExpr>(CLE->getInitializer()))
2479           Expr = ILE->getInit(0);
2480   }
2481 
2482   bool Result;
2483   return (!Expr->isValueDependent() &&
2484           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
2485           !Result);
2486 }
2487 
2488 static void CheckNonNullArgument(Sema &S,
2489                                  const Expr *ArgExpr,
2490                                  SourceLocation CallSiteLoc) {
2491   if (CheckNonNullExpr(S, ArgExpr))
2492     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
2493            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
2494 }
2495 
2496 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
2497   FormatStringInfo FSI;
2498   if ((GetFormatStringType(Format) == FST_NSString) &&
2499       getFormatStringInfo(Format, false, &FSI)) {
2500     Idx = FSI.FormatIdx;
2501     return true;
2502   }
2503   return false;
2504 }
2505 /// \brief Diagnose use of %s directive in an NSString which is being passed
2506 /// as formatting string to formatting method.
2507 static void
2508 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
2509                                         const NamedDecl *FDecl,
2510                                         Expr **Args,
2511                                         unsigned NumArgs) {
2512   unsigned Idx = 0;
2513   bool Format = false;
2514   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
2515   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
2516     Idx = 2;
2517     Format = true;
2518   }
2519   else
2520     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2521       if (S.GetFormatNSStringIdx(I, Idx)) {
2522         Format = true;
2523         break;
2524       }
2525     }
2526   if (!Format || NumArgs <= Idx)
2527     return;
2528   const Expr *FormatExpr = Args[Idx];
2529   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2530     FormatExpr = CSCE->getSubExpr();
2531   const StringLiteral *FormatString;
2532   if (const ObjCStringLiteral *OSL =
2533       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
2534     FormatString = OSL->getString();
2535   else
2536     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
2537   if (!FormatString)
2538     return;
2539   if (S.FormatStringHasSArg(FormatString)) {
2540     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2541       << "%s" << 1 << 1;
2542     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
2543       << FDecl->getDeclName();
2544   }
2545 }
2546 
2547 /// Determine whether the given type has a non-null nullability annotation.
2548 static bool isNonNullType(ASTContext &ctx, QualType type) {
2549   if (auto nullability = type->getNullability(ctx))
2550     return *nullability == NullabilityKind::NonNull;
2551 
2552   return false;
2553 }
2554 
2555 static void CheckNonNullArguments(Sema &S,
2556                                   const NamedDecl *FDecl,
2557                                   const FunctionProtoType *Proto,
2558                                   ArrayRef<const Expr *> Args,
2559                                   SourceLocation CallSiteLoc) {
2560   assert((FDecl || Proto) && "Need a function declaration or prototype");
2561 
2562   // Check the attributes attached to the method/function itself.
2563   llvm::SmallBitVector NonNullArgs;
2564   if (FDecl) {
2565     // Handle the nonnull attribute on the function/method declaration itself.
2566     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
2567       if (!NonNull->args_size()) {
2568         // Easy case: all pointer arguments are nonnull.
2569         for (const auto *Arg : Args)
2570           if (S.isValidPointerAttrType(Arg->getType()))
2571             CheckNonNullArgument(S, Arg, CallSiteLoc);
2572         return;
2573       }
2574 
2575       for (unsigned Val : NonNull->args()) {
2576         if (Val >= Args.size())
2577           continue;
2578         if (NonNullArgs.empty())
2579           NonNullArgs.resize(Args.size());
2580         NonNullArgs.set(Val);
2581       }
2582     }
2583   }
2584 
2585   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2586     // Handle the nonnull attribute on the parameters of the
2587     // function/method.
2588     ArrayRef<ParmVarDecl*> parms;
2589     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2590       parms = FD->parameters();
2591     else
2592       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2593 
2594     unsigned ParamIndex = 0;
2595     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
2596          I != E; ++I, ++ParamIndex) {
2597       const ParmVarDecl *PVD = *I;
2598       if (PVD->hasAttr<NonNullAttr>() ||
2599           isNonNullType(S.Context, PVD->getType())) {
2600         if (NonNullArgs.empty())
2601           NonNullArgs.resize(Args.size());
2602 
2603         NonNullArgs.set(ParamIndex);
2604       }
2605     }
2606   } else {
2607     // If we have a non-function, non-method declaration but no
2608     // function prototype, try to dig out the function prototype.
2609     if (!Proto) {
2610       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2611         QualType type = VD->getType().getNonReferenceType();
2612         if (auto pointerType = type->getAs<PointerType>())
2613           type = pointerType->getPointeeType();
2614         else if (auto blockType = type->getAs<BlockPointerType>())
2615           type = blockType->getPointeeType();
2616         // FIXME: data member pointers?
2617 
2618         // Dig out the function prototype, if there is one.
2619         Proto = type->getAs<FunctionProtoType>();
2620       }
2621     }
2622 
2623     // Fill in non-null argument information from the nullability
2624     // information on the parameter types (if we have them).
2625     if (Proto) {
2626       unsigned Index = 0;
2627       for (auto paramType : Proto->getParamTypes()) {
2628         if (isNonNullType(S.Context, paramType)) {
2629           if (NonNullArgs.empty())
2630             NonNullArgs.resize(Args.size());
2631 
2632           NonNullArgs.set(Index);
2633         }
2634 
2635         ++Index;
2636       }
2637     }
2638   }
2639 
2640   // Check for non-null arguments.
2641   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2642        ArgIndex != ArgIndexEnd; ++ArgIndex) {
2643     if (NonNullArgs[ArgIndex])
2644       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
2645   }
2646 }
2647 
2648 /// Handles the checks for format strings, non-POD arguments to vararg
2649 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
2650 /// attributes.
2651 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
2652                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
2653                      bool IsMemberFunction, SourceLocation Loc,
2654                      SourceRange Range, VariadicCallType CallType) {
2655   // FIXME: We should check as much as we can in the template definition.
2656   if (CurContext->isDependentContext())
2657     return;
2658 
2659   // Printf and scanf checking.
2660   llvm::SmallBitVector CheckedVarArgs;
2661   if (FDecl) {
2662     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
2663       // Only create vector if there are format attributes.
2664       CheckedVarArgs.resize(Args.size());
2665 
2666       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
2667                            CheckedVarArgs);
2668     }
2669   }
2670 
2671   // Refuse POD arguments that weren't caught by the format string
2672   // checks above.
2673   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2674   if (CallType != VariadicDoesNotApply &&
2675       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2676     unsigned NumParams = Proto ? Proto->getNumParams()
2677                        : FDecl && isa<FunctionDecl>(FDecl)
2678                            ? cast<FunctionDecl>(FDecl)->getNumParams()
2679                        : FDecl && isa<ObjCMethodDecl>(FDecl)
2680                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
2681                        : 0;
2682 
2683     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2684       // Args[ArgIdx] can be null in malformed code.
2685       if (const Expr *Arg = Args[ArgIdx]) {
2686         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2687           checkVariadicArgument(Arg, CallType);
2688       }
2689     }
2690   }
2691 
2692   if (FDecl || Proto) {
2693     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
2694 
2695     // Type safety checking.
2696     if (FDecl) {
2697       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
2698         CheckArgumentWithTypeTag(I, Args.data());
2699     }
2700   }
2701 
2702   if (FD)
2703     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2704 }
2705 
2706 /// CheckConstructorCall - Check a constructor call for correctness and safety
2707 /// properties not enforced by the C type system.
2708 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
2709                                 ArrayRef<const Expr *> Args,
2710                                 const FunctionProtoType *Proto,
2711                                 SourceLocation Loc) {
2712   VariadicCallType CallType =
2713     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2714   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
2715             Loc, SourceRange(), CallType);
2716 }
2717 
2718 /// CheckFunctionCall - Check a direct function call for various correctness
2719 /// and safety properties not strictly enforced by the C type system.
2720 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
2721                              const FunctionProtoType *Proto) {
2722   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2723                               isa<CXXMethodDecl>(FDecl);
2724   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2725                           IsMemberOperatorCall;
2726   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2727                                                   TheCall->getCallee());
2728   Expr** Args = TheCall->getArgs();
2729   unsigned NumArgs = TheCall->getNumArgs();
2730 
2731   Expr *ImplicitThis = nullptr;
2732   if (IsMemberOperatorCall) {
2733     // If this is a call to a member operator, hide the first argument
2734     // from checkCall.
2735     // FIXME: Our choice of AST representation here is less than ideal.
2736     ImplicitThis = Args[0];
2737     ++Args;
2738     --NumArgs;
2739   } else if (IsMemberFunction)
2740     ImplicitThis =
2741         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2742 
2743   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2744             IsMemberFunction, TheCall->getRParenLoc(),
2745             TheCall->getCallee()->getSourceRange(), CallType);
2746 
2747   IdentifierInfo *FnInfo = FDecl->getIdentifier();
2748   // None of the checks below are needed for functions that don't have
2749   // simple names (e.g., C++ conversion functions).
2750   if (!FnInfo)
2751     return false;
2752 
2753   CheckAbsoluteValueFunction(TheCall, FDecl);
2754   CheckMaxUnsignedZero(TheCall, FDecl);
2755 
2756   if (getLangOpts().ObjC1)
2757     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
2758 
2759   unsigned CMId = FDecl->getMemoryFunctionKind();
2760   if (CMId == 0)
2761     return false;
2762 
2763   // Handle memory setting and copying functions.
2764   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2765     CheckStrlcpycatArguments(TheCall, FnInfo);
2766   else if (CMId == Builtin::BIstrncat)
2767     CheckStrncatArguments(TheCall, FnInfo);
2768   else
2769     CheckMemaccessArguments(TheCall, CMId, FnInfo);
2770 
2771   return false;
2772 }
2773 
2774 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
2775                                ArrayRef<const Expr *> Args) {
2776   VariadicCallType CallType =
2777       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2778 
2779   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
2780             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
2781             CallType);
2782 
2783   return false;
2784 }
2785 
2786 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
2787                             const FunctionProtoType *Proto) {
2788   QualType Ty;
2789   if (const auto *V = dyn_cast<VarDecl>(NDecl))
2790     Ty = V->getType().getNonReferenceType();
2791   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
2792     Ty = F->getType().getNonReferenceType();
2793   else
2794     return false;
2795 
2796   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
2797       !Ty->isFunctionProtoType())
2798     return false;
2799 
2800   VariadicCallType CallType;
2801   if (!Proto || !Proto->isVariadic()) {
2802     CallType = VariadicDoesNotApply;
2803   } else if (Ty->isBlockPointerType()) {
2804     CallType = VariadicBlock;
2805   } else { // Ty->isFunctionPointerType()
2806     CallType = VariadicFunction;
2807   }
2808 
2809   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
2810             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2811             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2812             TheCall->getCallee()->getSourceRange(), CallType);
2813 
2814   return false;
2815 }
2816 
2817 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
2818 /// such as function pointers returned from functions.
2819 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
2820   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
2821                                                   TheCall->getCallee());
2822   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
2823             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
2824             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
2825             TheCall->getCallee()->getSourceRange(), CallType);
2826 
2827   return false;
2828 }
2829 
2830 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
2831   if (!llvm::isValidAtomicOrderingCABI(Ordering))
2832     return false;
2833 
2834   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2835   switch (Op) {
2836   case AtomicExpr::AO__c11_atomic_init:
2837   case AtomicExpr::AO__opencl_atomic_init:
2838     llvm_unreachable("There is no ordering argument for an init");
2839 
2840   case AtomicExpr::AO__c11_atomic_load:
2841   case AtomicExpr::AO__opencl_atomic_load:
2842   case AtomicExpr::AO__atomic_load_n:
2843   case AtomicExpr::AO__atomic_load:
2844     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2845            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2846 
2847   case AtomicExpr::AO__c11_atomic_store:
2848   case AtomicExpr::AO__opencl_atomic_store:
2849   case AtomicExpr::AO__atomic_store:
2850   case AtomicExpr::AO__atomic_store_n:
2851     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2852            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2853            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2854 
2855   default:
2856     return true;
2857   }
2858 }
2859 
2860 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
2861                                          AtomicExpr::AtomicOp Op) {
2862   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
2863   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2864 
2865   // All the non-OpenCL operations take one of the following forms.
2866   // The OpenCL operations take the __c11 forms with one extra argument for
2867   // synchronization scope.
2868   enum {
2869     // C    __c11_atomic_init(A *, C)
2870     Init,
2871     // C    __c11_atomic_load(A *, int)
2872     Load,
2873     // void __atomic_load(A *, CP, int)
2874     LoadCopy,
2875     // void __atomic_store(A *, CP, int)
2876     Copy,
2877     // C    __c11_atomic_add(A *, M, int)
2878     Arithmetic,
2879     // C    __atomic_exchange_n(A *, CP, int)
2880     Xchg,
2881     // void __atomic_exchange(A *, C *, CP, int)
2882     GNUXchg,
2883     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
2884     C11CmpXchg,
2885     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
2886     GNUCmpXchg
2887   } Form = Init;
2888   const unsigned NumForm = GNUCmpXchg + 1;
2889   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2890   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2891   // where:
2892   //   C is an appropriate type,
2893   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
2894   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
2895   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
2896   //   the int parameters are for orderings.
2897 
2898   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
2899       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
2900       "need to update code for modified forms");
2901   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2902                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2903                         AtomicExpr::AO__atomic_load,
2904                 "need to update code for modified C11 atomics");
2905   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
2906                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
2907   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
2908                Op <= AtomicExpr::AO__c11_atomic_fetch_xor) ||
2909                IsOpenCL;
2910   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2911              Op == AtomicExpr::AO__atomic_store_n ||
2912              Op == AtomicExpr::AO__atomic_exchange_n ||
2913              Op == AtomicExpr::AO__atomic_compare_exchange_n;
2914   bool IsAddSub = false;
2915 
2916   switch (Op) {
2917   case AtomicExpr::AO__c11_atomic_init:
2918   case AtomicExpr::AO__opencl_atomic_init:
2919     Form = Init;
2920     break;
2921 
2922   case AtomicExpr::AO__c11_atomic_load:
2923   case AtomicExpr::AO__opencl_atomic_load:
2924   case AtomicExpr::AO__atomic_load_n:
2925     Form = Load;
2926     break;
2927 
2928   case AtomicExpr::AO__atomic_load:
2929     Form = LoadCopy;
2930     break;
2931 
2932   case AtomicExpr::AO__c11_atomic_store:
2933   case AtomicExpr::AO__opencl_atomic_store:
2934   case AtomicExpr::AO__atomic_store:
2935   case AtomicExpr::AO__atomic_store_n:
2936     Form = Copy;
2937     break;
2938 
2939   case AtomicExpr::AO__c11_atomic_fetch_add:
2940   case AtomicExpr::AO__c11_atomic_fetch_sub:
2941   case AtomicExpr::AO__opencl_atomic_fetch_add:
2942   case AtomicExpr::AO__opencl_atomic_fetch_sub:
2943   case AtomicExpr::AO__opencl_atomic_fetch_min:
2944   case AtomicExpr::AO__opencl_atomic_fetch_max:
2945   case AtomicExpr::AO__atomic_fetch_add:
2946   case AtomicExpr::AO__atomic_fetch_sub:
2947   case AtomicExpr::AO__atomic_add_fetch:
2948   case AtomicExpr::AO__atomic_sub_fetch:
2949     IsAddSub = true;
2950     // Fall through.
2951   case AtomicExpr::AO__c11_atomic_fetch_and:
2952   case AtomicExpr::AO__c11_atomic_fetch_or:
2953   case AtomicExpr::AO__c11_atomic_fetch_xor:
2954   case AtomicExpr::AO__opencl_atomic_fetch_and:
2955   case AtomicExpr::AO__opencl_atomic_fetch_or:
2956   case AtomicExpr::AO__opencl_atomic_fetch_xor:
2957   case AtomicExpr::AO__atomic_fetch_and:
2958   case AtomicExpr::AO__atomic_fetch_or:
2959   case AtomicExpr::AO__atomic_fetch_xor:
2960   case AtomicExpr::AO__atomic_fetch_nand:
2961   case AtomicExpr::AO__atomic_and_fetch:
2962   case AtomicExpr::AO__atomic_or_fetch:
2963   case AtomicExpr::AO__atomic_xor_fetch:
2964   case AtomicExpr::AO__atomic_nand_fetch:
2965     Form = Arithmetic;
2966     break;
2967 
2968   case AtomicExpr::AO__c11_atomic_exchange:
2969   case AtomicExpr::AO__opencl_atomic_exchange:
2970   case AtomicExpr::AO__atomic_exchange_n:
2971     Form = Xchg;
2972     break;
2973 
2974   case AtomicExpr::AO__atomic_exchange:
2975     Form = GNUXchg;
2976     break;
2977 
2978   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2979   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2980   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
2981   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
2982     Form = C11CmpXchg;
2983     break;
2984 
2985   case AtomicExpr::AO__atomic_compare_exchange:
2986   case AtomicExpr::AO__atomic_compare_exchange_n:
2987     Form = GNUCmpXchg;
2988     break;
2989   }
2990 
2991   unsigned AdjustedNumArgs = NumArgs[Form];
2992   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
2993     ++AdjustedNumArgs;
2994   // Check we have the right number of arguments.
2995   if (TheCall->getNumArgs() < AdjustedNumArgs) {
2996     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2997       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
2998       << TheCall->getCallee()->getSourceRange();
2999     return ExprError();
3000   } else if (TheCall->getNumArgs() > AdjustedNumArgs) {
3001     Diag(TheCall->getArg(AdjustedNumArgs)->getLocStart(),
3002          diag::err_typecheck_call_too_many_args)
3003       << 0 << AdjustedNumArgs << TheCall->getNumArgs()
3004       << TheCall->getCallee()->getSourceRange();
3005     return ExprError();
3006   }
3007 
3008   // Inspect the first argument of the atomic operation.
3009   Expr *Ptr = TheCall->getArg(0);
3010   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
3011   if (ConvertedPtr.isInvalid())
3012     return ExprError();
3013 
3014   Ptr = ConvertedPtr.get();
3015   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
3016   if (!pointerType) {
3017     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3018       << Ptr->getType() << Ptr->getSourceRange();
3019     return ExprError();
3020   }
3021 
3022   // For a __c11 builtin, this should be a pointer to an _Atomic type.
3023   QualType AtomTy = pointerType->getPointeeType(); // 'A'
3024   QualType ValType = AtomTy; // 'C'
3025   if (IsC11) {
3026     if (!AtomTy->isAtomicType()) {
3027       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
3028         << Ptr->getType() << Ptr->getSourceRange();
3029       return ExprError();
3030     }
3031     if (AtomTy.isConstQualified() ||
3032         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
3033       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
3034           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
3035           << Ptr->getSourceRange();
3036       return ExprError();
3037     }
3038     ValType = AtomTy->getAs<AtomicType>()->getValueType();
3039   } else if (Form != Load && Form != LoadCopy) {
3040     if (ValType.isConstQualified()) {
3041       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
3042         << Ptr->getType() << Ptr->getSourceRange();
3043       return ExprError();
3044     }
3045   }
3046 
3047   // For an arithmetic operation, the implied arithmetic must be well-formed.
3048   if (Form == Arithmetic) {
3049     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
3050     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
3051       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3052         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3053       return ExprError();
3054     }
3055     if (!IsAddSub && !ValType->isIntegerType()) {
3056       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
3057         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3058       return ExprError();
3059     }
3060     if (IsC11 && ValType->isPointerType() &&
3061         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
3062                             diag::err_incomplete_type)) {
3063       return ExprError();
3064     }
3065   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
3066     // For __atomic_*_n operations, the value type must be a scalar integral or
3067     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
3068     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
3069       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
3070     return ExprError();
3071   }
3072 
3073   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
3074       !AtomTy->isScalarType()) {
3075     // For GNU atomics, require a trivially-copyable type. This is not part of
3076     // the GNU atomics specification, but we enforce it for sanity.
3077     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
3078       << Ptr->getType() << Ptr->getSourceRange();
3079     return ExprError();
3080   }
3081 
3082   switch (ValType.getObjCLifetime()) {
3083   case Qualifiers::OCL_None:
3084   case Qualifiers::OCL_ExplicitNone:
3085     // okay
3086     break;
3087 
3088   case Qualifiers::OCL_Weak:
3089   case Qualifiers::OCL_Strong:
3090   case Qualifiers::OCL_Autoreleasing:
3091     // FIXME: Can this happen? By this point, ValType should be known
3092     // to be trivially copyable.
3093     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3094       << ValType << Ptr->getSourceRange();
3095     return ExprError();
3096   }
3097 
3098   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
3099   // volatile-ness of the pointee-type inject itself into the result or the
3100   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
3101   ValType.removeLocalVolatile();
3102   ValType.removeLocalConst();
3103   QualType ResultType = ValType;
3104   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
3105       Form == Init)
3106     ResultType = Context.VoidTy;
3107   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
3108     ResultType = Context.BoolTy;
3109 
3110   // The type of a parameter passed 'by value'. In the GNU atomics, such
3111   // arguments are actually passed as pointers.
3112   QualType ByValType = ValType; // 'CP'
3113   if (!IsC11 && !IsN)
3114     ByValType = Ptr->getType();
3115 
3116   // The first argument --- the pointer --- has a fixed type; we
3117   // deduce the types of the rest of the arguments accordingly.  Walk
3118   // the remaining arguments, converting them to the deduced value type.
3119   for (unsigned i = 1; i != TheCall->getNumArgs(); ++i) {
3120     QualType Ty;
3121     if (i < NumVals[Form] + 1) {
3122       switch (i) {
3123       case 1:
3124         // The second argument is the non-atomic operand. For arithmetic, this
3125         // is always passed by value, and for a compare_exchange it is always
3126         // passed by address. For the rest, GNU uses by-address and C11 uses
3127         // by-value.
3128         assert(Form != Load);
3129         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
3130           Ty = ValType;
3131         else if (Form == Copy || Form == Xchg)
3132           Ty = ByValType;
3133         else if (Form == Arithmetic)
3134           Ty = Context.getPointerDiffType();
3135         else {
3136           Expr *ValArg = TheCall->getArg(i);
3137           // Treat this argument as _Nonnull as we want to show a warning if
3138           // NULL is passed into it.
3139           CheckNonNullArgument(*this, ValArg, DRE->getLocStart());
3140           unsigned AS = 0;
3141           // Keep address space of non-atomic pointer type.
3142           if (const PointerType *PtrTy =
3143                   ValArg->getType()->getAs<PointerType>()) {
3144             AS = PtrTy->getPointeeType().getAddressSpace();
3145           }
3146           Ty = Context.getPointerType(
3147               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
3148         }
3149         break;
3150       case 2:
3151         // The third argument to compare_exchange / GNU exchange is a
3152         // (pointer to a) desired value.
3153         Ty = ByValType;
3154         break;
3155       case 3:
3156         // The fourth argument to GNU compare_exchange is a 'weak' flag.
3157         Ty = Context.BoolTy;
3158         break;
3159       }
3160     } else {
3161       // The order(s) and scope are always converted to int.
3162       Ty = Context.IntTy;
3163     }
3164 
3165     InitializedEntity Entity =
3166         InitializedEntity::InitializeParameter(Context, Ty, false);
3167     ExprResult Arg = TheCall->getArg(i);
3168     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3169     if (Arg.isInvalid())
3170       return true;
3171     TheCall->setArg(i, Arg.get());
3172   }
3173 
3174   // Permute the arguments into a 'consistent' order.
3175   SmallVector<Expr*, 5> SubExprs;
3176   SubExprs.push_back(Ptr);
3177   switch (Form) {
3178   case Init:
3179     // Note, AtomicExpr::getVal1() has a special case for this atomic.
3180     SubExprs.push_back(TheCall->getArg(1)); // Val1
3181     break;
3182   case Load:
3183     SubExprs.push_back(TheCall->getArg(1)); // Order
3184     break;
3185   case LoadCopy:
3186   case Copy:
3187   case Arithmetic:
3188   case Xchg:
3189     SubExprs.push_back(TheCall->getArg(2)); // Order
3190     SubExprs.push_back(TheCall->getArg(1)); // Val1
3191     break;
3192   case GNUXchg:
3193     // Note, AtomicExpr::getVal2() has a special case for this atomic.
3194     SubExprs.push_back(TheCall->getArg(3)); // Order
3195     SubExprs.push_back(TheCall->getArg(1)); // Val1
3196     SubExprs.push_back(TheCall->getArg(2)); // Val2
3197     break;
3198   case C11CmpXchg:
3199     SubExprs.push_back(TheCall->getArg(3)); // Order
3200     SubExprs.push_back(TheCall->getArg(1)); // Val1
3201     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
3202     SubExprs.push_back(TheCall->getArg(2)); // Val2
3203     break;
3204   case GNUCmpXchg:
3205     SubExprs.push_back(TheCall->getArg(4)); // Order
3206     SubExprs.push_back(TheCall->getArg(1)); // Val1
3207     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
3208     SubExprs.push_back(TheCall->getArg(2)); // Val2
3209     SubExprs.push_back(TheCall->getArg(3)); // Weak
3210     break;
3211   }
3212 
3213   if (SubExprs.size() >= 2 && Form != Init) {
3214     llvm::APSInt Result(32);
3215     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
3216         !isValidOrderingForOp(Result.getSExtValue(), Op))
3217       Diag(SubExprs[1]->getLocStart(),
3218            diag::warn_atomic_op_has_invalid_memory_order)
3219           << SubExprs[1]->getSourceRange();
3220   }
3221 
3222   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
3223     auto *Scope = TheCall->getArg(TheCall->getNumArgs() - 1);
3224     llvm::APSInt Result(32);
3225     if (Scope->isIntegerConstantExpr(Result, Context) &&
3226         !ScopeModel->isValid(Result.getZExtValue())) {
3227       Diag(Scope->getLocStart(), diag::err_atomic_op_has_invalid_synch_scope)
3228           << Scope->getSourceRange();
3229     }
3230     SubExprs.push_back(Scope);
3231   }
3232 
3233   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
3234                                             SubExprs, ResultType, Op,
3235                                             TheCall->getRParenLoc());
3236 
3237   if ((Op == AtomicExpr::AO__c11_atomic_load ||
3238        Op == AtomicExpr::AO__c11_atomic_store ||
3239        Op == AtomicExpr::AO__opencl_atomic_load ||
3240        Op == AtomicExpr::AO__opencl_atomic_store ) &&
3241       Context.AtomicUsesUnsupportedLibcall(AE))
3242     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib)
3243         << ((Op == AtomicExpr::AO__c11_atomic_load ||
3244             Op == AtomicExpr::AO__opencl_atomic_load)
3245                 ? 0 : 1);
3246 
3247   return AE;
3248 }
3249 
3250 /// checkBuiltinArgument - Given a call to a builtin function, perform
3251 /// normal type-checking on the given argument, updating the call in
3252 /// place.  This is useful when a builtin function requires custom
3253 /// type-checking for some of its arguments but not necessarily all of
3254 /// them.
3255 ///
3256 /// Returns true on error.
3257 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
3258   FunctionDecl *Fn = E->getDirectCallee();
3259   assert(Fn && "builtin call without direct callee!");
3260 
3261   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
3262   InitializedEntity Entity =
3263     InitializedEntity::InitializeParameter(S.Context, Param);
3264 
3265   ExprResult Arg = E->getArg(0);
3266   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
3267   if (Arg.isInvalid())
3268     return true;
3269 
3270   E->setArg(ArgIndex, Arg.get());
3271   return false;
3272 }
3273 
3274 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
3275 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
3276 /// type of its first argument.  The main ActOnCallExpr routines have already
3277 /// promoted the types of arguments because all of these calls are prototyped as
3278 /// void(...).
3279 ///
3280 /// This function goes through and does final semantic checking for these
3281 /// builtins,
3282 ExprResult
3283 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
3284   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3285   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3286   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3287 
3288   // Ensure that we have at least one argument to do type inference from.
3289   if (TheCall->getNumArgs() < 1) {
3290     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3291       << 0 << 1 << TheCall->getNumArgs()
3292       << TheCall->getCallee()->getSourceRange();
3293     return ExprError();
3294   }
3295 
3296   // Inspect the first argument of the atomic builtin.  This should always be
3297   // a pointer type, whose element is an integral scalar or pointer type.
3298   // Because it is a pointer type, we don't have to worry about any implicit
3299   // casts here.
3300   // FIXME: We don't allow floating point scalars as input.
3301   Expr *FirstArg = TheCall->getArg(0);
3302   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3303   if (FirstArgResult.isInvalid())
3304     return ExprError();
3305   FirstArg = FirstArgResult.get();
3306   TheCall->setArg(0, FirstArg);
3307 
3308   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
3309   if (!pointerType) {
3310     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
3311       << FirstArg->getType() << FirstArg->getSourceRange();
3312     return ExprError();
3313   }
3314 
3315   QualType ValType = pointerType->getPointeeType();
3316   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3317       !ValType->isBlockPointerType()) {
3318     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3319       << FirstArg->getType() << FirstArg->getSourceRange();
3320     return ExprError();
3321   }
3322 
3323   switch (ValType.getObjCLifetime()) {
3324   case Qualifiers::OCL_None:
3325   case Qualifiers::OCL_ExplicitNone:
3326     // okay
3327     break;
3328 
3329   case Qualifiers::OCL_Weak:
3330   case Qualifiers::OCL_Strong:
3331   case Qualifiers::OCL_Autoreleasing:
3332     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
3333       << ValType << FirstArg->getSourceRange();
3334     return ExprError();
3335   }
3336 
3337   // Strip any qualifiers off ValType.
3338   ValType = ValType.getUnqualifiedType();
3339 
3340   // The majority of builtins return a value, but a few have special return
3341   // types, so allow them to override appropriately below.
3342   QualType ResultType = ValType;
3343 
3344   // We need to figure out which concrete builtin this maps onto.  For example,
3345   // __sync_fetch_and_add with a 2 byte object turns into
3346   // __sync_fetch_and_add_2.
3347 #define BUILTIN_ROW(x) \
3348   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3349     Builtin::BI##x##_8, Builtin::BI##x##_16 }
3350 
3351   static const unsigned BuiltinIndices[][5] = {
3352     BUILTIN_ROW(__sync_fetch_and_add),
3353     BUILTIN_ROW(__sync_fetch_and_sub),
3354     BUILTIN_ROW(__sync_fetch_and_or),
3355     BUILTIN_ROW(__sync_fetch_and_and),
3356     BUILTIN_ROW(__sync_fetch_and_xor),
3357     BUILTIN_ROW(__sync_fetch_and_nand),
3358 
3359     BUILTIN_ROW(__sync_add_and_fetch),
3360     BUILTIN_ROW(__sync_sub_and_fetch),
3361     BUILTIN_ROW(__sync_and_and_fetch),
3362     BUILTIN_ROW(__sync_or_and_fetch),
3363     BUILTIN_ROW(__sync_xor_and_fetch),
3364     BUILTIN_ROW(__sync_nand_and_fetch),
3365 
3366     BUILTIN_ROW(__sync_val_compare_and_swap),
3367     BUILTIN_ROW(__sync_bool_compare_and_swap),
3368     BUILTIN_ROW(__sync_lock_test_and_set),
3369     BUILTIN_ROW(__sync_lock_release),
3370     BUILTIN_ROW(__sync_swap)
3371   };
3372 #undef BUILTIN_ROW
3373 
3374   // Determine the index of the size.
3375   unsigned SizeIndex;
3376   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
3377   case 1: SizeIndex = 0; break;
3378   case 2: SizeIndex = 1; break;
3379   case 4: SizeIndex = 2; break;
3380   case 8: SizeIndex = 3; break;
3381   case 16: SizeIndex = 4; break;
3382   default:
3383     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
3384       << FirstArg->getType() << FirstArg->getSourceRange();
3385     return ExprError();
3386   }
3387 
3388   // Each of these builtins has one pointer argument, followed by some number of
3389   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
3390   // that we ignore.  Find out which row of BuiltinIndices to read from as well
3391   // as the number of fixed args.
3392   unsigned BuiltinID = FDecl->getBuiltinID();
3393   unsigned BuiltinIndex, NumFixed = 1;
3394   bool WarnAboutSemanticsChange = false;
3395   switch (BuiltinID) {
3396   default: llvm_unreachable("Unknown overloaded atomic builtin!");
3397   case Builtin::BI__sync_fetch_and_add:
3398   case Builtin::BI__sync_fetch_and_add_1:
3399   case Builtin::BI__sync_fetch_and_add_2:
3400   case Builtin::BI__sync_fetch_and_add_4:
3401   case Builtin::BI__sync_fetch_and_add_8:
3402   case Builtin::BI__sync_fetch_and_add_16:
3403     BuiltinIndex = 0;
3404     break;
3405 
3406   case Builtin::BI__sync_fetch_and_sub:
3407   case Builtin::BI__sync_fetch_and_sub_1:
3408   case Builtin::BI__sync_fetch_and_sub_2:
3409   case Builtin::BI__sync_fetch_and_sub_4:
3410   case Builtin::BI__sync_fetch_and_sub_8:
3411   case Builtin::BI__sync_fetch_and_sub_16:
3412     BuiltinIndex = 1;
3413     break;
3414 
3415   case Builtin::BI__sync_fetch_and_or:
3416   case Builtin::BI__sync_fetch_and_or_1:
3417   case Builtin::BI__sync_fetch_and_or_2:
3418   case Builtin::BI__sync_fetch_and_or_4:
3419   case Builtin::BI__sync_fetch_and_or_8:
3420   case Builtin::BI__sync_fetch_and_or_16:
3421     BuiltinIndex = 2;
3422     break;
3423 
3424   case Builtin::BI__sync_fetch_and_and:
3425   case Builtin::BI__sync_fetch_and_and_1:
3426   case Builtin::BI__sync_fetch_and_and_2:
3427   case Builtin::BI__sync_fetch_and_and_4:
3428   case Builtin::BI__sync_fetch_and_and_8:
3429   case Builtin::BI__sync_fetch_and_and_16:
3430     BuiltinIndex = 3;
3431     break;
3432 
3433   case Builtin::BI__sync_fetch_and_xor:
3434   case Builtin::BI__sync_fetch_and_xor_1:
3435   case Builtin::BI__sync_fetch_and_xor_2:
3436   case Builtin::BI__sync_fetch_and_xor_4:
3437   case Builtin::BI__sync_fetch_and_xor_8:
3438   case Builtin::BI__sync_fetch_and_xor_16:
3439     BuiltinIndex = 4;
3440     break;
3441 
3442   case Builtin::BI__sync_fetch_and_nand:
3443   case Builtin::BI__sync_fetch_and_nand_1:
3444   case Builtin::BI__sync_fetch_and_nand_2:
3445   case Builtin::BI__sync_fetch_and_nand_4:
3446   case Builtin::BI__sync_fetch_and_nand_8:
3447   case Builtin::BI__sync_fetch_and_nand_16:
3448     BuiltinIndex = 5;
3449     WarnAboutSemanticsChange = true;
3450     break;
3451 
3452   case Builtin::BI__sync_add_and_fetch:
3453   case Builtin::BI__sync_add_and_fetch_1:
3454   case Builtin::BI__sync_add_and_fetch_2:
3455   case Builtin::BI__sync_add_and_fetch_4:
3456   case Builtin::BI__sync_add_and_fetch_8:
3457   case Builtin::BI__sync_add_and_fetch_16:
3458     BuiltinIndex = 6;
3459     break;
3460 
3461   case Builtin::BI__sync_sub_and_fetch:
3462   case Builtin::BI__sync_sub_and_fetch_1:
3463   case Builtin::BI__sync_sub_and_fetch_2:
3464   case Builtin::BI__sync_sub_and_fetch_4:
3465   case Builtin::BI__sync_sub_and_fetch_8:
3466   case Builtin::BI__sync_sub_and_fetch_16:
3467     BuiltinIndex = 7;
3468     break;
3469 
3470   case Builtin::BI__sync_and_and_fetch:
3471   case Builtin::BI__sync_and_and_fetch_1:
3472   case Builtin::BI__sync_and_and_fetch_2:
3473   case Builtin::BI__sync_and_and_fetch_4:
3474   case Builtin::BI__sync_and_and_fetch_8:
3475   case Builtin::BI__sync_and_and_fetch_16:
3476     BuiltinIndex = 8;
3477     break;
3478 
3479   case Builtin::BI__sync_or_and_fetch:
3480   case Builtin::BI__sync_or_and_fetch_1:
3481   case Builtin::BI__sync_or_and_fetch_2:
3482   case Builtin::BI__sync_or_and_fetch_4:
3483   case Builtin::BI__sync_or_and_fetch_8:
3484   case Builtin::BI__sync_or_and_fetch_16:
3485     BuiltinIndex = 9;
3486     break;
3487 
3488   case Builtin::BI__sync_xor_and_fetch:
3489   case Builtin::BI__sync_xor_and_fetch_1:
3490   case Builtin::BI__sync_xor_and_fetch_2:
3491   case Builtin::BI__sync_xor_and_fetch_4:
3492   case Builtin::BI__sync_xor_and_fetch_8:
3493   case Builtin::BI__sync_xor_and_fetch_16:
3494     BuiltinIndex = 10;
3495     break;
3496 
3497   case Builtin::BI__sync_nand_and_fetch:
3498   case Builtin::BI__sync_nand_and_fetch_1:
3499   case Builtin::BI__sync_nand_and_fetch_2:
3500   case Builtin::BI__sync_nand_and_fetch_4:
3501   case Builtin::BI__sync_nand_and_fetch_8:
3502   case Builtin::BI__sync_nand_and_fetch_16:
3503     BuiltinIndex = 11;
3504     WarnAboutSemanticsChange = true;
3505     break;
3506 
3507   case Builtin::BI__sync_val_compare_and_swap:
3508   case Builtin::BI__sync_val_compare_and_swap_1:
3509   case Builtin::BI__sync_val_compare_and_swap_2:
3510   case Builtin::BI__sync_val_compare_and_swap_4:
3511   case Builtin::BI__sync_val_compare_and_swap_8:
3512   case Builtin::BI__sync_val_compare_and_swap_16:
3513     BuiltinIndex = 12;
3514     NumFixed = 2;
3515     break;
3516 
3517   case Builtin::BI__sync_bool_compare_and_swap:
3518   case Builtin::BI__sync_bool_compare_and_swap_1:
3519   case Builtin::BI__sync_bool_compare_and_swap_2:
3520   case Builtin::BI__sync_bool_compare_and_swap_4:
3521   case Builtin::BI__sync_bool_compare_and_swap_8:
3522   case Builtin::BI__sync_bool_compare_and_swap_16:
3523     BuiltinIndex = 13;
3524     NumFixed = 2;
3525     ResultType = Context.BoolTy;
3526     break;
3527 
3528   case Builtin::BI__sync_lock_test_and_set:
3529   case Builtin::BI__sync_lock_test_and_set_1:
3530   case Builtin::BI__sync_lock_test_and_set_2:
3531   case Builtin::BI__sync_lock_test_and_set_4:
3532   case Builtin::BI__sync_lock_test_and_set_8:
3533   case Builtin::BI__sync_lock_test_and_set_16:
3534     BuiltinIndex = 14;
3535     break;
3536 
3537   case Builtin::BI__sync_lock_release:
3538   case Builtin::BI__sync_lock_release_1:
3539   case Builtin::BI__sync_lock_release_2:
3540   case Builtin::BI__sync_lock_release_4:
3541   case Builtin::BI__sync_lock_release_8:
3542   case Builtin::BI__sync_lock_release_16:
3543     BuiltinIndex = 15;
3544     NumFixed = 0;
3545     ResultType = Context.VoidTy;
3546     break;
3547 
3548   case Builtin::BI__sync_swap:
3549   case Builtin::BI__sync_swap_1:
3550   case Builtin::BI__sync_swap_2:
3551   case Builtin::BI__sync_swap_4:
3552   case Builtin::BI__sync_swap_8:
3553   case Builtin::BI__sync_swap_16:
3554     BuiltinIndex = 16;
3555     break;
3556   }
3557 
3558   // Now that we know how many fixed arguments we expect, first check that we
3559   // have at least that many.
3560   if (TheCall->getNumArgs() < 1+NumFixed) {
3561     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3562       << 0 << 1+NumFixed << TheCall->getNumArgs()
3563       << TheCall->getCallee()->getSourceRange();
3564     return ExprError();
3565   }
3566 
3567   if (WarnAboutSemanticsChange) {
3568     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3569       << TheCall->getCallee()->getSourceRange();
3570   }
3571 
3572   // Get the decl for the concrete builtin from this, we can tell what the
3573   // concrete integer type we should convert to is.
3574   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3575   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
3576   FunctionDecl *NewBuiltinDecl;
3577   if (NewBuiltinID == BuiltinID)
3578     NewBuiltinDecl = FDecl;
3579   else {
3580     // Perform builtin lookup to avoid redeclaring it.
3581     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
3582     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
3583     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
3584     assert(Res.getFoundDecl());
3585     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
3586     if (!NewBuiltinDecl)
3587       return ExprError();
3588   }
3589 
3590   // The first argument --- the pointer --- has a fixed type; we
3591   // deduce the types of the rest of the arguments accordingly.  Walk
3592   // the remaining arguments, converting them to the deduced value type.
3593   for (unsigned i = 0; i != NumFixed; ++i) {
3594     ExprResult Arg = TheCall->getArg(i+1);
3595 
3596     // GCC does an implicit conversion to the pointer or integer ValType.  This
3597     // can fail in some cases (1i -> int**), check for this error case now.
3598     // Initialize the argument.
3599     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3600                                                    ValType, /*consume*/ false);
3601     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3602     if (Arg.isInvalid())
3603       return ExprError();
3604 
3605     // Okay, we have something that *can* be converted to the right type.  Check
3606     // to see if there is a potentially weird extension going on here.  This can
3607     // happen when you do an atomic operation on something like an char* and
3608     // pass in 42.  The 42 gets converted to char.  This is even more strange
3609     // for things like 45.123 -> char, etc.
3610     // FIXME: Do this check.
3611     TheCall->setArg(i+1, Arg.get());
3612   }
3613 
3614   ASTContext& Context = this->getASTContext();
3615 
3616   // Create a new DeclRefExpr to refer to the new decl.
3617   DeclRefExpr* NewDRE = DeclRefExpr::Create(
3618       Context,
3619       DRE->getQualifierLoc(),
3620       SourceLocation(),
3621       NewBuiltinDecl,
3622       /*enclosing*/ false,
3623       DRE->getLocation(),
3624       Context.BuiltinFnTy,
3625       DRE->getValueKind());
3626 
3627   // Set the callee in the CallExpr.
3628   // FIXME: This loses syntactic information.
3629   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
3630   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3631                                               CK_BuiltinFnToFnPtr);
3632   TheCall->setCallee(PromotedCall.get());
3633 
3634   // Change the result type of the call to match the original value type. This
3635   // is arbitrary, but the codegen for these builtins ins design to handle it
3636   // gracefully.
3637   TheCall->setType(ResultType);
3638 
3639   return TheCallResult;
3640 }
3641 
3642 /// SemaBuiltinNontemporalOverloaded - We have a call to
3643 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
3644 /// overloaded function based on the pointer type of its last argument.
3645 ///
3646 /// This function goes through and does final semantic checking for these
3647 /// builtins.
3648 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
3649   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
3650   DeclRefExpr *DRE =
3651       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3652   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3653   unsigned BuiltinID = FDecl->getBuiltinID();
3654   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3655           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3656          "Unexpected nontemporal load/store builtin!");
3657   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3658   unsigned numArgs = isStore ? 2 : 1;
3659 
3660   // Ensure that we have the proper number of arguments.
3661   if (checkArgCount(*this, TheCall, numArgs))
3662     return ExprError();
3663 
3664   // Inspect the last argument of the nontemporal builtin.  This should always
3665   // be a pointer type, from which we imply the type of the memory access.
3666   // Because it is a pointer type, we don't have to worry about any implicit
3667   // casts here.
3668   Expr *PointerArg = TheCall->getArg(numArgs - 1);
3669   ExprResult PointerArgResult =
3670       DefaultFunctionArrayLvalueConversion(PointerArg);
3671 
3672   if (PointerArgResult.isInvalid())
3673     return ExprError();
3674   PointerArg = PointerArgResult.get();
3675   TheCall->setArg(numArgs - 1, PointerArg);
3676 
3677   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
3678   if (!pointerType) {
3679     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3680         << PointerArg->getType() << PointerArg->getSourceRange();
3681     return ExprError();
3682   }
3683 
3684   QualType ValType = pointerType->getPointeeType();
3685 
3686   // Strip any qualifiers off ValType.
3687   ValType = ValType.getUnqualifiedType();
3688   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
3689       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
3690       !ValType->isVectorType()) {
3691     Diag(DRE->getLocStart(),
3692          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3693         << PointerArg->getType() << PointerArg->getSourceRange();
3694     return ExprError();
3695   }
3696 
3697   if (!isStore) {
3698     TheCall->setType(ValType);
3699     return TheCallResult;
3700   }
3701 
3702   ExprResult ValArg = TheCall->getArg(0);
3703   InitializedEntity Entity = InitializedEntity::InitializeParameter(
3704       Context, ValType, /*consume*/ false);
3705   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
3706   if (ValArg.isInvalid())
3707     return ExprError();
3708 
3709   TheCall->setArg(0, ValArg.get());
3710   TheCall->setType(Context.VoidTy);
3711   return TheCallResult;
3712 }
3713 
3714 /// CheckObjCString - Checks that the argument to the builtin
3715 /// CFString constructor is correct
3716 /// Note: It might also make sense to do the UTF-16 conversion here (would
3717 /// simplify the backend).
3718 bool Sema::CheckObjCString(Expr *Arg) {
3719   Arg = Arg->IgnoreParenCasts();
3720   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
3721 
3722   if (!Literal || !Literal->isAscii()) {
3723     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
3724       << Arg->getSourceRange();
3725     return true;
3726   }
3727 
3728   if (Literal->containsNonAsciiOrNull()) {
3729     StringRef String = Literal->getString();
3730     unsigned NumBytes = String.size();
3731     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
3732     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3733     llvm::UTF16 *ToPtr = &ToBuf[0];
3734 
3735     llvm::ConversionResult Result =
3736         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3737                                  ToPtr + NumBytes, llvm::strictConversion);
3738     // Check for conversion failure.
3739     if (Result != llvm::conversionOK)
3740       Diag(Arg->getLocStart(),
3741            diag::warn_cfstring_truncated) << Arg->getSourceRange();
3742   }
3743   return false;
3744 }
3745 
3746 /// CheckObjCString - Checks that the format string argument to the os_log()
3747 /// and os_trace() functions is correct, and converts it to const char *.
3748 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
3749   Arg = Arg->IgnoreParenCasts();
3750   auto *Literal = dyn_cast<StringLiteral>(Arg);
3751   if (!Literal) {
3752     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3753       Literal = ObjcLiteral->getString();
3754     }
3755   }
3756 
3757   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
3758     return ExprError(
3759         Diag(Arg->getLocStart(), diag::err_os_log_format_not_string_constant)
3760         << Arg->getSourceRange());
3761   }
3762 
3763   ExprResult Result(Literal);
3764   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
3765   InitializedEntity Entity =
3766       InitializedEntity::InitializeParameter(Context, ResultTy, false);
3767   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
3768   return Result;
3769 }
3770 
3771 /// Check that the user is calling the appropriate va_start builtin for the
3772 /// target and calling convention.
3773 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
3774   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
3775   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3776   bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3777   bool IsWindows = TT.isOSWindows();
3778   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3779   if (IsX64 || IsAArch64) {
3780     clang::CallingConv CC = CC_C;
3781     if (const FunctionDecl *FD = S.getCurFunctionDecl())
3782       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
3783     if (IsMSVAStart) {
3784       // Don't allow this in System V ABI functions.
3785       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
3786         return S.Diag(Fn->getLocStart(),
3787                       diag::err_ms_va_start_used_in_sysv_function);
3788     } else {
3789       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
3790       // On x64 Windows, don't allow this in System V ABI functions.
3791       // (Yes, that means there's no corresponding way to support variadic
3792       // System V ABI functions on Windows.)
3793       if ((IsWindows && CC == CC_X86_64SysV) ||
3794           (!IsWindows && CC == CC_Win64))
3795         return S.Diag(Fn->getLocStart(),
3796                       diag::err_va_start_used_in_wrong_abi_function)
3797                << !IsWindows;
3798     }
3799     return false;
3800   }
3801 
3802   if (IsMSVAStart)
3803     return S.Diag(Fn->getLocStart(), diag::err_builtin_x64_aarch64_only);
3804   return false;
3805 }
3806 
3807 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
3808                                              ParmVarDecl **LastParam = nullptr) {
3809   // Determine whether the current function, block, or obj-c method is variadic
3810   // and get its parameter list.
3811   bool IsVariadic = false;
3812   ArrayRef<ParmVarDecl *> Params;
3813   DeclContext *Caller = S.CurContext;
3814   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
3815     IsVariadic = Block->isVariadic();
3816     Params = Block->parameters();
3817   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3818     IsVariadic = FD->isVariadic();
3819     Params = FD->parameters();
3820   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3821     IsVariadic = MD->isVariadic();
3822     // FIXME: This isn't correct for methods (results in bogus warning).
3823     Params = MD->parameters();
3824   } else if (isa<CapturedDecl>(Caller)) {
3825     // We don't support va_start in a CapturedDecl.
3826     S.Diag(Fn->getLocStart(), diag::err_va_start_captured_stmt);
3827     return true;
3828   } else {
3829     // This must be some other declcontext that parses exprs.
3830     S.Diag(Fn->getLocStart(), diag::err_va_start_outside_function);
3831     return true;
3832   }
3833 
3834   if (!IsVariadic) {
3835     S.Diag(Fn->getLocStart(), diag::err_va_start_fixed_function);
3836     return true;
3837   }
3838 
3839   if (LastParam)
3840     *LastParam = Params.empty() ? nullptr : Params.back();
3841 
3842   return false;
3843 }
3844 
3845 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
3846 /// for validity.  Emit an error and return true on failure; return false
3847 /// on success.
3848 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
3849   Expr *Fn = TheCall->getCallee();
3850 
3851   if (checkVAStartABI(*this, BuiltinID, Fn))
3852     return true;
3853 
3854   if (TheCall->getNumArgs() > 2) {
3855     Diag(TheCall->getArg(2)->getLocStart(),
3856          diag::err_typecheck_call_too_many_args)
3857       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3858       << Fn->getSourceRange()
3859       << SourceRange(TheCall->getArg(2)->getLocStart(),
3860                      (*(TheCall->arg_end()-1))->getLocEnd());
3861     return true;
3862   }
3863 
3864   if (TheCall->getNumArgs() < 2) {
3865     return Diag(TheCall->getLocEnd(),
3866       diag::err_typecheck_call_too_few_args_at_least)
3867       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
3868   }
3869 
3870   // Type-check the first argument normally.
3871   if (checkBuiltinArgument(*this, TheCall, 0))
3872     return true;
3873 
3874   // Check that the current function is variadic, and get its last parameter.
3875   ParmVarDecl *LastParam;
3876   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
3877     return true;
3878 
3879   // Verify that the second argument to the builtin is the last argument of the
3880   // current function or method.
3881   bool SecondArgIsLastNamedArgument = false;
3882   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
3883 
3884   // These are valid if SecondArgIsLastNamedArgument is false after the next
3885   // block.
3886   QualType Type;
3887   SourceLocation ParamLoc;
3888   bool IsCRegister = false;
3889 
3890   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3891     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3892       SecondArgIsLastNamedArgument = PV == LastParam;
3893 
3894       Type = PV->getType();
3895       ParamLoc = PV->getLocation();
3896       IsCRegister =
3897           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
3898     }
3899   }
3900 
3901   if (!SecondArgIsLastNamedArgument)
3902     Diag(TheCall->getArg(1)->getLocStart(),
3903          diag::warn_second_arg_of_va_start_not_last_named_param);
3904   else if (IsCRegister || Type->isReferenceType() ||
3905            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
3906              // Promotable integers are UB, but enumerations need a bit of
3907              // extra checking to see what their promotable type actually is.
3908              if (!Type->isPromotableIntegerType())
3909                return false;
3910              if (!Type->isEnumeralType())
3911                return true;
3912              const EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3913              return !(ED &&
3914                       Context.typesAreCompatible(ED->getPromotionType(), Type));
3915            }()) {
3916     unsigned Reason = 0;
3917     if (Type->isReferenceType())  Reason = 1;
3918     else if (IsCRegister)         Reason = 2;
3919     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3920     Diag(ParamLoc, diag::note_parameter_type) << Type;
3921   }
3922 
3923   TheCall->setType(Context.VoidTy);
3924   return false;
3925 }
3926 
3927 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
3928   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
3929   //                 const char *named_addr);
3930 
3931   Expr *Func = Call->getCallee();
3932 
3933   if (Call->getNumArgs() < 3)
3934     return Diag(Call->getLocEnd(),
3935                 diag::err_typecheck_call_too_few_args_at_least)
3936            << 0 /*function call*/ << 3 << Call->getNumArgs();
3937 
3938   // Type-check the first argument normally.
3939   if (checkBuiltinArgument(*this, Call, 0))
3940     return true;
3941 
3942   // Check that the current function is variadic.
3943   if (checkVAStartIsInVariadicFunction(*this, Func))
3944     return true;
3945 
3946   // __va_start on Windows does not validate the parameter qualifiers
3947 
3948   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
3949   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
3950 
3951   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
3952   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
3953 
3954   const QualType &ConstCharPtrTy =
3955       Context.getPointerType(Context.CharTy.withConst());
3956   if (!Arg1Ty->isPointerType() ||
3957       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
3958     Diag(Arg1->getLocStart(), diag::err_typecheck_convert_incompatible)
3959         << Arg1->getType() << ConstCharPtrTy
3960         << 1 /* different class */
3961         << 0 /* qualifier difference */
3962         << 3 /* parameter mismatch */
3963         << 2 << Arg1->getType() << ConstCharPtrTy;
3964 
3965   const QualType SizeTy = Context.getSizeType();
3966   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
3967     Diag(Arg2->getLocStart(), diag::err_typecheck_convert_incompatible)
3968         << Arg2->getType() << SizeTy
3969         << 1 /* different class */
3970         << 0 /* qualifier difference */
3971         << 3 /* parameter mismatch */
3972         << 3 << Arg2->getType() << SizeTy;
3973 
3974   return false;
3975 }
3976 
3977 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
3978 /// friends.  This is declared to take (...), so we have to check everything.
3979 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
3980   if (TheCall->getNumArgs() < 2)
3981     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
3982       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
3983   if (TheCall->getNumArgs() > 2)
3984     return Diag(TheCall->getArg(2)->getLocStart(),
3985                 diag::err_typecheck_call_too_many_args)
3986       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
3987       << SourceRange(TheCall->getArg(2)->getLocStart(),
3988                      (*(TheCall->arg_end()-1))->getLocEnd());
3989 
3990   ExprResult OrigArg0 = TheCall->getArg(0);
3991   ExprResult OrigArg1 = TheCall->getArg(1);
3992 
3993   // Do standard promotions between the two arguments, returning their common
3994   // type.
3995   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
3996   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
3997     return true;
3998 
3999   // Make sure any conversions are pushed back into the call; this is
4000   // type safe since unordered compare builtins are declared as "_Bool
4001   // foo(...)".
4002   TheCall->setArg(0, OrigArg0.get());
4003   TheCall->setArg(1, OrigArg1.get());
4004 
4005   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
4006     return false;
4007 
4008   // If the common type isn't a real floating type, then the arguments were
4009   // invalid for this operation.
4010   if (Res.isNull() || !Res->isRealFloatingType())
4011     return Diag(OrigArg0.get()->getLocStart(),
4012                 diag::err_typecheck_call_invalid_ordered_compare)
4013       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
4014       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
4015 
4016   return false;
4017 }
4018 
4019 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
4020 /// __builtin_isnan and friends.  This is declared to take (...), so we have
4021 /// to check everything. We expect the last argument to be a floating point
4022 /// value.
4023 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
4024   if (TheCall->getNumArgs() < NumArgs)
4025     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4026       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
4027   if (TheCall->getNumArgs() > NumArgs)
4028     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
4029                 diag::err_typecheck_call_too_many_args)
4030       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
4031       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
4032                      (*(TheCall->arg_end()-1))->getLocEnd());
4033 
4034   Expr *OrigArg = TheCall->getArg(NumArgs-1);
4035 
4036   if (OrigArg->isTypeDependent())
4037     return false;
4038 
4039   // This operation requires a non-_Complex floating-point number.
4040   if (!OrigArg->getType()->isRealFloatingType())
4041     return Diag(OrigArg->getLocStart(),
4042                 diag::err_typecheck_call_invalid_unary_fp)
4043       << OrigArg->getType() << OrigArg->getSourceRange();
4044 
4045   // If this is an implicit conversion from float -> float or double, remove it.
4046   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
4047     // Only remove standard FloatCasts, leaving other casts inplace
4048     if (Cast->getCastKind() == CK_FloatingCast) {
4049       Expr *CastArg = Cast->getSubExpr();
4050       if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
4051           assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
4052                   Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
4053                "promotion from float to either float or double is the only expected cast here");
4054         Cast->setSubExpr(nullptr);
4055         TheCall->setArg(NumArgs-1, CastArg);
4056       }
4057     }
4058   }
4059 
4060   return false;
4061 }
4062 
4063 // Customized Sema Checking for VSX builtins that have the following signature:
4064 // vector [...] builtinName(vector [...], vector [...], const int);
4065 // Which takes the same type of vectors (any legal vector type) for the first
4066 // two arguments and takes compile time constant for the third argument.
4067 // Example builtins are :
4068 // vector double vec_xxpermdi(vector double, vector double, int);
4069 // vector short vec_xxsldwi(vector short, vector short, int);
4070 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
4071   unsigned ExpectedNumArgs = 3;
4072   if (TheCall->getNumArgs() < ExpectedNumArgs)
4073     return Diag(TheCall->getLocEnd(),
4074                 diag::err_typecheck_call_too_few_args_at_least)
4075            << 0 /*function call*/ <<  ExpectedNumArgs << TheCall->getNumArgs()
4076            << TheCall->getSourceRange();
4077 
4078   if (TheCall->getNumArgs() > ExpectedNumArgs)
4079     return Diag(TheCall->getLocEnd(),
4080                 diag::err_typecheck_call_too_many_args_at_most)
4081            << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs()
4082            << TheCall->getSourceRange();
4083 
4084   // Check the third argument is a compile time constant
4085   llvm::APSInt Value;
4086   if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context))
4087     return Diag(TheCall->getLocStart(),
4088                 diag::err_vsx_builtin_nonconstant_argument)
4089            << 3 /* argument index */ << TheCall->getDirectCallee()
4090            << SourceRange(TheCall->getArg(2)->getLocStart(),
4091                           TheCall->getArg(2)->getLocEnd());
4092 
4093   QualType Arg1Ty = TheCall->getArg(0)->getType();
4094   QualType Arg2Ty = TheCall->getArg(1)->getType();
4095 
4096   // Check the type of argument 1 and argument 2 are vectors.
4097   SourceLocation BuiltinLoc = TheCall->getLocStart();
4098   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
4099       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
4100     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
4101            << TheCall->getDirectCallee()
4102            << SourceRange(TheCall->getArg(0)->getLocStart(),
4103                           TheCall->getArg(1)->getLocEnd());
4104   }
4105 
4106   // Check the first two arguments are the same type.
4107   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
4108     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
4109            << TheCall->getDirectCallee()
4110            << SourceRange(TheCall->getArg(0)->getLocStart(),
4111                           TheCall->getArg(1)->getLocEnd());
4112   }
4113 
4114   // When default clang type checking is turned off and the customized type
4115   // checking is used, the returning type of the function must be explicitly
4116   // set. Otherwise it is _Bool by default.
4117   TheCall->setType(Arg1Ty);
4118 
4119   return false;
4120 }
4121 
4122 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
4123 // This is declared to take (...), so we have to check everything.
4124 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
4125   if (TheCall->getNumArgs() < 2)
4126     return ExprError(Diag(TheCall->getLocEnd(),
4127                           diag::err_typecheck_call_too_few_args_at_least)
4128                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
4129                      << TheCall->getSourceRange());
4130 
4131   // Determine which of the following types of shufflevector we're checking:
4132   // 1) unary, vector mask: (lhs, mask)
4133   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
4134   QualType resType = TheCall->getArg(0)->getType();
4135   unsigned numElements = 0;
4136 
4137   if (!TheCall->getArg(0)->isTypeDependent() &&
4138       !TheCall->getArg(1)->isTypeDependent()) {
4139     QualType LHSType = TheCall->getArg(0)->getType();
4140     QualType RHSType = TheCall->getArg(1)->getType();
4141 
4142     if (!LHSType->isVectorType() || !RHSType->isVectorType())
4143       return ExprError(Diag(TheCall->getLocStart(),
4144                             diag::err_vec_builtin_non_vector)
4145                        << TheCall->getDirectCallee()
4146                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4147                                       TheCall->getArg(1)->getLocEnd()));
4148 
4149     numElements = LHSType->getAs<VectorType>()->getNumElements();
4150     unsigned numResElements = TheCall->getNumArgs() - 2;
4151 
4152     // Check to see if we have a call with 2 vector arguments, the unary shuffle
4153     // with mask.  If so, verify that RHS is an integer vector type with the
4154     // same number of elts as lhs.
4155     if (TheCall->getNumArgs() == 2) {
4156       if (!RHSType->hasIntegerRepresentation() ||
4157           RHSType->getAs<VectorType>()->getNumElements() != numElements)
4158         return ExprError(Diag(TheCall->getLocStart(),
4159                               diag::err_vec_builtin_incompatible_vector)
4160                          << TheCall->getDirectCallee()
4161                          << SourceRange(TheCall->getArg(1)->getLocStart(),
4162                                         TheCall->getArg(1)->getLocEnd()));
4163     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
4164       return ExprError(Diag(TheCall->getLocStart(),
4165                             diag::err_vec_builtin_incompatible_vector)
4166                        << TheCall->getDirectCallee()
4167                        << SourceRange(TheCall->getArg(0)->getLocStart(),
4168                                       TheCall->getArg(1)->getLocEnd()));
4169     } else if (numElements != numResElements) {
4170       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
4171       resType = Context.getVectorType(eltType, numResElements,
4172                                       VectorType::GenericVector);
4173     }
4174   }
4175 
4176   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
4177     if (TheCall->getArg(i)->isTypeDependent() ||
4178         TheCall->getArg(i)->isValueDependent())
4179       continue;
4180 
4181     llvm::APSInt Result(32);
4182     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
4183       return ExprError(Diag(TheCall->getLocStart(),
4184                             diag::err_shufflevector_nonconstant_argument)
4185                        << TheCall->getArg(i)->getSourceRange());
4186 
4187     // Allow -1 which will be translated to undef in the IR.
4188     if (Result.isSigned() && Result.isAllOnesValue())
4189       continue;
4190 
4191     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4192       return ExprError(Diag(TheCall->getLocStart(),
4193                             diag::err_shufflevector_argument_too_large)
4194                        << TheCall->getArg(i)->getSourceRange());
4195   }
4196 
4197   SmallVector<Expr*, 32> exprs;
4198 
4199   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
4200     exprs.push_back(TheCall->getArg(i));
4201     TheCall->setArg(i, nullptr);
4202   }
4203 
4204   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
4205                                          TheCall->getCallee()->getLocStart(),
4206                                          TheCall->getRParenLoc());
4207 }
4208 
4209 /// SemaConvertVectorExpr - Handle __builtin_convertvector
4210 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
4211                                        SourceLocation BuiltinLoc,
4212                                        SourceLocation RParenLoc) {
4213   ExprValueKind VK = VK_RValue;
4214   ExprObjectKind OK = OK_Ordinary;
4215   QualType DstTy = TInfo->getType();
4216   QualType SrcTy = E->getType();
4217 
4218   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
4219     return ExprError(Diag(BuiltinLoc,
4220                           diag::err_convertvector_non_vector)
4221                      << E->getSourceRange());
4222   if (!DstTy->isVectorType() && !DstTy->isDependentType())
4223     return ExprError(Diag(BuiltinLoc,
4224                           diag::err_convertvector_non_vector_type));
4225 
4226   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
4227     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
4228     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
4229     if (SrcElts != DstElts)
4230       return ExprError(Diag(BuiltinLoc,
4231                             diag::err_convertvector_incompatible_vector)
4232                        << E->getSourceRange());
4233   }
4234 
4235   return new (Context)
4236       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4237 }
4238 
4239 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
4240 // This is declared to take (const void*, ...) and can take two
4241 // optional constant int args.
4242 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
4243   unsigned NumArgs = TheCall->getNumArgs();
4244 
4245   if (NumArgs > 3)
4246     return Diag(TheCall->getLocEnd(),
4247              diag::err_typecheck_call_too_many_args_at_most)
4248              << 0 /*function call*/ << 3 << NumArgs
4249              << TheCall->getSourceRange();
4250 
4251   // Argument 0 is checked for us and the remaining arguments must be
4252   // constant integers.
4253   for (unsigned i = 1; i != NumArgs; ++i)
4254     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4255       return true;
4256 
4257   return false;
4258 }
4259 
4260 /// SemaBuiltinAssume - Handle __assume (MS Extension).
4261 // __assume does not evaluate its arguments, and should warn if its argument
4262 // has side effects.
4263 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
4264   Expr *Arg = TheCall->getArg(0);
4265   if (Arg->isInstantiationDependent()) return false;
4266 
4267   if (Arg->HasSideEffects(Context))
4268     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
4269       << Arg->getSourceRange()
4270       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
4271 
4272   return false;
4273 }
4274 
4275 /// Handle __builtin_alloca_with_align. This is declared
4276 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
4277 /// than 8.
4278 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
4279   // The alignment must be a constant integer.
4280   Expr *Arg = TheCall->getArg(1);
4281 
4282   // We can't check the value of a dependent argument.
4283   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4284     if (const auto *UE =
4285             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
4286       if (UE->getKind() == UETT_AlignOf)
4287         Diag(TheCall->getLocStart(), diag::warn_alloca_align_alignof)
4288           << Arg->getSourceRange();
4289 
4290     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
4291 
4292     if (!Result.isPowerOf2())
4293       return Diag(TheCall->getLocStart(),
4294                   diag::err_alignment_not_power_of_two)
4295            << Arg->getSourceRange();
4296 
4297     if (Result < Context.getCharWidth())
4298       return Diag(TheCall->getLocStart(), diag::err_alignment_too_small)
4299            << (unsigned)Context.getCharWidth()
4300            << Arg->getSourceRange();
4301 
4302     if (Result > INT32_MAX)
4303       return Diag(TheCall->getLocStart(), diag::err_alignment_too_big)
4304            << INT32_MAX
4305            << Arg->getSourceRange();
4306   }
4307 
4308   return false;
4309 }
4310 
4311 /// Handle __builtin_assume_aligned. This is declared
4312 /// as (const void*, size_t, ...) and can take one optional constant int arg.
4313 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
4314   unsigned NumArgs = TheCall->getNumArgs();
4315 
4316   if (NumArgs > 3)
4317     return Diag(TheCall->getLocEnd(),
4318              diag::err_typecheck_call_too_many_args_at_most)
4319              << 0 /*function call*/ << 3 << NumArgs
4320              << TheCall->getSourceRange();
4321 
4322   // The alignment must be a constant integer.
4323   Expr *Arg = TheCall->getArg(1);
4324 
4325   // We can't check the value of a dependent argument.
4326   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
4327     llvm::APSInt Result;
4328     if (SemaBuiltinConstantArg(TheCall, 1, Result))
4329       return true;
4330 
4331     if (!Result.isPowerOf2())
4332       return Diag(TheCall->getLocStart(),
4333                   diag::err_alignment_not_power_of_two)
4334            << Arg->getSourceRange();
4335   }
4336 
4337   if (NumArgs > 2) {
4338     ExprResult Arg(TheCall->getArg(2));
4339     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
4340       Context.getSizeType(), false);
4341     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4342     if (Arg.isInvalid()) return true;
4343     TheCall->setArg(2, Arg.get());
4344   }
4345 
4346   return false;
4347 }
4348 
4349 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
4350   unsigned BuiltinID =
4351       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
4352   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4353 
4354   unsigned NumArgs = TheCall->getNumArgs();
4355   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4356   if (NumArgs < NumRequiredArgs) {
4357     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
4358            << 0 /* function call */ << NumRequiredArgs << NumArgs
4359            << TheCall->getSourceRange();
4360   }
4361   if (NumArgs >= NumRequiredArgs + 0x100) {
4362     return Diag(TheCall->getLocEnd(),
4363                 diag::err_typecheck_call_too_many_args_at_most)
4364            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
4365            << TheCall->getSourceRange();
4366   }
4367   unsigned i = 0;
4368 
4369   // For formatting call, check buffer arg.
4370   if (!IsSizeCall) {
4371     ExprResult Arg(TheCall->getArg(i));
4372     InitializedEntity Entity = InitializedEntity::InitializeParameter(
4373         Context, Context.VoidPtrTy, false);
4374     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
4375     if (Arg.isInvalid())
4376       return true;
4377     TheCall->setArg(i, Arg.get());
4378     i++;
4379   }
4380 
4381   // Check string literal arg.
4382   unsigned FormatIdx = i;
4383   {
4384     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
4385     if (Arg.isInvalid())
4386       return true;
4387     TheCall->setArg(i, Arg.get());
4388     i++;
4389   }
4390 
4391   // Make sure variadic args are scalar.
4392   unsigned FirstDataArg = i;
4393   while (i < NumArgs) {
4394     ExprResult Arg = DefaultVariadicArgumentPromotion(
4395         TheCall->getArg(i), VariadicFunction, nullptr);
4396     if (Arg.isInvalid())
4397       return true;
4398     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
4399     if (ArgSize.getQuantity() >= 0x100) {
4400       return Diag(Arg.get()->getLocEnd(), diag::err_os_log_argument_too_big)
4401              << i << (int)ArgSize.getQuantity() << 0xff
4402              << TheCall->getSourceRange();
4403     }
4404     TheCall->setArg(i, Arg.get());
4405     i++;
4406   }
4407 
4408   // Check formatting specifiers. NOTE: We're only doing this for the non-size
4409   // call to avoid duplicate diagnostics.
4410   if (!IsSizeCall) {
4411     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
4412     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
4413     bool Success = CheckFormatArguments(
4414         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
4415         VariadicFunction, TheCall->getLocStart(), SourceRange(),
4416         CheckedVarArgs);
4417     if (!Success)
4418       return true;
4419   }
4420 
4421   if (IsSizeCall) {
4422     TheCall->setType(Context.getSizeType());
4423   } else {
4424     TheCall->setType(Context.VoidPtrTy);
4425   }
4426   return false;
4427 }
4428 
4429 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
4430 /// TheCall is a constant expression.
4431 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
4432                                   llvm::APSInt &Result) {
4433   Expr *Arg = TheCall->getArg(ArgNum);
4434   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4435   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
4436 
4437   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
4438 
4439   if (!Arg->isIntegerConstantExpr(Result, Context))
4440     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
4441                 << FDecl->getDeclName() <<  Arg->getSourceRange();
4442 
4443   return false;
4444 }
4445 
4446 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
4447 /// TheCall is a constant expression in the range [Low, High].
4448 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
4449                                        int Low, int High) {
4450   llvm::APSInt Result;
4451 
4452   // We can't check the value of a dependent argument.
4453   Expr *Arg = TheCall->getArg(ArgNum);
4454   if (Arg->isTypeDependent() || Arg->isValueDependent())
4455     return false;
4456 
4457   // Check constant-ness first.
4458   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4459     return true;
4460 
4461   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4462     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
4463       << Low << High << Arg->getSourceRange();
4464 
4465   return false;
4466 }
4467 
4468 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
4469 /// TheCall is a constant expression is a multiple of Num..
4470 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
4471                                           unsigned Num) {
4472   llvm::APSInt Result;
4473 
4474   // We can't check the value of a dependent argument.
4475   Expr *Arg = TheCall->getArg(ArgNum);
4476   if (Arg->isTypeDependent() || Arg->isValueDependent())
4477     return false;
4478 
4479   // Check constant-ness first.
4480   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4481     return true;
4482 
4483   if (Result.getSExtValue() % Num != 0)
4484     return Diag(TheCall->getLocStart(), diag::err_argument_not_multiple)
4485       << Num << Arg->getSourceRange();
4486 
4487   return false;
4488 }
4489 
4490 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
4491 /// TheCall is an ARM/AArch64 special register string literal.
4492 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
4493                                     int ArgNum, unsigned ExpectedFieldNum,
4494                                     bool AllowName) {
4495   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4496                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4497                       BuiltinID == ARM::BI__builtin_arm_rsr ||
4498                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
4499                       BuiltinID == ARM::BI__builtin_arm_wsr ||
4500                       BuiltinID == ARM::BI__builtin_arm_wsrp;
4501   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4502                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4503                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
4504                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4505                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
4506                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
4507   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
4508 
4509   // We can't check the value of a dependent argument.
4510   Expr *Arg = TheCall->getArg(ArgNum);
4511   if (Arg->isTypeDependent() || Arg->isValueDependent())
4512     return false;
4513 
4514   // Check if the argument is a string literal.
4515   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
4516     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
4517            << Arg->getSourceRange();
4518 
4519   // Check the type of special register given.
4520   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
4521   SmallVector<StringRef, 6> Fields;
4522   Reg.split(Fields, ":");
4523 
4524   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4525     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4526            << Arg->getSourceRange();
4527 
4528   // If the string is the name of a register then we cannot check that it is
4529   // valid here but if the string is of one the forms described in ACLE then we
4530   // can check that the supplied fields are integers and within the valid
4531   // ranges.
4532   if (Fields.size() > 1) {
4533     bool FiveFields = Fields.size() == 5;
4534 
4535     bool ValidString = true;
4536     if (IsARMBuiltin) {
4537       ValidString &= Fields[0].startswith_lower("cp") ||
4538                      Fields[0].startswith_lower("p");
4539       if (ValidString)
4540         Fields[0] =
4541           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
4542 
4543       ValidString &= Fields[2].startswith_lower("c");
4544       if (ValidString)
4545         Fields[2] = Fields[2].drop_front(1);
4546 
4547       if (FiveFields) {
4548         ValidString &= Fields[3].startswith_lower("c");
4549         if (ValidString)
4550           Fields[3] = Fields[3].drop_front(1);
4551       }
4552     }
4553 
4554     SmallVector<int, 5> Ranges;
4555     if (FiveFields)
4556       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4557     else
4558       Ranges.append({15, 7, 15});
4559 
4560     for (unsigned i=0; i<Fields.size(); ++i) {
4561       int IntField;
4562       ValidString &= !Fields[i].getAsInteger(10, IntField);
4563       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4564     }
4565 
4566     if (!ValidString)
4567       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
4568              << Arg->getSourceRange();
4569 
4570   } else if (IsAArch64Builtin && Fields.size() == 1) {
4571     // If the register name is one of those that appear in the condition below
4572     // and the special register builtin being used is one of the write builtins,
4573     // then we require that the argument provided for writing to the register
4574     // is an integer constant expression. This is because it will be lowered to
4575     // an MSR (immediate) instruction, so we need to know the immediate at
4576     // compile time.
4577     if (TheCall->getNumArgs() != 2)
4578       return false;
4579 
4580     std::string RegLower = Reg.lower();
4581     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
4582         RegLower != "pan" && RegLower != "uao")
4583       return false;
4584 
4585     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4586   }
4587 
4588   return false;
4589 }
4590 
4591 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
4592 /// This checks that the target supports __builtin_longjmp and
4593 /// that val is a constant 1.
4594 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
4595   if (!Context.getTargetInfo().hasSjLjLowering())
4596     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
4597              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4598 
4599   Expr *Arg = TheCall->getArg(1);
4600   llvm::APSInt Result;
4601 
4602   // TODO: This is less than ideal. Overload this to take a value.
4603   if (SemaBuiltinConstantArg(TheCall, 1, Result))
4604     return true;
4605 
4606   if (Result != 1)
4607     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
4608              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
4609 
4610   return false;
4611 }
4612 
4613 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
4614 /// This checks that the target supports __builtin_setjmp.
4615 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
4616   if (!Context.getTargetInfo().hasSjLjLowering())
4617     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
4618              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
4619   return false;
4620 }
4621 
4622 namespace {
4623 class UncoveredArgHandler {
4624   enum { Unknown = -1, AllCovered = -2 };
4625   signed FirstUncoveredArg;
4626   SmallVector<const Expr *, 4> DiagnosticExprs;
4627 
4628 public:
4629   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
4630 
4631   bool hasUncoveredArg() const {
4632     return (FirstUncoveredArg >= 0);
4633   }
4634 
4635   unsigned getUncoveredArg() const {
4636     assert(hasUncoveredArg() && "no uncovered argument");
4637     return FirstUncoveredArg;
4638   }
4639 
4640   void setAllCovered() {
4641     // A string has been found with all arguments covered, so clear out
4642     // the diagnostics.
4643     DiagnosticExprs.clear();
4644     FirstUncoveredArg = AllCovered;
4645   }
4646 
4647   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
4648     assert(NewFirstUncoveredArg >= 0 && "Outside range");
4649 
4650     // Don't update if a previous string covers all arguments.
4651     if (FirstUncoveredArg == AllCovered)
4652       return;
4653 
4654     // UncoveredArgHandler tracks the highest uncovered argument index
4655     // and with it all the strings that match this index.
4656     if (NewFirstUncoveredArg == FirstUncoveredArg)
4657       DiagnosticExprs.push_back(StrExpr);
4658     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4659       DiagnosticExprs.clear();
4660       DiagnosticExprs.push_back(StrExpr);
4661       FirstUncoveredArg = NewFirstUncoveredArg;
4662     }
4663   }
4664 
4665   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
4666 };
4667 
4668 enum StringLiteralCheckType {
4669   SLCT_NotALiteral,
4670   SLCT_UncheckedLiteral,
4671   SLCT_CheckedLiteral
4672 };
4673 } // end anonymous namespace
4674 
4675 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
4676                                      BinaryOperatorKind BinOpKind,
4677                                      bool AddendIsRight) {
4678   unsigned BitWidth = Offset.getBitWidth();
4679   unsigned AddendBitWidth = Addend.getBitWidth();
4680   // There might be negative interim results.
4681   if (Addend.isUnsigned()) {
4682     Addend = Addend.zext(++AddendBitWidth);
4683     Addend.setIsSigned(true);
4684   }
4685   // Adjust the bit width of the APSInts.
4686   if (AddendBitWidth > BitWidth) {
4687     Offset = Offset.sext(AddendBitWidth);
4688     BitWidth = AddendBitWidth;
4689   } else if (BitWidth > AddendBitWidth) {
4690     Addend = Addend.sext(BitWidth);
4691   }
4692 
4693   bool Ov = false;
4694   llvm::APSInt ResOffset = Offset;
4695   if (BinOpKind == BO_Add)
4696     ResOffset = Offset.sadd_ov(Addend, Ov);
4697   else {
4698     assert(AddendIsRight && BinOpKind == BO_Sub &&
4699            "operator must be add or sub with addend on the right");
4700     ResOffset = Offset.ssub_ov(Addend, Ov);
4701   }
4702 
4703   // We add an offset to a pointer here so we should support an offset as big as
4704   // possible.
4705   if (Ov) {
4706     assert(BitWidth <= UINT_MAX / 2 && "index (intermediate) result too big");
4707     Offset = Offset.sext(2 * BitWidth);
4708     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4709     return;
4710   }
4711 
4712   Offset = ResOffset;
4713 }
4714 
4715 namespace {
4716 // This is a wrapper class around StringLiteral to support offsetted string
4717 // literals as format strings. It takes the offset into account when returning
4718 // the string and its length or the source locations to display notes correctly.
4719 class FormatStringLiteral {
4720   const StringLiteral *FExpr;
4721   int64_t Offset;
4722 
4723  public:
4724   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
4725       : FExpr(fexpr), Offset(Offset) {}
4726 
4727   StringRef getString() const {
4728     return FExpr->getString().drop_front(Offset);
4729   }
4730 
4731   unsigned getByteLength() const {
4732     return FExpr->getByteLength() - getCharByteWidth() * Offset;
4733   }
4734   unsigned getLength() const { return FExpr->getLength() - Offset; }
4735   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
4736 
4737   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
4738 
4739   QualType getType() const { return FExpr->getType(); }
4740 
4741   bool isAscii() const { return FExpr->isAscii(); }
4742   bool isWide() const { return FExpr->isWide(); }
4743   bool isUTF8() const { return FExpr->isUTF8(); }
4744   bool isUTF16() const { return FExpr->isUTF16(); }
4745   bool isUTF32() const { return FExpr->isUTF32(); }
4746   bool isPascal() const { return FExpr->isPascal(); }
4747 
4748   SourceLocation getLocationOfByte(
4749       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
4750       const TargetInfo &Target, unsigned *StartToken = nullptr,
4751       unsigned *StartTokenByteOffset = nullptr) const {
4752     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
4753                                     StartToken, StartTokenByteOffset);
4754   }
4755 
4756   SourceLocation getLocStart() const LLVM_READONLY {
4757     return FExpr->getLocStart().getLocWithOffset(Offset);
4758   }
4759   SourceLocation getLocEnd() const LLVM_READONLY { return FExpr->getLocEnd(); }
4760 };
4761 }  // end anonymous namespace
4762 
4763 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
4764                               const Expr *OrigFormatExpr,
4765                               ArrayRef<const Expr *> Args,
4766                               bool HasVAListArg, unsigned format_idx,
4767                               unsigned firstDataArg,
4768                               Sema::FormatStringType Type,
4769                               bool inFunctionCall,
4770                               Sema::VariadicCallType CallType,
4771                               llvm::SmallBitVector &CheckedVarArgs,
4772                               UncoveredArgHandler &UncoveredArg);
4773 
4774 // Determine if an expression is a string literal or constant string.
4775 // If this function returns false on the arguments to a function expecting a
4776 // format string, we will usually need to emit a warning.
4777 // True string literals are then checked by CheckFormatString.
4778 static StringLiteralCheckType
4779 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
4780                       bool HasVAListArg, unsigned format_idx,
4781                       unsigned firstDataArg, Sema::FormatStringType Type,
4782                       Sema::VariadicCallType CallType, bool InFunctionCall,
4783                       llvm::SmallBitVector &CheckedVarArgs,
4784                       UncoveredArgHandler &UncoveredArg,
4785                       llvm::APSInt Offset) {
4786  tryAgain:
4787   assert(Offset.isSigned() && "invalid offset");
4788 
4789   if (E->isTypeDependent() || E->isValueDependent())
4790     return SLCT_NotALiteral;
4791 
4792   E = E->IgnoreParenCasts();
4793 
4794   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
4795     // Technically -Wformat-nonliteral does not warn about this case.
4796     // The behavior of printf and friends in this case is implementation
4797     // dependent.  Ideally if the format string cannot be null then
4798     // it should have a 'nonnull' attribute in the function prototype.
4799     return SLCT_UncheckedLiteral;
4800 
4801   switch (E->getStmtClass()) {
4802   case Stmt::BinaryConditionalOperatorClass:
4803   case Stmt::ConditionalOperatorClass: {
4804     // The expression is a literal if both sub-expressions were, and it was
4805     // completely checked only if both sub-expressions were checked.
4806     const AbstractConditionalOperator *C =
4807         cast<AbstractConditionalOperator>(E);
4808 
4809     // Determine whether it is necessary to check both sub-expressions, for
4810     // example, because the condition expression is a constant that can be
4811     // evaluated at compile time.
4812     bool CheckLeft = true, CheckRight = true;
4813 
4814     bool Cond;
4815     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
4816       if (Cond)
4817         CheckRight = false;
4818       else
4819         CheckLeft = false;
4820     }
4821 
4822     // We need to maintain the offsets for the right and the left hand side
4823     // separately to check if every possible indexed expression is a valid
4824     // string literal. They might have different offsets for different string
4825     // literals in the end.
4826     StringLiteralCheckType Left;
4827     if (!CheckLeft)
4828       Left = SLCT_UncheckedLiteral;
4829     else {
4830       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
4831                                    HasVAListArg, format_idx, firstDataArg,
4832                                    Type, CallType, InFunctionCall,
4833                                    CheckedVarArgs, UncoveredArg, Offset);
4834       if (Left == SLCT_NotALiteral || !CheckRight) {
4835         return Left;
4836       }
4837     }
4838 
4839     StringLiteralCheckType Right =
4840         checkFormatStringExpr(S, C->getFalseExpr(), Args,
4841                               HasVAListArg, format_idx, firstDataArg,
4842                               Type, CallType, InFunctionCall, CheckedVarArgs,
4843                               UncoveredArg, Offset);
4844 
4845     return (CheckLeft && Left < Right) ? Left : Right;
4846   }
4847 
4848   case Stmt::ImplicitCastExprClass: {
4849     E = cast<ImplicitCastExpr>(E)->getSubExpr();
4850     goto tryAgain;
4851   }
4852 
4853   case Stmt::OpaqueValueExprClass:
4854     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4855       E = src;
4856       goto tryAgain;
4857     }
4858     return SLCT_NotALiteral;
4859 
4860   case Stmt::PredefinedExprClass:
4861     // While __func__, etc., are technically not string literals, they
4862     // cannot contain format specifiers and thus are not a security
4863     // liability.
4864     return SLCT_UncheckedLiteral;
4865 
4866   case Stmt::DeclRefExprClass: {
4867     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
4868 
4869     // As an exception, do not flag errors for variables binding to
4870     // const string literals.
4871     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
4872       bool isConstant = false;
4873       QualType T = DR->getType();
4874 
4875       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
4876         isConstant = AT->getElementType().isConstant(S.Context);
4877       } else if (const PointerType *PT = T->getAs<PointerType>()) {
4878         isConstant = T.isConstant(S.Context) &&
4879                      PT->getPointeeType().isConstant(S.Context);
4880       } else if (T->isObjCObjectPointerType()) {
4881         // In ObjC, there is usually no "const ObjectPointer" type,
4882         // so don't check if the pointee type is constant.
4883         isConstant = T.isConstant(S.Context);
4884       }
4885 
4886       if (isConstant) {
4887         if (const Expr *Init = VD->getAnyInitializer()) {
4888           // Look through initializers like const char c[] = { "foo" }
4889           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4890             if (InitList->isStringLiteralInit())
4891               Init = InitList->getInit(0)->IgnoreParenImpCasts();
4892           }
4893           return checkFormatStringExpr(S, Init, Args,
4894                                        HasVAListArg, format_idx,
4895                                        firstDataArg, Type, CallType,
4896                                        /*InFunctionCall*/ false, CheckedVarArgs,
4897                                        UncoveredArg, Offset);
4898         }
4899       }
4900 
4901       // For vprintf* functions (i.e., HasVAListArg==true), we add a
4902       // special check to see if the format string is a function parameter
4903       // of the function calling the printf function.  If the function
4904       // has an attribute indicating it is a printf-like function, then we
4905       // should suppress warnings concerning non-literals being used in a call
4906       // to a vprintf function.  For example:
4907       //
4908       // void
4909       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
4910       //      va_list ap;
4911       //      va_start(ap, fmt);
4912       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
4913       //      ...
4914       // }
4915       if (HasVAListArg) {
4916         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4917           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4918             int PVIndex = PV->getFunctionScopeIndex() + 1;
4919             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4920               // adjust for implicit parameter
4921               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4922                 if (MD->isInstance())
4923                   ++PVIndex;
4924               // We also check if the formats are compatible.
4925               // We can't pass a 'scanf' string to a 'printf' function.
4926               if (PVIndex == PVFormat->getFormatIdx() &&
4927                   Type == S.GetFormatStringType(PVFormat))
4928                 return SLCT_UncheckedLiteral;
4929             }
4930           }
4931         }
4932       }
4933     }
4934 
4935     return SLCT_NotALiteral;
4936   }
4937 
4938   case Stmt::CallExprClass:
4939   case Stmt::CXXMemberCallExprClass: {
4940     const CallExpr *CE = cast<CallExpr>(E);
4941     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
4942       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4943         unsigned ArgIndex = FA->getFormatIdx();
4944         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
4945           if (MD->isInstance())
4946             --ArgIndex;
4947         const Expr *Arg = CE->getArg(ArgIndex - 1);
4948 
4949         return checkFormatStringExpr(S, Arg, Args,
4950                                      HasVAListArg, format_idx, firstDataArg,
4951                                      Type, CallType, InFunctionCall,
4952                                      CheckedVarArgs, UncoveredArg, Offset);
4953       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4954         unsigned BuiltinID = FD->getBuiltinID();
4955         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4956             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4957           const Expr *Arg = CE->getArg(0);
4958           return checkFormatStringExpr(S, Arg, Args,
4959                                        HasVAListArg, format_idx,
4960                                        firstDataArg, Type, CallType,
4961                                        InFunctionCall, CheckedVarArgs,
4962                                        UncoveredArg, Offset);
4963         }
4964       }
4965     }
4966 
4967     return SLCT_NotALiteral;
4968   }
4969   case Stmt::ObjCMessageExprClass: {
4970     const auto *ME = cast<ObjCMessageExpr>(E);
4971     if (const auto *ND = ME->getMethodDecl()) {
4972       if (const auto *FA = ND->getAttr<FormatArgAttr>()) {
4973         unsigned ArgIndex = FA->getFormatIdx();
4974         const Expr *Arg = ME->getArg(ArgIndex - 1);
4975         return checkFormatStringExpr(
4976             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4977             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4978       }
4979     }
4980 
4981     return SLCT_NotALiteral;
4982   }
4983   case Stmt::ObjCStringLiteralClass:
4984   case Stmt::StringLiteralClass: {
4985     const StringLiteral *StrE = nullptr;
4986 
4987     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
4988       StrE = ObjCFExpr->getString();
4989     else
4990       StrE = cast<StringLiteral>(E);
4991 
4992     if (StrE) {
4993       if (Offset.isNegative() || Offset > StrE->getLength()) {
4994         // TODO: It would be better to have an explicit warning for out of
4995         // bounds literals.
4996         return SLCT_NotALiteral;
4997       }
4998       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4999       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
5000                         firstDataArg, Type, InFunctionCall, CallType,
5001                         CheckedVarArgs, UncoveredArg);
5002       return SLCT_CheckedLiteral;
5003     }
5004 
5005     return SLCT_NotALiteral;
5006   }
5007   case Stmt::BinaryOperatorClass: {
5008     llvm::APSInt LResult;
5009     llvm::APSInt RResult;
5010 
5011     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
5012 
5013     // A string literal + an int offset is still a string literal.
5014     if (BinOp->isAdditiveOp()) {
5015       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(LResult, S.Context);
5016       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(RResult, S.Context);
5017 
5018       if (LIsInt != RIsInt) {
5019         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
5020 
5021         if (LIsInt) {
5022           if (BinOpKind == BO_Add) {
5023             sumOffsets(Offset, LResult, BinOpKind, RIsInt);
5024             E = BinOp->getRHS();
5025             goto tryAgain;
5026           }
5027         } else {
5028           sumOffsets(Offset, RResult, BinOpKind, RIsInt);
5029           E = BinOp->getLHS();
5030           goto tryAgain;
5031         }
5032       }
5033     }
5034 
5035     return SLCT_NotALiteral;
5036   }
5037   case Stmt::UnaryOperatorClass: {
5038     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
5039     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
5040     if (UnaOp->getOpcode() == clang::UO_AddrOf && ASE) {
5041       llvm::APSInt IndexResult;
5042       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context)) {
5043         sumOffsets(Offset, IndexResult, BO_Add, /*RHS is int*/ true);
5044         E = ASE->getBase();
5045         goto tryAgain;
5046       }
5047     }
5048 
5049     return SLCT_NotALiteral;
5050   }
5051 
5052   default:
5053     return SLCT_NotALiteral;
5054   }
5055 }
5056 
5057 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
5058   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
5059       .Case("scanf", FST_Scanf)
5060       .Cases("printf", "printf0", FST_Printf)
5061       .Cases("NSString", "CFString", FST_NSString)
5062       .Case("strftime", FST_Strftime)
5063       .Case("strfmon", FST_Strfmon)
5064       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
5065       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
5066       .Case("os_trace", FST_OSLog)
5067       .Case("os_log", FST_OSLog)
5068       .Default(FST_Unknown);
5069 }
5070 
5071 /// CheckFormatArguments - Check calls to printf and scanf (and similar
5072 /// functions) for correct use of format strings.
5073 /// Returns true if a format string has been fully checked.
5074 bool Sema::CheckFormatArguments(const FormatAttr *Format,
5075                                 ArrayRef<const Expr *> Args,
5076                                 bool IsCXXMember,
5077                                 VariadicCallType CallType,
5078                                 SourceLocation Loc, SourceRange Range,
5079                                 llvm::SmallBitVector &CheckedVarArgs) {
5080   FormatStringInfo FSI;
5081   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
5082     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
5083                                 FSI.FirstDataArg, GetFormatStringType(Format),
5084                                 CallType, Loc, Range, CheckedVarArgs);
5085   return false;
5086 }
5087 
5088 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
5089                                 bool HasVAListArg, unsigned format_idx,
5090                                 unsigned firstDataArg, FormatStringType Type,
5091                                 VariadicCallType CallType,
5092                                 SourceLocation Loc, SourceRange Range,
5093                                 llvm::SmallBitVector &CheckedVarArgs) {
5094   // CHECK: printf/scanf-like function is called with no format string.
5095   if (format_idx >= Args.size()) {
5096     Diag(Loc, diag::warn_missing_format_string) << Range;
5097     return false;
5098   }
5099 
5100   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
5101 
5102   // CHECK: format string is not a string literal.
5103   //
5104   // Dynamically generated format strings are difficult to
5105   // automatically vet at compile time.  Requiring that format strings
5106   // are string literals: (1) permits the checking of format strings by
5107   // the compiler and thereby (2) can practically remove the source of
5108   // many format string exploits.
5109 
5110   // Format string can be either ObjC string (e.g. @"%d") or
5111   // C string (e.g. "%d")
5112   // ObjC string uses the same format specifiers as C string, so we can use
5113   // the same format string checking logic for both ObjC and C strings.
5114   UncoveredArgHandler UncoveredArg;
5115   StringLiteralCheckType CT =
5116       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
5117                             format_idx, firstDataArg, Type, CallType,
5118                             /*IsFunctionCall*/ true, CheckedVarArgs,
5119                             UncoveredArg,
5120                             /*no string offset*/ llvm::APSInt(64, false) = 0);
5121 
5122   // Generate a diagnostic where an uncovered argument is detected.
5123   if (UncoveredArg.hasUncoveredArg()) {
5124     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
5125     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
5126     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
5127   }
5128 
5129   if (CT != SLCT_NotALiteral)
5130     // Literal format string found, check done!
5131     return CT == SLCT_CheckedLiteral;
5132 
5133   // Strftime is particular as it always uses a single 'time' argument,
5134   // so it is safe to pass a non-literal string.
5135   if (Type == FST_Strftime)
5136     return false;
5137 
5138   // Do not emit diag when the string param is a macro expansion and the
5139   // format is either NSString or CFString. This is a hack to prevent
5140   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
5141   // which are usually used in place of NS and CF string literals.
5142   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
5143   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
5144     return false;
5145 
5146   // If there are no arguments specified, warn with -Wformat-security, otherwise
5147   // warn only with -Wformat-nonliteral.
5148   if (Args.size() == firstDataArg) {
5149     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
5150       << OrigFormatExpr->getSourceRange();
5151     switch (Type) {
5152     default:
5153       break;
5154     case FST_Kprintf:
5155     case FST_FreeBSDKPrintf:
5156     case FST_Printf:
5157       Diag(FormatLoc, diag::note_format_security_fixit)
5158         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
5159       break;
5160     case FST_NSString:
5161       Diag(FormatLoc, diag::note_format_security_fixit)
5162         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
5163       break;
5164     }
5165   } else {
5166     Diag(FormatLoc, diag::warn_format_nonliteral)
5167       << OrigFormatExpr->getSourceRange();
5168   }
5169   return false;
5170 }
5171 
5172 namespace {
5173 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
5174 protected:
5175   Sema &S;
5176   const FormatStringLiteral *FExpr;
5177   const Expr *OrigFormatExpr;
5178   const Sema::FormatStringType FSType;
5179   const unsigned FirstDataArg;
5180   const unsigned NumDataArgs;
5181   const char *Beg; // Start of format string.
5182   const bool HasVAListArg;
5183   ArrayRef<const Expr *> Args;
5184   unsigned FormatIdx;
5185   llvm::SmallBitVector CoveredArgs;
5186   bool usesPositionalArgs;
5187   bool atFirstArg;
5188   bool inFunctionCall;
5189   Sema::VariadicCallType CallType;
5190   llvm::SmallBitVector &CheckedVarArgs;
5191   UncoveredArgHandler &UncoveredArg;
5192 
5193 public:
5194   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
5195                      const Expr *origFormatExpr,
5196                      const Sema::FormatStringType type, unsigned firstDataArg,
5197                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
5198                      ArrayRef<const Expr *> Args, unsigned formatIdx,
5199                      bool inFunctionCall, Sema::VariadicCallType callType,
5200                      llvm::SmallBitVector &CheckedVarArgs,
5201                      UncoveredArgHandler &UncoveredArg)
5202       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5203         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5204         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5205         usesPositionalArgs(false), atFirstArg(true),
5206         inFunctionCall(inFunctionCall), CallType(callType),
5207         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5208     CoveredArgs.resize(numDataArgs);
5209     CoveredArgs.reset();
5210   }
5211 
5212   void DoneProcessing();
5213 
5214   void HandleIncompleteSpecifier(const char *startSpecifier,
5215                                  unsigned specifierLen) override;
5216 
5217   void HandleInvalidLengthModifier(
5218                            const analyze_format_string::FormatSpecifier &FS,
5219                            const analyze_format_string::ConversionSpecifier &CS,
5220                            const char *startSpecifier, unsigned specifierLen,
5221                            unsigned DiagID);
5222 
5223   void HandleNonStandardLengthModifier(
5224                     const analyze_format_string::FormatSpecifier &FS,
5225                     const char *startSpecifier, unsigned specifierLen);
5226 
5227   void HandleNonStandardConversionSpecifier(
5228                     const analyze_format_string::ConversionSpecifier &CS,
5229                     const char *startSpecifier, unsigned specifierLen);
5230 
5231   void HandlePosition(const char *startPos, unsigned posLen) override;
5232 
5233   void HandleInvalidPosition(const char *startSpecifier,
5234                              unsigned specifierLen,
5235                              analyze_format_string::PositionContext p) override;
5236 
5237   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
5238 
5239   void HandleNullChar(const char *nullCharacter) override;
5240 
5241   template <typename Range>
5242   static void
5243   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
5244                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
5245                        bool IsStringLocation, Range StringRange,
5246                        ArrayRef<FixItHint> Fixit = None);
5247 
5248 protected:
5249   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
5250                                         const char *startSpec,
5251                                         unsigned specifierLen,
5252                                         const char *csStart, unsigned csLen);
5253 
5254   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
5255                                          const char *startSpec,
5256                                          unsigned specifierLen);
5257 
5258   SourceRange getFormatStringRange();
5259   CharSourceRange getSpecifierRange(const char *startSpecifier,
5260                                     unsigned specifierLen);
5261   SourceLocation getLocationOfByte(const char *x);
5262 
5263   const Expr *getDataArg(unsigned i) const;
5264 
5265   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
5266                     const analyze_format_string::ConversionSpecifier &CS,
5267                     const char *startSpecifier, unsigned specifierLen,
5268                     unsigned argIndex);
5269 
5270   template <typename Range>
5271   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5272                             bool IsStringLocation, Range StringRange,
5273                             ArrayRef<FixItHint> Fixit = None);
5274 };
5275 } // end anonymous namespace
5276 
5277 SourceRange CheckFormatHandler::getFormatStringRange() {
5278   return OrigFormatExpr->getSourceRange();
5279 }
5280 
5281 CharSourceRange CheckFormatHandler::
5282 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
5283   SourceLocation Start = getLocationOfByte(startSpecifier);
5284   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
5285 
5286   // Advance the end SourceLocation by one due to half-open ranges.
5287   End = End.getLocWithOffset(1);
5288 
5289   return CharSourceRange::getCharRange(Start, End);
5290 }
5291 
5292 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
5293   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
5294                                   S.getLangOpts(), S.Context.getTargetInfo());
5295 }
5296 
5297 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
5298                                                    unsigned specifierLen){
5299   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
5300                        getLocationOfByte(startSpecifier),
5301                        /*IsStringLocation*/true,
5302                        getSpecifierRange(startSpecifier, specifierLen));
5303 }
5304 
5305 void CheckFormatHandler::HandleInvalidLengthModifier(
5306     const analyze_format_string::FormatSpecifier &FS,
5307     const analyze_format_string::ConversionSpecifier &CS,
5308     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
5309   using namespace analyze_format_string;
5310 
5311   const LengthModifier &LM = FS.getLengthModifier();
5312   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5313 
5314   // See if we know how to fix this length modifier.
5315   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5316   if (FixedLM) {
5317     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5318                          getLocationOfByte(LM.getStart()),
5319                          /*IsStringLocation*/true,
5320                          getSpecifierRange(startSpecifier, specifierLen));
5321 
5322     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5323       << FixedLM->toString()
5324       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5325 
5326   } else {
5327     FixItHint Hint;
5328     if (DiagID == diag::warn_format_nonsensical_length)
5329       Hint = FixItHint::CreateRemoval(LMRange);
5330 
5331     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
5332                          getLocationOfByte(LM.getStart()),
5333                          /*IsStringLocation*/true,
5334                          getSpecifierRange(startSpecifier, specifierLen),
5335                          Hint);
5336   }
5337 }
5338 
5339 void CheckFormatHandler::HandleNonStandardLengthModifier(
5340     const analyze_format_string::FormatSpecifier &FS,
5341     const char *startSpecifier, unsigned specifierLen) {
5342   using namespace analyze_format_string;
5343 
5344   const LengthModifier &LM = FS.getLengthModifier();
5345   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5346 
5347   // See if we know how to fix this length modifier.
5348   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
5349   if (FixedLM) {
5350     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5351                            << LM.toString() << 0,
5352                          getLocationOfByte(LM.getStart()),
5353                          /*IsStringLocation*/true,
5354                          getSpecifierRange(startSpecifier, specifierLen));
5355 
5356     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5357       << FixedLM->toString()
5358       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
5359 
5360   } else {
5361     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5362                            << LM.toString() << 0,
5363                          getLocationOfByte(LM.getStart()),
5364                          /*IsStringLocation*/true,
5365                          getSpecifierRange(startSpecifier, specifierLen));
5366   }
5367 }
5368 
5369 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5370     const analyze_format_string::ConversionSpecifier &CS,
5371     const char *startSpecifier, unsigned specifierLen) {
5372   using namespace analyze_format_string;
5373 
5374   // See if we know how to fix this conversion specifier.
5375   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
5376   if (FixedCS) {
5377     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5378                           << CS.toString() << /*conversion specifier*/1,
5379                          getLocationOfByte(CS.getStart()),
5380                          /*IsStringLocation*/true,
5381                          getSpecifierRange(startSpecifier, specifierLen));
5382 
5383     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
5384     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
5385       << FixedCS->toString()
5386       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
5387   } else {
5388     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
5389                           << CS.toString() << /*conversion specifier*/1,
5390                          getLocationOfByte(CS.getStart()),
5391                          /*IsStringLocation*/true,
5392                          getSpecifierRange(startSpecifier, specifierLen));
5393   }
5394 }
5395 
5396 void CheckFormatHandler::HandlePosition(const char *startPos,
5397                                         unsigned posLen) {
5398   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
5399                                getLocationOfByte(startPos),
5400                                /*IsStringLocation*/true,
5401                                getSpecifierRange(startPos, posLen));
5402 }
5403 
5404 void
5405 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
5406                                      analyze_format_string::PositionContext p) {
5407   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
5408                          << (unsigned) p,
5409                        getLocationOfByte(startPos), /*IsStringLocation*/true,
5410                        getSpecifierRange(startPos, posLen));
5411 }
5412 
5413 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
5414                                             unsigned posLen) {
5415   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
5416                                getLocationOfByte(startPos),
5417                                /*IsStringLocation*/true,
5418                                getSpecifierRange(startPos, posLen));
5419 }
5420 
5421 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
5422   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5423     // The presence of a null character is likely an error.
5424     EmitFormatDiagnostic(
5425       S.PDiag(diag::warn_printf_format_string_contains_null_char),
5426       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
5427       getFormatStringRange());
5428   }
5429 }
5430 
5431 // Note that this may return NULL if there was an error parsing or building
5432 // one of the argument expressions.
5433 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
5434   return Args[FirstDataArg + i];
5435 }
5436 
5437 void CheckFormatHandler::DoneProcessing() {
5438   // Does the number of data arguments exceed the number of
5439   // format conversions in the format string?
5440   if (!HasVAListArg) {
5441       // Find any arguments that weren't covered.
5442     CoveredArgs.flip();
5443     signed notCoveredArg = CoveredArgs.find_first();
5444     if (notCoveredArg >= 0) {
5445       assert((unsigned)notCoveredArg < NumDataArgs);
5446       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5447     } else {
5448       UncoveredArg.setAllCovered();
5449     }
5450   }
5451 }
5452 
5453 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
5454                                    const Expr *ArgExpr) {
5455   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5456          "Invalid state");
5457 
5458   if (!ArgExpr)
5459     return;
5460 
5461   SourceLocation Loc = ArgExpr->getLocStart();
5462 
5463   if (S.getSourceManager().isInSystemMacro(Loc))
5464     return;
5465 
5466   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
5467   for (auto E : DiagnosticExprs)
5468     PDiag << E->getSourceRange();
5469 
5470   CheckFormatHandler::EmitFormatDiagnostic(
5471                                   S, IsFunctionCall, DiagnosticExprs[0],
5472                                   PDiag, Loc, /*IsStringLocation*/false,
5473                                   DiagnosticExprs[0]->getSourceRange());
5474 }
5475 
5476 bool
5477 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
5478                                                      SourceLocation Loc,
5479                                                      const char *startSpec,
5480                                                      unsigned specifierLen,
5481                                                      const char *csStart,
5482                                                      unsigned csLen) {
5483   bool keepGoing = true;
5484   if (argIndex < NumDataArgs) {
5485     // Consider the argument coverered, even though the specifier doesn't
5486     // make sense.
5487     CoveredArgs.set(argIndex);
5488   }
5489   else {
5490     // If argIndex exceeds the number of data arguments we
5491     // don't issue a warning because that is just a cascade of warnings (and
5492     // they may have intended '%%' anyway). We don't want to continue processing
5493     // the format string after this point, however, as we will like just get
5494     // gibberish when trying to match arguments.
5495     keepGoing = false;
5496   }
5497 
5498   StringRef Specifier(csStart, csLen);
5499 
5500   // If the specifier in non-printable, it could be the first byte of a UTF-8
5501   // sequence. In that case, print the UTF-8 code point. If not, print the byte
5502   // hex value.
5503   std::string CodePointStr;
5504   if (!llvm::sys::locale::isPrint(*csStart)) {
5505     llvm::UTF32 CodePoint;
5506     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
5507     const llvm::UTF8 *E =
5508         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
5509     llvm::ConversionResult Result =
5510         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5511 
5512     if (Result != llvm::conversionOK) {
5513       unsigned char FirstChar = *csStart;
5514       CodePoint = (llvm::UTF32)FirstChar;
5515     }
5516 
5517     llvm::raw_string_ostream OS(CodePointStr);
5518     if (CodePoint < 256)
5519       OS << "\\x" << llvm::format("%02x", CodePoint);
5520     else if (CodePoint <= 0xFFFF)
5521       OS << "\\u" << llvm::format("%04x", CodePoint);
5522     else
5523       OS << "\\U" << llvm::format("%08x", CodePoint);
5524     OS.flush();
5525     Specifier = CodePointStr;
5526   }
5527 
5528   EmitFormatDiagnostic(
5529       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
5530       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
5531 
5532   return keepGoing;
5533 }
5534 
5535 void
5536 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
5537                                                       const char *startSpec,
5538                                                       unsigned specifierLen) {
5539   EmitFormatDiagnostic(
5540     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
5541     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
5542 }
5543 
5544 bool
5545 CheckFormatHandler::CheckNumArgs(
5546   const analyze_format_string::FormatSpecifier &FS,
5547   const analyze_format_string::ConversionSpecifier &CS,
5548   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
5549 
5550   if (argIndex >= NumDataArgs) {
5551     PartialDiagnostic PDiag = FS.usesPositionalArg()
5552       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5553            << (argIndex+1) << NumDataArgs)
5554       : S.PDiag(diag::warn_printf_insufficient_data_args);
5555     EmitFormatDiagnostic(
5556       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
5557       getSpecifierRange(startSpecifier, specifierLen));
5558 
5559     // Since more arguments than conversion tokens are given, by extension
5560     // all arguments are covered, so mark this as so.
5561     UncoveredArg.setAllCovered();
5562     return false;
5563   }
5564   return true;
5565 }
5566 
5567 template<typename Range>
5568 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
5569                                               SourceLocation Loc,
5570                                               bool IsStringLocation,
5571                                               Range StringRange,
5572                                               ArrayRef<FixItHint> FixIt) {
5573   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5574                        Loc, IsStringLocation, StringRange, FixIt);
5575 }
5576 
5577 /// \brief If the format string is not within the funcion call, emit a note
5578 /// so that the function call and string are in diagnostic messages.
5579 ///
5580 /// \param InFunctionCall if true, the format string is within the function
5581 /// call and only one diagnostic message will be produced.  Otherwise, an
5582 /// extra note will be emitted pointing to location of the format string.
5583 ///
5584 /// \param ArgumentExpr the expression that is passed as the format string
5585 /// argument in the function call.  Used for getting locations when two
5586 /// diagnostics are emitted.
5587 ///
5588 /// \param PDiag the callee should already have provided any strings for the
5589 /// diagnostic message.  This function only adds locations and fixits
5590 /// to diagnostics.
5591 ///
5592 /// \param Loc primary location for diagnostic.  If two diagnostics are
5593 /// required, one will be at Loc and a new SourceLocation will be created for
5594 /// the other one.
5595 ///
5596 /// \param IsStringLocation if true, Loc points to the format string should be
5597 /// used for the note.  Otherwise, Loc points to the argument list and will
5598 /// be used with PDiag.
5599 ///
5600 /// \param StringRange some or all of the string to highlight.  This is
5601 /// templated so it can accept either a CharSourceRange or a SourceRange.
5602 ///
5603 /// \param FixIt optional fix it hint for the format string.
5604 template <typename Range>
5605 void CheckFormatHandler::EmitFormatDiagnostic(
5606     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
5607     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
5608     Range StringRange, ArrayRef<FixItHint> FixIt) {
5609   if (InFunctionCall) {
5610     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
5611     D << StringRange;
5612     D << FixIt;
5613   } else {
5614     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
5615       << ArgumentExpr->getSourceRange();
5616 
5617     const Sema::SemaDiagnosticBuilder &Note =
5618       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5619              diag::note_format_string_defined);
5620 
5621     Note << StringRange;
5622     Note << FixIt;
5623   }
5624 }
5625 
5626 //===--- CHECK: Printf format string checking ------------------------------===//
5627 
5628 namespace {
5629 class CheckPrintfHandler : public CheckFormatHandler {
5630 public:
5631   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
5632                      const Expr *origFormatExpr,
5633                      const Sema::FormatStringType type, unsigned firstDataArg,
5634                      unsigned numDataArgs, bool isObjC, const char *beg,
5635                      bool hasVAListArg, ArrayRef<const Expr *> Args,
5636                      unsigned formatIdx, bool inFunctionCall,
5637                      Sema::VariadicCallType CallType,
5638                      llvm::SmallBitVector &CheckedVarArgs,
5639                      UncoveredArgHandler &UncoveredArg)
5640       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5641                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
5642                            inFunctionCall, CallType, CheckedVarArgs,
5643                            UncoveredArg) {}
5644 
5645   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
5646 
5647   /// Returns true if '%@' specifiers are allowed in the format string.
5648   bool allowsObjCArg() const {
5649     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
5650            FSType == Sema::FST_OSTrace;
5651   }
5652 
5653   bool HandleInvalidPrintfConversionSpecifier(
5654                                       const analyze_printf::PrintfSpecifier &FS,
5655                                       const char *startSpecifier,
5656                                       unsigned specifierLen) override;
5657 
5658   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
5659                              const char *startSpecifier,
5660                              unsigned specifierLen) override;
5661   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
5662                        const char *StartSpecifier,
5663                        unsigned SpecifierLen,
5664                        const Expr *E);
5665 
5666   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
5667                     const char *startSpecifier, unsigned specifierLen);
5668   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
5669                            const analyze_printf::OptionalAmount &Amt,
5670                            unsigned type,
5671                            const char *startSpecifier, unsigned specifierLen);
5672   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5673                   const analyze_printf::OptionalFlag &flag,
5674                   const char *startSpecifier, unsigned specifierLen);
5675   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
5676                          const analyze_printf::OptionalFlag &ignoredFlag,
5677                          const analyze_printf::OptionalFlag &flag,
5678                          const char *startSpecifier, unsigned specifierLen);
5679   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
5680                            const Expr *E);
5681 
5682   void HandleEmptyObjCModifierFlag(const char *startFlag,
5683                                    unsigned flagLen) override;
5684 
5685   void HandleInvalidObjCModifierFlag(const char *startFlag,
5686                                             unsigned flagLen) override;
5687 
5688   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
5689                                            const char *flagsEnd,
5690                                            const char *conversionPosition)
5691                                              override;
5692 };
5693 } // end anonymous namespace
5694 
5695 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5696                                       const analyze_printf::PrintfSpecifier &FS,
5697                                       const char *startSpecifier,
5698                                       unsigned specifierLen) {
5699   const analyze_printf::PrintfConversionSpecifier &CS =
5700     FS.getConversionSpecifier();
5701 
5702   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
5703                                           getLocationOfByte(CS.getStart()),
5704                                           startSpecifier, specifierLen,
5705                                           CS.getStart(), CS.getLength());
5706 }
5707 
5708 bool CheckPrintfHandler::HandleAmount(
5709                                const analyze_format_string::OptionalAmount &Amt,
5710                                unsigned k, const char *startSpecifier,
5711                                unsigned specifierLen) {
5712   if (Amt.hasDataArgument()) {
5713     if (!HasVAListArg) {
5714       unsigned argIndex = Amt.getArgIndex();
5715       if (argIndex >= NumDataArgs) {
5716         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
5717                                << k,
5718                              getLocationOfByte(Amt.getStart()),
5719                              /*IsStringLocation*/true,
5720                              getSpecifierRange(startSpecifier, specifierLen));
5721         // Don't do any more checking.  We will just emit
5722         // spurious errors.
5723         return false;
5724       }
5725 
5726       // Type check the data argument.  It should be an 'int'.
5727       // Although not in conformance with C99, we also allow the argument to be
5728       // an 'unsigned int' as that is a reasonably safe case.  GCC also
5729       // doesn't emit a warning for that case.
5730       CoveredArgs.set(argIndex);
5731       const Expr *Arg = getDataArg(argIndex);
5732       if (!Arg)
5733         return false;
5734 
5735       QualType T = Arg->getType();
5736 
5737       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
5738       assert(AT.isValid());
5739 
5740       if (!AT.matchesType(S.Context, T)) {
5741         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
5742                                << k << AT.getRepresentativeTypeName(S.Context)
5743                                << T << Arg->getSourceRange(),
5744                              getLocationOfByte(Amt.getStart()),
5745                              /*IsStringLocation*/true,
5746                              getSpecifierRange(startSpecifier, specifierLen));
5747         // Don't do any more checking.  We will just emit
5748         // spurious errors.
5749         return false;
5750       }
5751     }
5752   }
5753   return true;
5754 }
5755 
5756 void CheckPrintfHandler::HandleInvalidAmount(
5757                                       const analyze_printf::PrintfSpecifier &FS,
5758                                       const analyze_printf::OptionalAmount &Amt,
5759                                       unsigned type,
5760                                       const char *startSpecifier,
5761                                       unsigned specifierLen) {
5762   const analyze_printf::PrintfConversionSpecifier &CS =
5763     FS.getConversionSpecifier();
5764 
5765   FixItHint fixit =
5766     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5767       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
5768                                  Amt.getConstantLength()))
5769       : FixItHint();
5770 
5771   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
5772                          << type << CS.toString(),
5773                        getLocationOfByte(Amt.getStart()),
5774                        /*IsStringLocation*/true,
5775                        getSpecifierRange(startSpecifier, specifierLen),
5776                        fixit);
5777 }
5778 
5779 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
5780                                     const analyze_printf::OptionalFlag &flag,
5781                                     const char *startSpecifier,
5782                                     unsigned specifierLen) {
5783   // Warn about pointless flag with a fixit removal.
5784   const analyze_printf::PrintfConversionSpecifier &CS =
5785     FS.getConversionSpecifier();
5786   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
5787                          << flag.toString() << CS.toString(),
5788                        getLocationOfByte(flag.getPosition()),
5789                        /*IsStringLocation*/true,
5790                        getSpecifierRange(startSpecifier, specifierLen),
5791                        FixItHint::CreateRemoval(
5792                          getSpecifierRange(flag.getPosition(), 1)));
5793 }
5794 
5795 void CheckPrintfHandler::HandleIgnoredFlag(
5796                                 const analyze_printf::PrintfSpecifier &FS,
5797                                 const analyze_printf::OptionalFlag &ignoredFlag,
5798                                 const analyze_printf::OptionalFlag &flag,
5799                                 const char *startSpecifier,
5800                                 unsigned specifierLen) {
5801   // Warn about ignored flag with a fixit removal.
5802   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
5803                          << ignoredFlag.toString() << flag.toString(),
5804                        getLocationOfByte(ignoredFlag.getPosition()),
5805                        /*IsStringLocation*/true,
5806                        getSpecifierRange(startSpecifier, specifierLen),
5807                        FixItHint::CreateRemoval(
5808                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
5809 }
5810 
5811 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
5812 //                            bool IsStringLocation, Range StringRange,
5813 //                            ArrayRef<FixItHint> Fixit = None);
5814 
5815 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
5816                                                      unsigned flagLen) {
5817   // Warn about an empty flag.
5818   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
5819                        getLocationOfByte(startFlag),
5820                        /*IsStringLocation*/true,
5821                        getSpecifierRange(startFlag, flagLen));
5822 }
5823 
5824 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
5825                                                        unsigned flagLen) {
5826   // Warn about an invalid flag.
5827   auto Range = getSpecifierRange(startFlag, flagLen);
5828   StringRef flag(startFlag, flagLen);
5829   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5830                       getLocationOfByte(startFlag),
5831                       /*IsStringLocation*/true,
5832                       Range, FixItHint::CreateRemoval(Range));
5833 }
5834 
5835 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5836     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
5837     // Warn about using '[...]' without a '@' conversion.
5838     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5839     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5840     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
5841                          getLocationOfByte(conversionPosition),
5842                          /*IsStringLocation*/true,
5843                          Range, FixItHint::CreateRemoval(Range));
5844 }
5845 
5846 // Determines if the specified is a C++ class or struct containing
5847 // a member with the specified name and kind (e.g. a CXXMethodDecl named
5848 // "c_str()").
5849 template<typename MemberKind>
5850 static llvm::SmallPtrSet<MemberKind*, 1>
5851 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
5852   const RecordType *RT = Ty->getAs<RecordType>();
5853   llvm::SmallPtrSet<MemberKind*, 1> Results;
5854 
5855   if (!RT)
5856     return Results;
5857   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
5858   if (!RD || !RD->getDefinition())
5859     return Results;
5860 
5861   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
5862                  Sema::LookupMemberName);
5863   R.suppressDiagnostics();
5864 
5865   // We just need to include all members of the right kind turned up by the
5866   // filter, at this point.
5867   if (S.LookupQualifiedName(R, RT->getDecl()))
5868     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
5869       NamedDecl *decl = (*I)->getUnderlyingDecl();
5870       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5871         Results.insert(FK);
5872     }
5873   return Results;
5874 }
5875 
5876 /// Check if we could call '.c_str()' on an object.
5877 ///
5878 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
5879 /// allow the call, or if it would be ambiguous).
5880 bool Sema::hasCStrMethod(const Expr *E) {
5881   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5882   MethodSet Results =
5883       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
5884   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5885        MI != ME; ++MI)
5886     if ((*MI)->getMinRequiredArguments() == 0)
5887       return true;
5888   return false;
5889 }
5890 
5891 // Check if a (w)string was passed when a (w)char* was needed, and offer a
5892 // better diagnostic if so. AT is assumed to be valid.
5893 // Returns true when a c_str() conversion method is found.
5894 bool CheckPrintfHandler::checkForCStrMembers(
5895     const analyze_printf::ArgType &AT, const Expr *E) {
5896   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5897 
5898   MethodSet Results =
5899       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
5900 
5901   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5902        MI != ME; ++MI) {
5903     const CXXMethodDecl *Method = *MI;
5904     if (Method->getMinRequiredArguments() == 0 &&
5905         AT.matchesType(S.Context, Method->getReturnType())) {
5906       // FIXME: Suggest parens if the expression needs them.
5907       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
5908       S.Diag(E->getLocStart(), diag::note_printf_c_str)
5909           << "c_str()"
5910           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
5911       return true;
5912     }
5913   }
5914 
5915   return false;
5916 }
5917 
5918 bool
5919 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
5920                                             &FS,
5921                                           const char *startSpecifier,
5922                                           unsigned specifierLen) {
5923   using namespace analyze_format_string;
5924   using namespace analyze_printf;
5925   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
5926 
5927   if (FS.consumesDataArgument()) {
5928     if (atFirstArg) {
5929         atFirstArg = false;
5930         usesPositionalArgs = FS.usesPositionalArg();
5931     }
5932     else if (usesPositionalArgs != FS.usesPositionalArg()) {
5933       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
5934                                         startSpecifier, specifierLen);
5935       return false;
5936     }
5937   }
5938 
5939   // First check if the field width, precision, and conversion specifier
5940   // have matching data arguments.
5941   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
5942                     startSpecifier, specifierLen)) {
5943     return false;
5944   }
5945 
5946   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
5947                     startSpecifier, specifierLen)) {
5948     return false;
5949   }
5950 
5951   if (!CS.consumesDataArgument()) {
5952     // FIXME: Technically specifying a precision or field width here
5953     // makes no sense.  Worth issuing a warning at some point.
5954     return true;
5955   }
5956 
5957   // Consume the argument.
5958   unsigned argIndex = FS.getArgIndex();
5959   if (argIndex < NumDataArgs) {
5960     // The check to see if the argIndex is valid will come later.
5961     // We set the bit here because we may exit early from this
5962     // function if we encounter some other error.
5963     CoveredArgs.set(argIndex);
5964   }
5965 
5966   // FreeBSD kernel extensions.
5967   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
5968       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
5969     // We need at least two arguments.
5970     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5971       return false;
5972 
5973     // Claim the second argument.
5974     CoveredArgs.set(argIndex + 1);
5975 
5976     // Type check the first argument (int for %b, pointer for %D)
5977     const Expr *Ex = getDataArg(argIndex);
5978     const analyze_printf::ArgType &AT =
5979       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
5980         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5981     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
5982       EmitFormatDiagnostic(
5983         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5984         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
5985         << false << Ex->getSourceRange(),
5986         Ex->getLocStart(), /*IsStringLocation*/false,
5987         getSpecifierRange(startSpecifier, specifierLen));
5988 
5989     // Type check the second argument (char * for both %b and %D)
5990     Ex = getDataArg(argIndex + 1);
5991     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5992     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5993       EmitFormatDiagnostic(
5994         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5995         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5996         << false << Ex->getSourceRange(),
5997         Ex->getLocStart(), /*IsStringLocation*/false,
5998         getSpecifierRange(startSpecifier, specifierLen));
5999 
6000      return true;
6001   }
6002 
6003   // Check for using an Objective-C specific conversion specifier
6004   // in a non-ObjC literal.
6005   if (!allowsObjCArg() && CS.isObjCArg()) {
6006     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6007                                                   specifierLen);
6008   }
6009 
6010   // %P can only be used with os_log.
6011   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
6012     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6013                                                   specifierLen);
6014   }
6015 
6016   // %n is not allowed with os_log.
6017   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
6018     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
6019                          getLocationOfByte(CS.getStart()),
6020                          /*IsStringLocation*/ false,
6021                          getSpecifierRange(startSpecifier, specifierLen));
6022 
6023     return true;
6024   }
6025 
6026   // Only scalars are allowed for os_trace.
6027   if (FSType == Sema::FST_OSTrace &&
6028       (CS.getKind() == ConversionSpecifier::PArg ||
6029        CS.getKind() == ConversionSpecifier::sArg ||
6030        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
6031     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
6032                                                   specifierLen);
6033   }
6034 
6035   // Check for use of public/private annotation outside of os_log().
6036   if (FSType != Sema::FST_OSLog) {
6037     if (FS.isPublic().isSet()) {
6038       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6039                                << "public",
6040                            getLocationOfByte(FS.isPublic().getPosition()),
6041                            /*IsStringLocation*/ false,
6042                            getSpecifierRange(startSpecifier, specifierLen));
6043     }
6044     if (FS.isPrivate().isSet()) {
6045       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
6046                                << "private",
6047                            getLocationOfByte(FS.isPrivate().getPosition()),
6048                            /*IsStringLocation*/ false,
6049                            getSpecifierRange(startSpecifier, specifierLen));
6050     }
6051   }
6052 
6053   // Check for invalid use of field width
6054   if (!FS.hasValidFieldWidth()) {
6055     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
6056         startSpecifier, specifierLen);
6057   }
6058 
6059   // Check for invalid use of precision
6060   if (!FS.hasValidPrecision()) {
6061     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
6062         startSpecifier, specifierLen);
6063   }
6064 
6065   // Precision is mandatory for %P specifier.
6066   if (CS.getKind() == ConversionSpecifier::PArg &&
6067       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
6068     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
6069                          getLocationOfByte(startSpecifier),
6070                          /*IsStringLocation*/ false,
6071                          getSpecifierRange(startSpecifier, specifierLen));
6072   }
6073 
6074   // Check each flag does not conflict with any other component.
6075   if (!FS.hasValidThousandsGroupingPrefix())
6076     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
6077   if (!FS.hasValidLeadingZeros())
6078     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
6079   if (!FS.hasValidPlusPrefix())
6080     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
6081   if (!FS.hasValidSpacePrefix())
6082     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
6083   if (!FS.hasValidAlternativeForm())
6084     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
6085   if (!FS.hasValidLeftJustified())
6086     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
6087 
6088   // Check that flags are not ignored by another flag
6089   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
6090     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
6091         startSpecifier, specifierLen);
6092   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
6093     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
6094             startSpecifier, specifierLen);
6095 
6096   // Check the length modifier is valid with the given conversion specifier.
6097   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6098     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6099                                 diag::warn_format_nonsensical_length);
6100   else if (!FS.hasStandardLengthModifier())
6101     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6102   else if (!FS.hasStandardLengthConversionCombination())
6103     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6104                                 diag::warn_format_non_standard_conversion_spec);
6105 
6106   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6107     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6108 
6109   // The remaining checks depend on the data arguments.
6110   if (HasVAListArg)
6111     return true;
6112 
6113   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6114     return false;
6115 
6116   const Expr *Arg = getDataArg(argIndex);
6117   if (!Arg)
6118     return true;
6119 
6120   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
6121 }
6122 
6123 static bool requiresParensToAddCast(const Expr *E) {
6124   // FIXME: We should have a general way to reason about operator
6125   // precedence and whether parens are actually needed here.
6126   // Take care of a few common cases where they aren't.
6127   const Expr *Inside = E->IgnoreImpCasts();
6128   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
6129     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
6130 
6131   switch (Inside->getStmtClass()) {
6132   case Stmt::ArraySubscriptExprClass:
6133   case Stmt::CallExprClass:
6134   case Stmt::CharacterLiteralClass:
6135   case Stmt::CXXBoolLiteralExprClass:
6136   case Stmt::DeclRefExprClass:
6137   case Stmt::FloatingLiteralClass:
6138   case Stmt::IntegerLiteralClass:
6139   case Stmt::MemberExprClass:
6140   case Stmt::ObjCArrayLiteralClass:
6141   case Stmt::ObjCBoolLiteralExprClass:
6142   case Stmt::ObjCBoxedExprClass:
6143   case Stmt::ObjCDictionaryLiteralClass:
6144   case Stmt::ObjCEncodeExprClass:
6145   case Stmt::ObjCIvarRefExprClass:
6146   case Stmt::ObjCMessageExprClass:
6147   case Stmt::ObjCPropertyRefExprClass:
6148   case Stmt::ObjCStringLiteralClass:
6149   case Stmt::ObjCSubscriptRefExprClass:
6150   case Stmt::ParenExprClass:
6151   case Stmt::StringLiteralClass:
6152   case Stmt::UnaryOperatorClass:
6153     return false;
6154   default:
6155     return true;
6156   }
6157 }
6158 
6159 static std::pair<QualType, StringRef>
6160 shouldNotPrintDirectly(const ASTContext &Context,
6161                        QualType IntendedTy,
6162                        const Expr *E) {
6163   // Use a 'while' to peel off layers of typedefs.
6164   QualType TyTy = IntendedTy;
6165   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
6166     StringRef Name = UserTy->getDecl()->getName();
6167     QualType CastTy = llvm::StringSwitch<QualType>(Name)
6168       .Case("CFIndex", Context.LongTy)
6169       .Case("NSInteger", Context.LongTy)
6170       .Case("NSUInteger", Context.UnsignedLongTy)
6171       .Case("SInt32", Context.IntTy)
6172       .Case("UInt32", Context.UnsignedIntTy)
6173       .Default(QualType());
6174 
6175     if (!CastTy.isNull())
6176       return std::make_pair(CastTy, Name);
6177 
6178     TyTy = UserTy->desugar();
6179   }
6180 
6181   // Strip parens if necessary.
6182   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6183     return shouldNotPrintDirectly(Context,
6184                                   PE->getSubExpr()->getType(),
6185                                   PE->getSubExpr());
6186 
6187   // If this is a conditional expression, then its result type is constructed
6188   // via usual arithmetic conversions and thus there might be no necessary
6189   // typedef sugar there.  Recurse to operands to check for NSInteger &
6190   // Co. usage condition.
6191   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
6192     QualType TrueTy, FalseTy;
6193     StringRef TrueName, FalseName;
6194 
6195     std::tie(TrueTy, TrueName) =
6196       shouldNotPrintDirectly(Context,
6197                              CO->getTrueExpr()->getType(),
6198                              CO->getTrueExpr());
6199     std::tie(FalseTy, FalseName) =
6200       shouldNotPrintDirectly(Context,
6201                              CO->getFalseExpr()->getType(),
6202                              CO->getFalseExpr());
6203 
6204     if (TrueTy == FalseTy)
6205       return std::make_pair(TrueTy, TrueName);
6206     else if (TrueTy.isNull())
6207       return std::make_pair(FalseTy, FalseName);
6208     else if (FalseTy.isNull())
6209       return std::make_pair(TrueTy, TrueName);
6210   }
6211 
6212   return std::make_pair(QualType(), StringRef());
6213 }
6214 
6215 bool
6216 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
6217                                     const char *StartSpecifier,
6218                                     unsigned SpecifierLen,
6219                                     const Expr *E) {
6220   using namespace analyze_format_string;
6221   using namespace analyze_printf;
6222   // Now type check the data expression that matches the
6223   // format specifier.
6224   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
6225   if (!AT.isValid())
6226     return true;
6227 
6228   QualType ExprTy = E->getType();
6229   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6230     ExprTy = TET->getUnderlyingExpr()->getType();
6231   }
6232 
6233   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
6234 
6235   if (match == analyze_printf::ArgType::Match) {
6236     return true;
6237   }
6238 
6239   // Look through argument promotions for our error message's reported type.
6240   // This includes the integral and floating promotions, but excludes array
6241   // and function pointer decay; seeing that an argument intended to be a
6242   // string has type 'char [6]' is probably more confusing than 'char *'.
6243   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6244     if (ICE->getCastKind() == CK_IntegralCast ||
6245         ICE->getCastKind() == CK_FloatingCast) {
6246       E = ICE->getSubExpr();
6247       ExprTy = E->getType();
6248 
6249       // Check if we didn't match because of an implicit cast from a 'char'
6250       // or 'short' to an 'int'.  This is done because printf is a varargs
6251       // function.
6252       if (ICE->getType() == S.Context.IntTy ||
6253           ICE->getType() == S.Context.UnsignedIntTy) {
6254         // All further checking is done on the subexpression.
6255         if (AT.matchesType(S.Context, ExprTy))
6256           return true;
6257       }
6258     }
6259   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
6260     // Special case for 'a', which has type 'int' in C.
6261     // Note, however, that we do /not/ want to treat multibyte constants like
6262     // 'MooV' as characters! This form is deprecated but still exists.
6263     if (ExprTy == S.Context.IntTy)
6264       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6265         ExprTy = S.Context.CharTy;
6266   }
6267 
6268   // Look through enums to their underlying type.
6269   bool IsEnum = false;
6270   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
6271     ExprTy = EnumTy->getDecl()->getIntegerType();
6272     IsEnum = true;
6273   }
6274 
6275   // %C in an Objective-C context prints a unichar, not a wchar_t.
6276   // If the argument is an integer of some kind, believe the %C and suggest
6277   // a cast instead of changing the conversion specifier.
6278   QualType IntendedTy = ExprTy;
6279   if (isObjCContext() &&
6280       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
6281     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6282         !ExprTy->isCharType()) {
6283       // 'unichar' is defined as a typedef of unsigned short, but we should
6284       // prefer using the typedef if it is visible.
6285       IntendedTy = S.Context.UnsignedShortTy;
6286 
6287       // While we are here, check if the value is an IntegerLiteral that happens
6288       // to be within the valid range.
6289       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
6290         const llvm::APInt &V = IL->getValue();
6291         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6292           return true;
6293       }
6294 
6295       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
6296                           Sema::LookupOrdinaryName);
6297       if (S.LookupName(Result, S.getCurScope())) {
6298         NamedDecl *ND = Result.getFoundDecl();
6299         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
6300           if (TD->getUnderlyingType() == IntendedTy)
6301             IntendedTy = S.Context.getTypedefType(TD);
6302       }
6303     }
6304   }
6305 
6306   // Special-case some of Darwin's platform-independence types by suggesting
6307   // casts to primitive types that are known to be large enough.
6308   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
6309   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6310     QualType CastTy;
6311     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
6312     if (!CastTy.isNull()) {
6313       IntendedTy = CastTy;
6314       ShouldNotPrintDirectly = true;
6315     }
6316   }
6317 
6318   // We may be able to offer a FixItHint if it is a supported type.
6319   PrintfSpecifier fixedFS = FS;
6320   bool success =
6321       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6322 
6323   if (success) {
6324     // Get the fix string from the fixed format specifier
6325     SmallString<16> buf;
6326     llvm::raw_svector_ostream os(buf);
6327     fixedFS.toString(os);
6328 
6329     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6330 
6331     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6332       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6333       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6334         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6335       }
6336       // In this case, the specifier is wrong and should be changed to match
6337       // the argument.
6338       EmitFormatDiagnostic(S.PDiag(diag)
6339                                << AT.getRepresentativeTypeName(S.Context)
6340                                << IntendedTy << IsEnum << E->getSourceRange(),
6341                            E->getLocStart(),
6342                            /*IsStringLocation*/ false, SpecRange,
6343                            FixItHint::CreateReplacement(SpecRange, os.str()));
6344     } else {
6345       // The canonical type for formatting this value is different from the
6346       // actual type of the expression. (This occurs, for example, with Darwin's
6347       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
6348       // should be printed as 'long' for 64-bit compatibility.)
6349       // Rather than emitting a normal format/argument mismatch, we want to
6350       // add a cast to the recommended type (and correct the format string
6351       // if necessary).
6352       SmallString<16> CastBuf;
6353       llvm::raw_svector_ostream CastFix(CastBuf);
6354       CastFix << "(";
6355       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6356       CastFix << ")";
6357 
6358       SmallVector<FixItHint,4> Hints;
6359       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
6360         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
6361 
6362       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
6363         // If there's already a cast present, just replace it.
6364         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6365         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
6366 
6367       } else if (!requiresParensToAddCast(E)) {
6368         // If the expression has high enough precedence,
6369         // just write the C-style cast.
6370         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6371                                                    CastFix.str()));
6372       } else {
6373         // Otherwise, add parens around the expression as well as the cast.
6374         CastFix << "(";
6375         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
6376                                                    CastFix.str()));
6377 
6378         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
6379         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
6380       }
6381 
6382       if (ShouldNotPrintDirectly) {
6383         // The expression has a type that should not be printed directly.
6384         // We extract the name from the typedef because we don't want to show
6385         // the underlying type in the diagnostic.
6386         StringRef Name;
6387         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6388           Name = TypedefTy->getDecl()->getName();
6389         else
6390           Name = CastTyName;
6391         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6392                                << Name << IntendedTy << IsEnum
6393                                << E->getSourceRange(),
6394                              E->getLocStart(), /*IsStringLocation=*/false,
6395                              SpecRange, Hints);
6396       } else {
6397         // In this case, the expression could be printed using a different
6398         // specifier, but we've decided that the specifier is probably correct
6399         // and we should cast instead. Just use the normal warning message.
6400         EmitFormatDiagnostic(
6401           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6402             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6403             << E->getSourceRange(),
6404           E->getLocStart(), /*IsStringLocation*/false,
6405           SpecRange, Hints);
6406       }
6407     }
6408   } else {
6409     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
6410                                                    SpecifierLen);
6411     // Since the warning for passing non-POD types to variadic functions
6412     // was deferred until now, we emit a warning for non-POD
6413     // arguments here.
6414     switch (S.isValidVarArgType(ExprTy)) {
6415     case Sema::VAK_Valid:
6416     case Sema::VAK_ValidInCXX11: {
6417       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6418       if (match == analyze_printf::ArgType::NoMatchPedantic) {
6419         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6420       }
6421 
6422       EmitFormatDiagnostic(
6423           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6424                         << IsEnum << CSR << E->getSourceRange(),
6425           E->getLocStart(), /*IsStringLocation*/ false, CSR);
6426       break;
6427     }
6428     case Sema::VAK_Undefined:
6429     case Sema::VAK_MSVCUndefined:
6430       EmitFormatDiagnostic(
6431         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6432           << S.getLangOpts().CPlusPlus11
6433           << ExprTy
6434           << CallType
6435           << AT.getRepresentativeTypeName(S.Context)
6436           << CSR
6437           << E->getSourceRange(),
6438         E->getLocStart(), /*IsStringLocation*/false, CSR);
6439       checkForCStrMembers(AT, E);
6440       break;
6441 
6442     case Sema::VAK_Invalid:
6443       if (ExprTy->isObjCObjectType())
6444         EmitFormatDiagnostic(
6445           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6446             << S.getLangOpts().CPlusPlus11
6447             << ExprTy
6448             << CallType
6449             << AT.getRepresentativeTypeName(S.Context)
6450             << CSR
6451             << E->getSourceRange(),
6452           E->getLocStart(), /*IsStringLocation*/false, CSR);
6453       else
6454         // FIXME: If this is an initializer list, suggest removing the braces
6455         // or inserting a cast to the target type.
6456         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
6457           << isa<InitListExpr>(E) << ExprTy << CallType
6458           << AT.getRepresentativeTypeName(S.Context)
6459           << E->getSourceRange();
6460       break;
6461     }
6462 
6463     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
6464            "format string specifier index out of range");
6465     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
6466   }
6467 
6468   return true;
6469 }
6470 
6471 //===--- CHECK: Scanf format string checking ------------------------------===//
6472 
6473 namespace {
6474 class CheckScanfHandler : public CheckFormatHandler {
6475 public:
6476   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
6477                     const Expr *origFormatExpr, Sema::FormatStringType type,
6478                     unsigned firstDataArg, unsigned numDataArgs,
6479                     const char *beg, bool hasVAListArg,
6480                     ArrayRef<const Expr *> Args, unsigned formatIdx,
6481                     bool inFunctionCall, Sema::VariadicCallType CallType,
6482                     llvm::SmallBitVector &CheckedVarArgs,
6483                     UncoveredArgHandler &UncoveredArg)
6484       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6485                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
6486                            inFunctionCall, CallType, CheckedVarArgs,
6487                            UncoveredArg) {}
6488 
6489   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
6490                             const char *startSpecifier,
6491                             unsigned specifierLen) override;
6492 
6493   bool HandleInvalidScanfConversionSpecifier(
6494           const analyze_scanf::ScanfSpecifier &FS,
6495           const char *startSpecifier,
6496           unsigned specifierLen) override;
6497 
6498   void HandleIncompleteScanList(const char *start, const char *end) override;
6499 };
6500 } // end anonymous namespace
6501 
6502 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
6503                                                  const char *end) {
6504   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6505                        getLocationOfByte(end), /*IsStringLocation*/true,
6506                        getSpecifierRange(start, end - start));
6507 }
6508 
6509 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6510                                         const analyze_scanf::ScanfSpecifier &FS,
6511                                         const char *startSpecifier,
6512                                         unsigned specifierLen) {
6513 
6514   const analyze_scanf::ScanfConversionSpecifier &CS =
6515     FS.getConversionSpecifier();
6516 
6517   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
6518                                           getLocationOfByte(CS.getStart()),
6519                                           startSpecifier, specifierLen,
6520                                           CS.getStart(), CS.getLength());
6521 }
6522 
6523 bool CheckScanfHandler::HandleScanfSpecifier(
6524                                        const analyze_scanf::ScanfSpecifier &FS,
6525                                        const char *startSpecifier,
6526                                        unsigned specifierLen) {
6527   using namespace analyze_scanf;
6528   using namespace analyze_format_string;
6529 
6530   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
6531 
6532   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
6533   // be used to decide if we are using positional arguments consistently.
6534   if (FS.consumesDataArgument()) {
6535     if (atFirstArg) {
6536       atFirstArg = false;
6537       usesPositionalArgs = FS.usesPositionalArg();
6538     }
6539     else if (usesPositionalArgs != FS.usesPositionalArg()) {
6540       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
6541                                         startSpecifier, specifierLen);
6542       return false;
6543     }
6544   }
6545 
6546   // Check if the field with is non-zero.
6547   const OptionalAmount &Amt = FS.getFieldWidth();
6548   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6549     if (Amt.getConstantAmount() == 0) {
6550       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
6551                                                    Amt.getConstantLength());
6552       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6553                            getLocationOfByte(Amt.getStart()),
6554                            /*IsStringLocation*/true, R,
6555                            FixItHint::CreateRemoval(R));
6556     }
6557   }
6558 
6559   if (!FS.consumesDataArgument()) {
6560     // FIXME: Technically specifying a precision or field width here
6561     // makes no sense.  Worth issuing a warning at some point.
6562     return true;
6563   }
6564 
6565   // Consume the argument.
6566   unsigned argIndex = FS.getArgIndex();
6567   if (argIndex < NumDataArgs) {
6568       // The check to see if the argIndex is valid will come later.
6569       // We set the bit here because we may exit early from this
6570       // function if we encounter some other error.
6571     CoveredArgs.set(argIndex);
6572   }
6573 
6574   // Check the length modifier is valid with the given conversion specifier.
6575   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
6576     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6577                                 diag::warn_format_nonsensical_length);
6578   else if (!FS.hasStandardLengthModifier())
6579     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6580   else if (!FS.hasStandardLengthConversionCombination())
6581     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6582                                 diag::warn_format_non_standard_conversion_spec);
6583 
6584   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
6585     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6586 
6587   // The remaining checks depend on the data arguments.
6588   if (HasVAListArg)
6589     return true;
6590 
6591   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6592     return false;
6593 
6594   // Check that the argument type matches the format specifier.
6595   const Expr *Ex = getDataArg(argIndex);
6596   if (!Ex)
6597     return true;
6598 
6599   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
6600 
6601   if (!AT.isValid()) {
6602     return true;
6603   }
6604 
6605   analyze_format_string::ArgType::MatchKind match =
6606       AT.matchesType(S.Context, Ex->getType());
6607   if (match == analyze_format_string::ArgType::Match) {
6608     return true;
6609   }
6610 
6611   ScanfSpecifier fixedFS = FS;
6612   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6613                                  S.getLangOpts(), S.Context);
6614 
6615   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6616   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
6617     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6618   }
6619 
6620   if (success) {
6621     // Get the fix string from the fixed format specifier.
6622     SmallString<128> buf;
6623     llvm::raw_svector_ostream os(buf);
6624     fixedFS.toString(os);
6625 
6626     EmitFormatDiagnostic(
6627         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6628                       << Ex->getType() << false << Ex->getSourceRange(),
6629         Ex->getLocStart(),
6630         /*IsStringLocation*/ false,
6631         getSpecifierRange(startSpecifier, specifierLen),
6632         FixItHint::CreateReplacement(
6633             getSpecifierRange(startSpecifier, specifierLen), os.str()));
6634   } else {
6635     EmitFormatDiagnostic(S.PDiag(diag)
6636                              << AT.getRepresentativeTypeName(S.Context)
6637                              << Ex->getType() << false << Ex->getSourceRange(),
6638                          Ex->getLocStart(),
6639                          /*IsStringLocation*/ false,
6640                          getSpecifierRange(startSpecifier, specifierLen));
6641   }
6642 
6643   return true;
6644 }
6645 
6646 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
6647                               const Expr *OrigFormatExpr,
6648                               ArrayRef<const Expr *> Args,
6649                               bool HasVAListArg, unsigned format_idx,
6650                               unsigned firstDataArg,
6651                               Sema::FormatStringType Type,
6652                               bool inFunctionCall,
6653                               Sema::VariadicCallType CallType,
6654                               llvm::SmallBitVector &CheckedVarArgs,
6655                               UncoveredArgHandler &UncoveredArg) {
6656   // CHECK: is the format string a wide literal?
6657   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6658     CheckFormatHandler::EmitFormatDiagnostic(
6659       S, inFunctionCall, Args[format_idx],
6660       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6661       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6662     return;
6663   }
6664 
6665   // Str - The format string.  NOTE: this is NOT null-terminated!
6666   StringRef StrRef = FExpr->getString();
6667   const char *Str = StrRef.data();
6668   // Account for cases where the string literal is truncated in a declaration.
6669   const ConstantArrayType *T =
6670     S.Context.getAsConstantArrayType(FExpr->getType());
6671   assert(T && "String literal not of constant array type!");
6672   size_t TypeSize = T->getSize().getZExtValue();
6673   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6674   const unsigned numDataArgs = Args.size() - firstDataArg;
6675 
6676   // Emit a warning if the string literal is truncated and does not contain an
6677   // embedded null character.
6678   if (TypeSize <= StrRef.size() &&
6679       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
6680     CheckFormatHandler::EmitFormatDiagnostic(
6681         S, inFunctionCall, Args[format_idx],
6682         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
6683         FExpr->getLocStart(),
6684         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
6685     return;
6686   }
6687 
6688   // CHECK: empty format string?
6689   if (StrLen == 0 && numDataArgs > 0) {
6690     CheckFormatHandler::EmitFormatDiagnostic(
6691       S, inFunctionCall, Args[format_idx],
6692       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6693       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
6694     return;
6695   }
6696 
6697   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
6698       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
6699       Type == Sema::FST_OSTrace) {
6700     CheckPrintfHandler H(
6701         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6702         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
6703         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6704         CheckedVarArgs, UncoveredArg);
6705 
6706     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
6707                                                   S.getLangOpts(),
6708                                                   S.Context.getTargetInfo(),
6709                                             Type == Sema::FST_FreeBSDKPrintf))
6710       H.DoneProcessing();
6711   } else if (Type == Sema::FST_Scanf) {
6712     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6713                         numDataArgs, Str, HasVAListArg, Args, format_idx,
6714                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6715 
6716     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
6717                                                  S.getLangOpts(),
6718                                                  S.Context.getTargetInfo()))
6719       H.DoneProcessing();
6720   } // TODO: handle other formats
6721 }
6722 
6723 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
6724   // Str - The format string.  NOTE: this is NOT null-terminated!
6725   StringRef StrRef = FExpr->getString();
6726   const char *Str = StrRef.data();
6727   // Account for cases where the string literal is truncated in a declaration.
6728   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
6729   assert(T && "String literal not of constant array type!");
6730   size_t TypeSize = T->getSize().getZExtValue();
6731   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
6732   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
6733                                                          getLangOpts(),
6734                                                          Context.getTargetInfo());
6735 }
6736 
6737 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
6738 
6739 // Returns the related absolute value function that is larger, of 0 if one
6740 // does not exist.
6741 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
6742   switch (AbsFunction) {
6743   default:
6744     return 0;
6745 
6746   case Builtin::BI__builtin_abs:
6747     return Builtin::BI__builtin_labs;
6748   case Builtin::BI__builtin_labs:
6749     return Builtin::BI__builtin_llabs;
6750   case Builtin::BI__builtin_llabs:
6751     return 0;
6752 
6753   case Builtin::BI__builtin_fabsf:
6754     return Builtin::BI__builtin_fabs;
6755   case Builtin::BI__builtin_fabs:
6756     return Builtin::BI__builtin_fabsl;
6757   case Builtin::BI__builtin_fabsl:
6758     return 0;
6759 
6760   case Builtin::BI__builtin_cabsf:
6761     return Builtin::BI__builtin_cabs;
6762   case Builtin::BI__builtin_cabs:
6763     return Builtin::BI__builtin_cabsl;
6764   case Builtin::BI__builtin_cabsl:
6765     return 0;
6766 
6767   case Builtin::BIabs:
6768     return Builtin::BIlabs;
6769   case Builtin::BIlabs:
6770     return Builtin::BIllabs;
6771   case Builtin::BIllabs:
6772     return 0;
6773 
6774   case Builtin::BIfabsf:
6775     return Builtin::BIfabs;
6776   case Builtin::BIfabs:
6777     return Builtin::BIfabsl;
6778   case Builtin::BIfabsl:
6779     return 0;
6780 
6781   case Builtin::BIcabsf:
6782    return Builtin::BIcabs;
6783   case Builtin::BIcabs:
6784     return Builtin::BIcabsl;
6785   case Builtin::BIcabsl:
6786     return 0;
6787   }
6788 }
6789 
6790 // Returns the argument type of the absolute value function.
6791 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
6792                                              unsigned AbsType) {
6793   if (AbsType == 0)
6794     return QualType();
6795 
6796   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
6797   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
6798   if (Error != ASTContext::GE_None)
6799     return QualType();
6800 
6801   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
6802   if (!FT)
6803     return QualType();
6804 
6805   if (FT->getNumParams() != 1)
6806     return QualType();
6807 
6808   return FT->getParamType(0);
6809 }
6810 
6811 // Returns the best absolute value function, or zero, based on type and
6812 // current absolute value function.
6813 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
6814                                    unsigned AbsFunctionKind) {
6815   unsigned BestKind = 0;
6816   uint64_t ArgSize = Context.getTypeSize(ArgType);
6817   for (unsigned Kind = AbsFunctionKind; Kind != 0;
6818        Kind = getLargerAbsoluteValueFunction(Kind)) {
6819     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
6820     if (Context.getTypeSize(ParamType) >= ArgSize) {
6821       if (BestKind == 0)
6822         BestKind = Kind;
6823       else if (Context.hasSameType(ParamType, ArgType)) {
6824         BestKind = Kind;
6825         break;
6826       }
6827     }
6828   }
6829   return BestKind;
6830 }
6831 
6832 enum AbsoluteValueKind {
6833   AVK_Integer,
6834   AVK_Floating,
6835   AVK_Complex
6836 };
6837 
6838 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
6839   if (T->isIntegralOrEnumerationType())
6840     return AVK_Integer;
6841   if (T->isRealFloatingType())
6842     return AVK_Floating;
6843   if (T->isAnyComplexType())
6844     return AVK_Complex;
6845 
6846   llvm_unreachable("Type not integer, floating, or complex");
6847 }
6848 
6849 // Changes the absolute value function to a different type.  Preserves whether
6850 // the function is a builtin.
6851 static unsigned changeAbsFunction(unsigned AbsKind,
6852                                   AbsoluteValueKind ValueKind) {
6853   switch (ValueKind) {
6854   case AVK_Integer:
6855     switch (AbsKind) {
6856     default:
6857       return 0;
6858     case Builtin::BI__builtin_fabsf:
6859     case Builtin::BI__builtin_fabs:
6860     case Builtin::BI__builtin_fabsl:
6861     case Builtin::BI__builtin_cabsf:
6862     case Builtin::BI__builtin_cabs:
6863     case Builtin::BI__builtin_cabsl:
6864       return Builtin::BI__builtin_abs;
6865     case Builtin::BIfabsf:
6866     case Builtin::BIfabs:
6867     case Builtin::BIfabsl:
6868     case Builtin::BIcabsf:
6869     case Builtin::BIcabs:
6870     case Builtin::BIcabsl:
6871       return Builtin::BIabs;
6872     }
6873   case AVK_Floating:
6874     switch (AbsKind) {
6875     default:
6876       return 0;
6877     case Builtin::BI__builtin_abs:
6878     case Builtin::BI__builtin_labs:
6879     case Builtin::BI__builtin_llabs:
6880     case Builtin::BI__builtin_cabsf:
6881     case Builtin::BI__builtin_cabs:
6882     case Builtin::BI__builtin_cabsl:
6883       return Builtin::BI__builtin_fabsf;
6884     case Builtin::BIabs:
6885     case Builtin::BIlabs:
6886     case Builtin::BIllabs:
6887     case Builtin::BIcabsf:
6888     case Builtin::BIcabs:
6889     case Builtin::BIcabsl:
6890       return Builtin::BIfabsf;
6891     }
6892   case AVK_Complex:
6893     switch (AbsKind) {
6894     default:
6895       return 0;
6896     case Builtin::BI__builtin_abs:
6897     case Builtin::BI__builtin_labs:
6898     case Builtin::BI__builtin_llabs:
6899     case Builtin::BI__builtin_fabsf:
6900     case Builtin::BI__builtin_fabs:
6901     case Builtin::BI__builtin_fabsl:
6902       return Builtin::BI__builtin_cabsf;
6903     case Builtin::BIabs:
6904     case Builtin::BIlabs:
6905     case Builtin::BIllabs:
6906     case Builtin::BIfabsf:
6907     case Builtin::BIfabs:
6908     case Builtin::BIfabsl:
6909       return Builtin::BIcabsf;
6910     }
6911   }
6912   llvm_unreachable("Unable to convert function");
6913 }
6914 
6915 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
6916   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
6917   if (!FnInfo)
6918     return 0;
6919 
6920   switch (FDecl->getBuiltinID()) {
6921   default:
6922     return 0;
6923   case Builtin::BI__builtin_abs:
6924   case Builtin::BI__builtin_fabs:
6925   case Builtin::BI__builtin_fabsf:
6926   case Builtin::BI__builtin_fabsl:
6927   case Builtin::BI__builtin_labs:
6928   case Builtin::BI__builtin_llabs:
6929   case Builtin::BI__builtin_cabs:
6930   case Builtin::BI__builtin_cabsf:
6931   case Builtin::BI__builtin_cabsl:
6932   case Builtin::BIabs:
6933   case Builtin::BIlabs:
6934   case Builtin::BIllabs:
6935   case Builtin::BIfabs:
6936   case Builtin::BIfabsf:
6937   case Builtin::BIfabsl:
6938   case Builtin::BIcabs:
6939   case Builtin::BIcabsf:
6940   case Builtin::BIcabsl:
6941     return FDecl->getBuiltinID();
6942   }
6943   llvm_unreachable("Unknown Builtin type");
6944 }
6945 
6946 // If the replacement is valid, emit a note with replacement function.
6947 // Additionally, suggest including the proper header if not already included.
6948 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
6949                             unsigned AbsKind, QualType ArgType) {
6950   bool EmitHeaderHint = true;
6951   const char *HeaderName = nullptr;
6952   const char *FunctionName = nullptr;
6953   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
6954     FunctionName = "std::abs";
6955     if (ArgType->isIntegralOrEnumerationType()) {
6956       HeaderName = "cstdlib";
6957     } else if (ArgType->isRealFloatingType()) {
6958       HeaderName = "cmath";
6959     } else {
6960       llvm_unreachable("Invalid Type");
6961     }
6962 
6963     // Lookup all std::abs
6964     if (NamespaceDecl *Std = S.getStdNamespace()) {
6965       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
6966       R.suppressDiagnostics();
6967       S.LookupQualifiedName(R, Std);
6968 
6969       for (const auto *I : R) {
6970         const FunctionDecl *FDecl = nullptr;
6971         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
6972           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
6973         } else {
6974           FDecl = dyn_cast<FunctionDecl>(I);
6975         }
6976         if (!FDecl)
6977           continue;
6978 
6979         // Found std::abs(), check that they are the right ones.
6980         if (FDecl->getNumParams() != 1)
6981           continue;
6982 
6983         // Check that the parameter type can handle the argument.
6984         QualType ParamType = FDecl->getParamDecl(0)->getType();
6985         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
6986             S.Context.getTypeSize(ArgType) <=
6987                 S.Context.getTypeSize(ParamType)) {
6988           // Found a function, don't need the header hint.
6989           EmitHeaderHint = false;
6990           break;
6991         }
6992       }
6993     }
6994   } else {
6995     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
6996     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
6997 
6998     if (HeaderName) {
6999       DeclarationName DN(&S.Context.Idents.get(FunctionName));
7000       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
7001       R.suppressDiagnostics();
7002       S.LookupName(R, S.getCurScope());
7003 
7004       if (R.isSingleResult()) {
7005         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
7006         if (FD && FD->getBuiltinID() == AbsKind) {
7007           EmitHeaderHint = false;
7008         } else {
7009           return;
7010         }
7011       } else if (!R.empty()) {
7012         return;
7013       }
7014     }
7015   }
7016 
7017   S.Diag(Loc, diag::note_replace_abs_function)
7018       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
7019 
7020   if (!HeaderName)
7021     return;
7022 
7023   if (!EmitHeaderHint)
7024     return;
7025 
7026   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
7027                                                     << FunctionName;
7028 }
7029 
7030 template <std::size_t StrLen>
7031 static bool IsStdFunction(const FunctionDecl *FDecl,
7032                           const char (&Str)[StrLen]) {
7033   if (!FDecl)
7034     return false;
7035   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
7036     return false;
7037   if (!FDecl->isInStdNamespace())
7038     return false;
7039 
7040   return true;
7041 }
7042 
7043 // Warn when using the wrong abs() function.
7044 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
7045                                       const FunctionDecl *FDecl) {
7046   if (Call->getNumArgs() != 1)
7047     return;
7048 
7049   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
7050   bool IsStdAbs = IsStdFunction(FDecl, "abs");
7051   if (AbsKind == 0 && !IsStdAbs)
7052     return;
7053 
7054   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7055   QualType ParamType = Call->getArg(0)->getType();
7056 
7057   // Unsigned types cannot be negative.  Suggest removing the absolute value
7058   // function call.
7059   if (ArgType->isUnsignedIntegerType()) {
7060     const char *FunctionName =
7061         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
7062     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
7063     Diag(Call->getExprLoc(), diag::note_remove_abs)
7064         << FunctionName
7065         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
7066     return;
7067   }
7068 
7069   // Taking the absolute value of a pointer is very suspicious, they probably
7070   // wanted to index into an array, dereference a pointer, call a function, etc.
7071   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
7072     unsigned DiagType = 0;
7073     if (ArgType->isFunctionType())
7074       DiagType = 1;
7075     else if (ArgType->isArrayType())
7076       DiagType = 2;
7077 
7078     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
7079     return;
7080   }
7081 
7082   // std::abs has overloads which prevent most of the absolute value problems
7083   // from occurring.
7084   if (IsStdAbs)
7085     return;
7086 
7087   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
7088   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
7089 
7090   // The argument and parameter are the same kind.  Check if they are the right
7091   // size.
7092   if (ArgValueKind == ParamValueKind) {
7093     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
7094       return;
7095 
7096     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
7097     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
7098         << FDecl << ArgType << ParamType;
7099 
7100     if (NewAbsKind == 0)
7101       return;
7102 
7103     emitReplacement(*this, Call->getExprLoc(),
7104                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7105     return;
7106   }
7107 
7108   // ArgValueKind != ParamValueKind
7109   // The wrong type of absolute value function was used.  Attempt to find the
7110   // proper one.
7111   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
7112   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
7113   if (NewAbsKind == 0)
7114     return;
7115 
7116   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
7117       << FDecl << ParamValueKind << ArgValueKind;
7118 
7119   emitReplacement(*this, Call->getExprLoc(),
7120                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
7121 }
7122 
7123 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
7124 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
7125                                 const FunctionDecl *FDecl) {
7126   if (!Call || !FDecl) return;
7127 
7128   // Ignore template specializations and macros.
7129   if (inTemplateInstantiation()) return;
7130   if (Call->getExprLoc().isMacroID()) return;
7131 
7132   // Only care about the one template argument, two function parameter std::max
7133   if (Call->getNumArgs() != 2) return;
7134   if (!IsStdFunction(FDecl, "max")) return;
7135   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
7136   if (!ArgList) return;
7137   if (ArgList->size() != 1) return;
7138 
7139   // Check that template type argument is unsigned integer.
7140   const auto& TA = ArgList->get(0);
7141   if (TA.getKind() != TemplateArgument::Type) return;
7142   QualType ArgType = TA.getAsType();
7143   if (!ArgType->isUnsignedIntegerType()) return;
7144 
7145   // See if either argument is a literal zero.
7146   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
7147     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
7148     if (!MTE) return false;
7149     const auto *Num = dyn_cast<IntegerLiteral>(MTE->GetTemporaryExpr());
7150     if (!Num) return false;
7151     if (Num->getValue() != 0) return false;
7152     return true;
7153   };
7154 
7155   const Expr *FirstArg = Call->getArg(0);
7156   const Expr *SecondArg = Call->getArg(1);
7157   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7158   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7159 
7160   // Only warn when exactly one argument is zero.
7161   if (IsFirstArgZero == IsSecondArgZero) return;
7162 
7163   SourceRange FirstRange = FirstArg->getSourceRange();
7164   SourceRange SecondRange = SecondArg->getSourceRange();
7165 
7166   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7167 
7168   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
7169       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
7170 
7171   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
7172   SourceRange RemovalRange;
7173   if (IsFirstArgZero) {
7174     RemovalRange = SourceRange(FirstRange.getBegin(),
7175                                SecondRange.getBegin().getLocWithOffset(-1));
7176   } else {
7177     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
7178                                SecondRange.getEnd());
7179   }
7180 
7181   Diag(Call->getExprLoc(), diag::note_remove_max_call)
7182         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
7183         << FixItHint::CreateRemoval(RemovalRange);
7184 }
7185 
7186 //===--- CHECK: Standard memory functions ---------------------------------===//
7187 
7188 /// \brief Takes the expression passed to the size_t parameter of functions
7189 /// such as memcmp, strncat, etc and warns if it's a comparison.
7190 ///
7191 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
7192 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
7193                                            IdentifierInfo *FnName,
7194                                            SourceLocation FnLoc,
7195                                            SourceLocation RParenLoc) {
7196   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
7197   if (!Size)
7198     return false;
7199 
7200   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
7201   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
7202     return false;
7203 
7204   SourceRange SizeRange = Size->getSourceRange();
7205   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
7206       << SizeRange << FnName;
7207   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
7208       << FnName << FixItHint::CreateInsertion(
7209                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
7210       << FixItHint::CreateRemoval(RParenLoc);
7211   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
7212       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
7213       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
7214                                     ")");
7215 
7216   return true;
7217 }
7218 
7219 /// \brief Determine whether the given type is or contains a dynamic class type
7220 /// (e.g., whether it has a vtable).
7221 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
7222                                                      bool &IsContained) {
7223   // Look through array types while ignoring qualifiers.
7224   const Type *Ty = T->getBaseElementTypeUnsafe();
7225   IsContained = false;
7226 
7227   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
7228   RD = RD ? RD->getDefinition() : nullptr;
7229   if (!RD || RD->isInvalidDecl())
7230     return nullptr;
7231 
7232   if (RD->isDynamicClass())
7233     return RD;
7234 
7235   // Check all the fields.  If any bases were dynamic, the class is dynamic.
7236   // It's impossible for a class to transitively contain itself by value, so
7237   // infinite recursion is impossible.
7238   for (auto *FD : RD->fields()) {
7239     bool SubContained;
7240     if (const CXXRecordDecl *ContainedRD =
7241             getContainedDynamicClass(FD->getType(), SubContained)) {
7242       IsContained = true;
7243       return ContainedRD;
7244     }
7245   }
7246 
7247   return nullptr;
7248 }
7249 
7250 /// \brief If E is a sizeof expression, returns its argument expression,
7251 /// otherwise returns NULL.
7252 static const Expr *getSizeOfExprArg(const Expr *E) {
7253   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7254       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7255     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
7256       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
7257 
7258   return nullptr;
7259 }
7260 
7261 /// \brief If E is a sizeof expression, returns its argument type.
7262 static QualType getSizeOfArgType(const Expr *E) {
7263   if (const UnaryExprOrTypeTraitExpr *SizeOf =
7264       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7265     if (SizeOf->getKind() == clang::UETT_SizeOf)
7266       return SizeOf->getTypeOfArgument();
7267 
7268   return QualType();
7269 }
7270 
7271 /// \brief Check for dangerous or invalid arguments to memset().
7272 ///
7273 /// This issues warnings on known problematic, dangerous or unspecified
7274 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
7275 /// function calls.
7276 ///
7277 /// \param Call The call expression to diagnose.
7278 void Sema::CheckMemaccessArguments(const CallExpr *Call,
7279                                    unsigned BId,
7280                                    IdentifierInfo *FnName) {
7281   assert(BId != 0);
7282 
7283   // It is possible to have a non-standard definition of memset.  Validate
7284   // we have enough arguments, and if not, abort further checking.
7285   unsigned ExpectedNumArgs =
7286       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7287   if (Call->getNumArgs() < ExpectedNumArgs)
7288     return;
7289 
7290   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7291                       BId == Builtin::BIstrndup ? 1 : 2);
7292   unsigned LenArg =
7293       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7294   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
7295 
7296   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
7297                                      Call->getLocStart(), Call->getRParenLoc()))
7298     return;
7299 
7300   // We have special checking when the length is a sizeof expression.
7301   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
7302   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
7303   llvm::FoldingSetNodeID SizeOfArgID;
7304 
7305   // Although widely used, 'bzero' is not a standard function. Be more strict
7306   // with the argument types before allowing diagnostics and only allow the
7307   // form bzero(ptr, sizeof(...)).
7308   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
7309   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
7310     return;
7311 
7312   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7313     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
7314     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
7315 
7316     QualType DestTy = Dest->getType();
7317     QualType PointeeTy;
7318     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
7319       PointeeTy = DestPtrTy->getPointeeType();
7320 
7321       // Never warn about void type pointers. This can be used to suppress
7322       // false positives.
7323       if (PointeeTy->isVoidType())
7324         continue;
7325 
7326       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
7327       // actually comparing the expressions for equality. Because computing the
7328       // expression IDs can be expensive, we only do this if the diagnostic is
7329       // enabled.
7330       if (SizeOfArg &&
7331           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7332                            SizeOfArg->getExprLoc())) {
7333         // We only compute IDs for expressions if the warning is enabled, and
7334         // cache the sizeof arg's ID.
7335         if (SizeOfArgID == llvm::FoldingSetNodeID())
7336           SizeOfArg->Profile(SizeOfArgID, Context, true);
7337         llvm::FoldingSetNodeID DestID;
7338         Dest->Profile(DestID, Context, true);
7339         if (DestID == SizeOfArgID) {
7340           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
7341           //       over sizeof(src) as well.
7342           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
7343           StringRef ReadableName = FnName->getName();
7344 
7345           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7346             if (UnaryOp->getOpcode() == UO_AddrOf)
7347               ActionIdx = 1; // If its an address-of operator, just remove it.
7348           if (!PointeeTy->isIncompleteType() &&
7349               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
7350             ActionIdx = 2; // If the pointee's size is sizeof(char),
7351                            // suggest an explicit length.
7352 
7353           // If the function is defined as a builtin macro, do not show macro
7354           // expansion.
7355           SourceLocation SL = SizeOfArg->getExprLoc();
7356           SourceRange DSR = Dest->getSourceRange();
7357           SourceRange SSR = SizeOfArg->getSourceRange();
7358           SourceManager &SM = getSourceManager();
7359 
7360           if (SM.isMacroArgExpansion(SL)) {
7361             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
7362             SL = SM.getSpellingLoc(SL);
7363             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
7364                              SM.getSpellingLoc(DSR.getEnd()));
7365             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
7366                              SM.getSpellingLoc(SSR.getEnd()));
7367           }
7368 
7369           DiagRuntimeBehavior(SL, SizeOfArg,
7370                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7371                                 << ReadableName
7372                                 << PointeeTy
7373                                 << DestTy
7374                                 << DSR
7375                                 << SSR);
7376           DiagRuntimeBehavior(SL, SizeOfArg,
7377                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7378                                 << ActionIdx
7379                                 << SSR);
7380 
7381           break;
7382         }
7383       }
7384 
7385       // Also check for cases where the sizeof argument is the exact same
7386       // type as the memory argument, and where it points to a user-defined
7387       // record type.
7388       if (SizeOfArgTy != QualType()) {
7389         if (PointeeTy->isRecordType() &&
7390             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
7391           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
7392                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
7393                                 << FnName << SizeOfArgTy << ArgIdx
7394                                 << PointeeTy << Dest->getSourceRange()
7395                                 << LenExpr->getSourceRange());
7396           break;
7397         }
7398       }
7399     } else if (DestTy->isArrayType()) {
7400       PointeeTy = DestTy;
7401     }
7402 
7403     if (PointeeTy == QualType())
7404       continue;
7405 
7406     // Always complain about dynamic classes.
7407     bool IsContained;
7408     if (const CXXRecordDecl *ContainedRD =
7409             getContainedDynamicClass(PointeeTy, IsContained)) {
7410 
7411       unsigned OperationType = 0;
7412       // "overwritten" if we're warning about the destination for any call
7413       // but memcmp; otherwise a verb appropriate to the call.
7414       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7415         if (BId == Builtin::BImemcpy)
7416           OperationType = 1;
7417         else if(BId == Builtin::BImemmove)
7418           OperationType = 2;
7419         else if (BId == Builtin::BImemcmp)
7420           OperationType = 3;
7421       }
7422 
7423       DiagRuntimeBehavior(
7424         Dest->getExprLoc(), Dest,
7425         PDiag(diag::warn_dyn_class_memaccess)
7426           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7427           << FnName << IsContained << ContainedRD << OperationType
7428           << Call->getCallee()->getSourceRange());
7429     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
7430              BId != Builtin::BImemset)
7431       DiagRuntimeBehavior(
7432         Dest->getExprLoc(), Dest,
7433         PDiag(diag::warn_arc_object_memaccess)
7434           << ArgIdx << FnName << PointeeTy
7435           << Call->getCallee()->getSourceRange());
7436     else
7437       continue;
7438 
7439     DiagRuntimeBehavior(
7440       Dest->getExprLoc(), Dest,
7441       PDiag(diag::note_bad_memaccess_silence)
7442         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
7443     break;
7444   }
7445 }
7446 
7447 // A little helper routine: ignore addition and subtraction of integer literals.
7448 // This intentionally does not ignore all integer constant expressions because
7449 // we don't want to remove sizeof().
7450 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
7451   Ex = Ex->IgnoreParenCasts();
7452 
7453   for (;;) {
7454     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
7455     if (!BO || !BO->isAdditiveOp())
7456       break;
7457 
7458     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
7459     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
7460 
7461     if (isa<IntegerLiteral>(RHS))
7462       Ex = LHS;
7463     else if (isa<IntegerLiteral>(LHS))
7464       Ex = RHS;
7465     else
7466       break;
7467   }
7468 
7469   return Ex;
7470 }
7471 
7472 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
7473                                                       ASTContext &Context) {
7474   // Only handle constant-sized or VLAs, but not flexible members.
7475   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
7476     // Only issue the FIXIT for arrays of size > 1.
7477     if (CAT->getSize().getSExtValue() <= 1)
7478       return false;
7479   } else if (!Ty->isVariableArrayType()) {
7480     return false;
7481   }
7482   return true;
7483 }
7484 
7485 // Warn if the user has made the 'size' argument to strlcpy or strlcat
7486 // be the size of the source, instead of the destination.
7487 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
7488                                     IdentifierInfo *FnName) {
7489 
7490   // Don't crash if the user has the wrong number of arguments
7491   unsigned NumArgs = Call->getNumArgs();
7492   if ((NumArgs != 3) && (NumArgs != 4))
7493     return;
7494 
7495   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
7496   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
7497   const Expr *CompareWithSrc = nullptr;
7498 
7499   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
7500                                      Call->getLocStart(), Call->getRParenLoc()))
7501     return;
7502 
7503   // Look for 'strlcpy(dst, x, sizeof(x))'
7504   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
7505     CompareWithSrc = Ex;
7506   else {
7507     // Look for 'strlcpy(dst, x, strlen(x))'
7508     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7509       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7510           SizeCall->getNumArgs() == 1)
7511         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
7512     }
7513   }
7514 
7515   if (!CompareWithSrc)
7516     return;
7517 
7518   // Determine if the argument to sizeof/strlen is equal to the source
7519   // argument.  In principle there's all kinds of things you could do
7520   // here, for instance creating an == expression and evaluating it with
7521   // EvaluateAsBooleanCondition, but this uses a more direct technique:
7522   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
7523   if (!SrcArgDRE)
7524     return;
7525 
7526   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
7527   if (!CompareWithSrcDRE ||
7528       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
7529     return;
7530 
7531   const Expr *OriginalSizeArg = Call->getArg(2);
7532   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
7533     << OriginalSizeArg->getSourceRange() << FnName;
7534 
7535   // Output a FIXIT hint if the destination is an array (rather than a
7536   // pointer to an array).  This could be enhanced to handle some
7537   // pointers if we know the actual size, like if DstArg is 'array+2'
7538   // we could say 'sizeof(array)-2'.
7539   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
7540   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
7541     return;
7542 
7543   SmallString<128> sizeString;
7544   llvm::raw_svector_ostream OS(sizeString);
7545   OS << "sizeof(";
7546   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7547   OS << ")";
7548 
7549   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
7550     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
7551                                     OS.str());
7552 }
7553 
7554 /// Check if two expressions refer to the same declaration.
7555 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
7556   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7557     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7558       return D1->getDecl() == D2->getDecl();
7559   return false;
7560 }
7561 
7562 static const Expr *getStrlenExprArg(const Expr *E) {
7563   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7564     const FunctionDecl *FD = CE->getDirectCallee();
7565     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
7566       return nullptr;
7567     return CE->getArg(0)->IgnoreParenCasts();
7568   }
7569   return nullptr;
7570 }
7571 
7572 // Warn on anti-patterns as the 'size' argument to strncat.
7573 // The correct size argument should look like following:
7574 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
7575 void Sema::CheckStrncatArguments(const CallExpr *CE,
7576                                  IdentifierInfo *FnName) {
7577   // Don't crash if the user has the wrong number of arguments.
7578   if (CE->getNumArgs() < 3)
7579     return;
7580   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
7581   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
7582   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
7583 
7584   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
7585                                      CE->getRParenLoc()))
7586     return;
7587 
7588   // Identify common expressions, which are wrongly used as the size argument
7589   // to strncat and may lead to buffer overflows.
7590   unsigned PatternType = 0;
7591   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
7592     // - sizeof(dst)
7593     if (referToTheSameDecl(SizeOfArg, DstArg))
7594       PatternType = 1;
7595     // - sizeof(src)
7596     else if (referToTheSameDecl(SizeOfArg, SrcArg))
7597       PatternType = 2;
7598   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7599     if (BE->getOpcode() == BO_Sub) {
7600       const Expr *L = BE->getLHS()->IgnoreParenCasts();
7601       const Expr *R = BE->getRHS()->IgnoreParenCasts();
7602       // - sizeof(dst) - strlen(dst)
7603       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
7604           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
7605         PatternType = 1;
7606       // - sizeof(src) - (anything)
7607       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
7608         PatternType = 2;
7609     }
7610   }
7611 
7612   if (PatternType == 0)
7613     return;
7614 
7615   // Generate the diagnostic.
7616   SourceLocation SL = LenArg->getLocStart();
7617   SourceRange SR = LenArg->getSourceRange();
7618   SourceManager &SM = getSourceManager();
7619 
7620   // If the function is defined as a builtin macro, do not show macro expansion.
7621   if (SM.isMacroArgExpansion(SL)) {
7622     SL = SM.getSpellingLoc(SL);
7623     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
7624                      SM.getSpellingLoc(SR.getEnd()));
7625   }
7626 
7627   // Check if the destination is an array (rather than a pointer to an array).
7628   QualType DstTy = DstArg->getType();
7629   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
7630                                                                     Context);
7631   if (!isKnownSizeArray) {
7632     if (PatternType == 1)
7633       Diag(SL, diag::warn_strncat_wrong_size) << SR;
7634     else
7635       Diag(SL, diag::warn_strncat_src_size) << SR;
7636     return;
7637   }
7638 
7639   if (PatternType == 1)
7640     Diag(SL, diag::warn_strncat_large_size) << SR;
7641   else
7642     Diag(SL, diag::warn_strncat_src_size) << SR;
7643 
7644   SmallString<128> sizeString;
7645   llvm::raw_svector_ostream OS(sizeString);
7646   OS << "sizeof(";
7647   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7648   OS << ") - ";
7649   OS << "strlen(";
7650   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
7651   OS << ") - 1";
7652 
7653   Diag(SL, diag::note_strncat_wrong_size)
7654     << FixItHint::CreateReplacement(SR, OS.str());
7655 }
7656 
7657 //===--- CHECK: Return Address of Stack Variable --------------------------===//
7658 
7659 static const Expr *EvalVal(const Expr *E,
7660                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7661                            const Decl *ParentDecl);
7662 static const Expr *EvalAddr(const Expr *E,
7663                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7664                             const Decl *ParentDecl);
7665 
7666 /// CheckReturnStackAddr - Check if a return statement returns the address
7667 ///   of a stack variable.
7668 static void
7669 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
7670                      SourceLocation ReturnLoc) {
7671 
7672   const Expr *stackE = nullptr;
7673   SmallVector<const DeclRefExpr *, 8> refVars;
7674 
7675   // Perform checking for returned stack addresses, local blocks,
7676   // label addresses or references to temporaries.
7677   if (lhsType->isPointerType() ||
7678       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
7679     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
7680   } else if (lhsType->isReferenceType()) {
7681     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
7682   }
7683 
7684   if (!stackE)
7685     return; // Nothing suspicious was found.
7686 
7687   // Parameters are initialized in the calling scope, so taking the address
7688   // of a parameter reference doesn't need a warning.
7689   for (auto *DRE : refVars)
7690     if (isa<ParmVarDecl>(DRE->getDecl()))
7691       return;
7692 
7693   SourceLocation diagLoc;
7694   SourceRange diagRange;
7695   if (refVars.empty()) {
7696     diagLoc = stackE->getLocStart();
7697     diagRange = stackE->getSourceRange();
7698   } else {
7699     // We followed through a reference variable. 'stackE' contains the
7700     // problematic expression but we will warn at the return statement pointing
7701     // at the reference variable. We will later display the "trail" of
7702     // reference variables using notes.
7703     diagLoc = refVars[0]->getLocStart();
7704     diagRange = refVars[0]->getSourceRange();
7705   }
7706 
7707   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7708     // address of local var
7709     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
7710      << DR->getDecl()->getDeclName() << diagRange;
7711   } else if (isa<BlockExpr>(stackE)) { // local block.
7712     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7713   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
7714     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7715   } else { // local temporary.
7716     // If there is an LValue->RValue conversion, then the value of the
7717     // reference type is used, not the reference.
7718     if (auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7719       if (ICE->getCastKind() == CK_LValueToRValue) {
7720         return;
7721       }
7722     }
7723     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7724      << lhsType->isReferenceType() << diagRange;
7725   }
7726 
7727   // Display the "trail" of reference variables that we followed until we
7728   // found the problematic expression using notes.
7729   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
7730     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7731     // If this var binds to another reference var, show the range of the next
7732     // var, otherwise the var binds to the problematic expression, in which case
7733     // show the range of the expression.
7734     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
7735                                     : stackE->getSourceRange();
7736     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
7737         << VD->getDeclName() << range;
7738   }
7739 }
7740 
7741 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
7742 ///  check if the expression in a return statement evaluates to an address
7743 ///  to a location on the stack, a local block, an address of a label, or a
7744 ///  reference to local temporary. The recursion is used to traverse the
7745 ///  AST of the return expression, with recursion backtracking when we
7746 ///  encounter a subexpression that (1) clearly does not lead to one of the
7747 ///  above problematic expressions (2) is something we cannot determine leads to
7748 ///  a problematic expression based on such local checking.
7749 ///
7750 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
7751 ///  the expression that they point to. Such variables are added to the
7752 ///  'refVars' vector so that we know what the reference variable "trail" was.
7753 ///
7754 ///  EvalAddr processes expressions that are pointers that are used as
7755 ///  references (and not L-values).  EvalVal handles all other values.
7756 ///  At the base case of the recursion is a check for the above problematic
7757 ///  expressions.
7758 ///
7759 ///  This implementation handles:
7760 ///
7761 ///   * pointer-to-pointer casts
7762 ///   * implicit conversions from array references to pointers
7763 ///   * taking the address of fields
7764 ///   * arbitrary interplay between "&" and "*" operators
7765 ///   * pointer arithmetic from an address of a stack variable
7766 ///   * taking the address of an array element where the array is on the stack
7767 static const Expr *EvalAddr(const Expr *E,
7768                             SmallVectorImpl<const DeclRefExpr *> &refVars,
7769                             const Decl *ParentDecl) {
7770   if (E->isTypeDependent())
7771     return nullptr;
7772 
7773   // We should only be called for evaluating pointer expressions.
7774   assert((E->getType()->isAnyPointerType() ||
7775           E->getType()->isBlockPointerType() ||
7776           E->getType()->isObjCQualifiedIdType()) &&
7777          "EvalAddr only works on pointers");
7778 
7779   E = E->IgnoreParens();
7780 
7781   // Our "symbolic interpreter" is just a dispatch off the currently
7782   // viewed AST node.  We then recursively traverse the AST by calling
7783   // EvalAddr and EvalVal appropriately.
7784   switch (E->getStmtClass()) {
7785   case Stmt::DeclRefExprClass: {
7786     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7787 
7788     // If we leave the immediate function, the lifetime isn't about to end.
7789     if (DR->refersToEnclosingVariableOrCapture())
7790       return nullptr;
7791 
7792     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
7793       // If this is a reference variable, follow through to the expression that
7794       // it points to.
7795       if (V->hasLocalStorage() &&
7796           V->getType()->isReferenceType() && V->hasInit()) {
7797         // Add the reference variable to the "trail".
7798         refVars.push_back(DR);
7799         return EvalAddr(V->getInit(), refVars, ParentDecl);
7800       }
7801 
7802     return nullptr;
7803   }
7804 
7805   case Stmt::UnaryOperatorClass: {
7806     // The only unary operator that make sense to handle here
7807     // is AddrOf.  All others don't make sense as pointers.
7808     const UnaryOperator *U = cast<UnaryOperator>(E);
7809 
7810     if (U->getOpcode() == UO_AddrOf)
7811       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
7812     return nullptr;
7813   }
7814 
7815   case Stmt::BinaryOperatorClass: {
7816     // Handle pointer arithmetic.  All other binary operators are not valid
7817     // in this context.
7818     const BinaryOperator *B = cast<BinaryOperator>(E);
7819     BinaryOperatorKind op = B->getOpcode();
7820 
7821     if (op != BO_Add && op != BO_Sub)
7822       return nullptr;
7823 
7824     const Expr *Base = B->getLHS();
7825 
7826     // Determine which argument is the real pointer base.  It could be
7827     // the RHS argument instead of the LHS.
7828     if (!Base->getType()->isPointerType())
7829       Base = B->getRHS();
7830 
7831     assert(Base->getType()->isPointerType());
7832     return EvalAddr(Base, refVars, ParentDecl);
7833   }
7834 
7835   // For conditional operators we need to see if either the LHS or RHS are
7836   // valid DeclRefExpr*s.  If one of them is valid, we return it.
7837   case Stmt::ConditionalOperatorClass: {
7838     const ConditionalOperator *C = cast<ConditionalOperator>(E);
7839 
7840     // Handle the GNU extension for missing LHS.
7841     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
7842     if (const Expr *LHSExpr = C->getLHS()) {
7843       // In C++, we can have a throw-expression, which has 'void' type.
7844       if (!LHSExpr->getType()->isVoidType())
7845         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
7846           return LHS;
7847     }
7848 
7849     // In C++, we can have a throw-expression, which has 'void' type.
7850     if (C->getRHS()->getType()->isVoidType())
7851       return nullptr;
7852 
7853     return EvalAddr(C->getRHS(), refVars, ParentDecl);
7854   }
7855 
7856   case Stmt::BlockExprClass:
7857     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7858       return E; // local block.
7859     return nullptr;
7860 
7861   case Stmt::AddrLabelExprClass:
7862     return E; // address of label.
7863 
7864   case Stmt::ExprWithCleanupsClass:
7865     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7866                     ParentDecl);
7867 
7868   // For casts, we need to handle conversions from arrays to
7869   // pointer values, and pointer-to-pointer conversions.
7870   case Stmt::ImplicitCastExprClass:
7871   case Stmt::CStyleCastExprClass:
7872   case Stmt::CXXFunctionalCastExprClass:
7873   case Stmt::ObjCBridgedCastExprClass:
7874   case Stmt::CXXStaticCastExprClass:
7875   case Stmt::CXXDynamicCastExprClass:
7876   case Stmt::CXXConstCastExprClass:
7877   case Stmt::CXXReinterpretCastExprClass: {
7878     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
7879     switch (cast<CastExpr>(E)->getCastKind()) {
7880     case CK_LValueToRValue:
7881     case CK_NoOp:
7882     case CK_BaseToDerived:
7883     case CK_DerivedToBase:
7884     case CK_UncheckedDerivedToBase:
7885     case CK_Dynamic:
7886     case CK_CPointerToObjCPointerCast:
7887     case CK_BlockPointerToObjCPointerCast:
7888     case CK_AnyPointerToBlockPointerCast:
7889       return EvalAddr(SubExpr, refVars, ParentDecl);
7890 
7891     case CK_ArrayToPointerDecay:
7892       return EvalVal(SubExpr, refVars, ParentDecl);
7893 
7894     case CK_BitCast:
7895       if (SubExpr->getType()->isAnyPointerType() ||
7896           SubExpr->getType()->isBlockPointerType() ||
7897           SubExpr->getType()->isObjCQualifiedIdType())
7898         return EvalAddr(SubExpr, refVars, ParentDecl);
7899       else
7900         return nullptr;
7901 
7902     default:
7903       return nullptr;
7904     }
7905   }
7906 
7907   case Stmt::MaterializeTemporaryExprClass:
7908     if (const Expr *Result =
7909             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7910                      refVars, ParentDecl))
7911       return Result;
7912     return E;
7913 
7914   // Everything else: we simply don't reason about them.
7915   default:
7916     return nullptr;
7917   }
7918 }
7919 
7920 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
7921 ///   See the comments for EvalAddr for more details.
7922 static const Expr *EvalVal(const Expr *E,
7923                            SmallVectorImpl<const DeclRefExpr *> &refVars,
7924                            const Decl *ParentDecl) {
7925   do {
7926     // We should only be called for evaluating non-pointer expressions, or
7927     // expressions with a pointer type that are not used as references but
7928     // instead
7929     // are l-values (e.g., DeclRefExpr with a pointer type).
7930 
7931     // Our "symbolic interpreter" is just a dispatch off the currently
7932     // viewed AST node.  We then recursively traverse the AST by calling
7933     // EvalAddr and EvalVal appropriately.
7934 
7935     E = E->IgnoreParens();
7936     switch (E->getStmtClass()) {
7937     case Stmt::ImplicitCastExprClass: {
7938       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
7939       if (IE->getValueKind() == VK_LValue) {
7940         E = IE->getSubExpr();
7941         continue;
7942       }
7943       return nullptr;
7944     }
7945 
7946     case Stmt::ExprWithCleanupsClass:
7947       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7948                      ParentDecl);
7949 
7950     case Stmt::DeclRefExprClass: {
7951       // When we hit a DeclRefExpr we are looking at code that refers to a
7952       // variable's name. If it's not a reference variable we check if it has
7953       // local storage within the function, and if so, return the expression.
7954       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7955 
7956       // If we leave the immediate function, the lifetime isn't about to end.
7957       if (DR->refersToEnclosingVariableOrCapture())
7958         return nullptr;
7959 
7960       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
7961         // Check if it refers to itself, e.g. "int& i = i;".
7962         if (V == ParentDecl)
7963           return DR;
7964 
7965         if (V->hasLocalStorage()) {
7966           if (!V->getType()->isReferenceType())
7967             return DR;
7968 
7969           // Reference variable, follow through to the expression that
7970           // it points to.
7971           if (V->hasInit()) {
7972             // Add the reference variable to the "trail".
7973             refVars.push_back(DR);
7974             return EvalVal(V->getInit(), refVars, V);
7975           }
7976         }
7977       }
7978 
7979       return nullptr;
7980     }
7981 
7982     case Stmt::UnaryOperatorClass: {
7983       // The only unary operator that make sense to handle here
7984       // is Deref.  All others don't resolve to a "name."  This includes
7985       // handling all sorts of rvalues passed to a unary operator.
7986       const UnaryOperator *U = cast<UnaryOperator>(E);
7987 
7988       if (U->getOpcode() == UO_Deref)
7989         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
7990 
7991       return nullptr;
7992     }
7993 
7994     case Stmt::ArraySubscriptExprClass: {
7995       // Array subscripts are potential references to data on the stack.  We
7996       // retrieve the DeclRefExpr* for the array variable if it indeed
7997       // has local storage.
7998       const auto *ASE = cast<ArraySubscriptExpr>(E);
7999       if (ASE->isTypeDependent())
8000         return nullptr;
8001       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
8002     }
8003 
8004     case Stmt::OMPArraySectionExprClass: {
8005       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
8006                       ParentDecl);
8007     }
8008 
8009     case Stmt::ConditionalOperatorClass: {
8010       // For conditional operators we need to see if either the LHS or RHS are
8011       // non-NULL Expr's.  If one is non-NULL, we return it.
8012       const ConditionalOperator *C = cast<ConditionalOperator>(E);
8013 
8014       // Handle the GNU extension for missing LHS.
8015       if (const Expr *LHSExpr = C->getLHS()) {
8016         // In C++, we can have a throw-expression, which has 'void' type.
8017         if (!LHSExpr->getType()->isVoidType())
8018           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
8019             return LHS;
8020       }
8021 
8022       // In C++, we can have a throw-expression, which has 'void' type.
8023       if (C->getRHS()->getType()->isVoidType())
8024         return nullptr;
8025 
8026       return EvalVal(C->getRHS(), refVars, ParentDecl);
8027     }
8028 
8029     // Accesses to members are potential references to data on the stack.
8030     case Stmt::MemberExprClass: {
8031       const MemberExpr *M = cast<MemberExpr>(E);
8032 
8033       // Check for indirect access.  We only want direct field accesses.
8034       if (M->isArrow())
8035         return nullptr;
8036 
8037       // Check whether the member type is itself a reference, in which case
8038       // we're not going to refer to the member, but to what the member refers
8039       // to.
8040       if (M->getMemberDecl()->getType()->isReferenceType())
8041         return nullptr;
8042 
8043       return EvalVal(M->getBase(), refVars, ParentDecl);
8044     }
8045 
8046     case Stmt::MaterializeTemporaryExprClass:
8047       if (const Expr *Result =
8048               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
8049                       refVars, ParentDecl))
8050         return Result;
8051       return E;
8052 
8053     default:
8054       // Check that we don't return or take the address of a reference to a
8055       // temporary. This is only useful in C++.
8056       if (!E->isTypeDependent() && E->isRValue())
8057         return E;
8058 
8059       // Everything else: we simply don't reason about them.
8060       return nullptr;
8061     }
8062   } while (true);
8063 }
8064 
8065 void
8066 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
8067                          SourceLocation ReturnLoc,
8068                          bool isObjCMethod,
8069                          const AttrVec *Attrs,
8070                          const FunctionDecl *FD) {
8071   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
8072 
8073   // Check if the return value is null but should not be.
8074   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
8075        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
8076       CheckNonNullExpr(*this, RetValExp))
8077     Diag(ReturnLoc, diag::warn_null_ret)
8078       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
8079 
8080   // C++11 [basic.stc.dynamic.allocation]p4:
8081   //   If an allocation function declared with a non-throwing
8082   //   exception-specification fails to allocate storage, it shall return
8083   //   a null pointer. Any other allocation function that fails to allocate
8084   //   storage shall indicate failure only by throwing an exception [...]
8085   if (FD) {
8086     OverloadedOperatorKind Op = FD->getOverloadedOperator();
8087     if (Op == OO_New || Op == OO_Array_New) {
8088       const FunctionProtoType *Proto
8089         = FD->getType()->castAs<FunctionProtoType>();
8090       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
8091           CheckNonNullExpr(*this, RetValExp))
8092         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
8093           << FD << getLangOpts().CPlusPlus11;
8094     }
8095   }
8096 }
8097 
8098 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
8099 
8100 /// Check for comparisons of floating point operands using != and ==.
8101 /// Issue a warning if these are no self-comparisons, as they are not likely
8102 /// to do what the programmer intended.
8103 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
8104   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
8105   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
8106 
8107   // Special case: check for x == x (which is OK).
8108   // Do not emit warnings for such cases.
8109   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
8110     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
8111       if (DRL->getDecl() == DRR->getDecl())
8112         return;
8113 
8114   // Special case: check for comparisons against literals that can be exactly
8115   //  represented by APFloat.  In such cases, do not emit a warning.  This
8116   //  is a heuristic: often comparison against such literals are used to
8117   //  detect if a value in a variable has not changed.  This clearly can
8118   //  lead to false negatives.
8119   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
8120     if (FLL->isExact())
8121       return;
8122   } else
8123     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
8124       if (FLR->isExact())
8125         return;
8126 
8127   // Check for comparisons with builtin types.
8128   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
8129     if (CL->getBuiltinCallee())
8130       return;
8131 
8132   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
8133     if (CR->getBuiltinCallee())
8134       return;
8135 
8136   // Emit the diagnostic.
8137   Diag(Loc, diag::warn_floatingpoint_eq)
8138     << LHS->getSourceRange() << RHS->getSourceRange();
8139 }
8140 
8141 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
8142 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
8143 
8144 namespace {
8145 
8146 /// Structure recording the 'active' range of an integer-valued
8147 /// expression.
8148 struct IntRange {
8149   /// The number of bits active in the int.
8150   unsigned Width;
8151 
8152   /// True if the int is known not to have negative values.
8153   bool NonNegative;
8154 
8155   IntRange(unsigned Width, bool NonNegative)
8156     : Width(Width), NonNegative(NonNegative)
8157   {}
8158 
8159   /// Returns the range of the bool type.
8160   static IntRange forBoolType() {
8161     return IntRange(1, true);
8162   }
8163 
8164   /// Returns the range of an opaque value of the given integral type.
8165   static IntRange forValueOfType(ASTContext &C, QualType T) {
8166     return forValueOfCanonicalType(C,
8167                           T->getCanonicalTypeInternal().getTypePtr());
8168   }
8169 
8170   /// Returns the range of an opaque value of a canonical integral type.
8171   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
8172     assert(T->isCanonicalUnqualified());
8173 
8174     if (const VectorType *VT = dyn_cast<VectorType>(T))
8175       T = VT->getElementType().getTypePtr();
8176     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8177       T = CT->getElementType().getTypePtr();
8178     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8179       T = AT->getValueType().getTypePtr();
8180 
8181     // For enum types, use the known bit width of the enumerators.
8182     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
8183       EnumDecl *Enum = ET->getDecl();
8184       // In C++11, enums without definitions can have an explicitly specified
8185       // underlying type.  Use this type to compute the range.
8186       if (!Enum->isCompleteDefinition())
8187         return IntRange(C.getIntWidth(QualType(T, 0)),
8188                         !ET->isSignedIntegerOrEnumerationType());
8189 
8190       unsigned NumPositive = Enum->getNumPositiveBits();
8191       unsigned NumNegative = Enum->getNumNegativeBits();
8192 
8193       if (NumNegative == 0)
8194         return IntRange(NumPositive, true/*NonNegative*/);
8195       else
8196         return IntRange(std::max(NumPositive + 1, NumNegative),
8197                         false/*NonNegative*/);
8198     }
8199 
8200     const BuiltinType *BT = cast<BuiltinType>(T);
8201     assert(BT->isInteger());
8202 
8203     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8204   }
8205 
8206   /// Returns the "target" range of a canonical integral type, i.e.
8207   /// the range of values expressible in the type.
8208   ///
8209   /// This matches forValueOfCanonicalType except that enums have the
8210   /// full range of their type, not the range of their enumerators.
8211   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
8212     assert(T->isCanonicalUnqualified());
8213 
8214     if (const VectorType *VT = dyn_cast<VectorType>(T))
8215       T = VT->getElementType().getTypePtr();
8216     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
8217       T = CT->getElementType().getTypePtr();
8218     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
8219       T = AT->getValueType().getTypePtr();
8220     if (const EnumType *ET = dyn_cast<EnumType>(T))
8221       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
8222 
8223     const BuiltinType *BT = cast<BuiltinType>(T);
8224     assert(BT->isInteger());
8225 
8226     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
8227   }
8228 
8229   /// Returns the supremum of two ranges: i.e. their conservative merge.
8230   static IntRange join(IntRange L, IntRange R) {
8231     return IntRange(std::max(L.Width, R.Width),
8232                     L.NonNegative && R.NonNegative);
8233   }
8234 
8235   /// Returns the infinum of two ranges: i.e. their aggressive merge.
8236   static IntRange meet(IntRange L, IntRange R) {
8237     return IntRange(std::min(L.Width, R.Width),
8238                     L.NonNegative || R.NonNegative);
8239   }
8240 };
8241 
8242 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
8243   if (value.isSigned() && value.isNegative())
8244     return IntRange(value.getMinSignedBits(), false);
8245 
8246   if (value.getBitWidth() > MaxWidth)
8247     value = value.trunc(MaxWidth);
8248 
8249   // isNonNegative() just checks the sign bit without considering
8250   // signedness.
8251   return IntRange(value.getActiveBits(), true);
8252 }
8253 
8254 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
8255                        unsigned MaxWidth) {
8256   if (result.isInt())
8257     return GetValueRange(C, result.getInt(), MaxWidth);
8258 
8259   if (result.isVector()) {
8260     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
8261     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
8262       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
8263       R = IntRange::join(R, El);
8264     }
8265     return R;
8266   }
8267 
8268   if (result.isComplexInt()) {
8269     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
8270     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
8271     return IntRange::join(R, I);
8272   }
8273 
8274   // This can happen with lossless casts to intptr_t of "based" lvalues.
8275   // Assume it might use arbitrary bits.
8276   // FIXME: The only reason we need to pass the type in here is to get
8277   // the sign right on this one case.  It would be nice if APValue
8278   // preserved this.
8279   assert(result.isLValue() || result.isAddrLabelDiff());
8280   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
8281 }
8282 
8283 QualType GetExprType(const Expr *E) {
8284   QualType Ty = E->getType();
8285   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
8286     Ty = AtomicRHS->getValueType();
8287   return Ty;
8288 }
8289 
8290 /// Pseudo-evaluate the given integer expression, estimating the
8291 /// range of values it might take.
8292 ///
8293 /// \param MaxWidth - the width to which the value will be truncated
8294 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
8295   E = E->IgnoreParens();
8296 
8297   // Try a full evaluation first.
8298   Expr::EvalResult result;
8299   if (E->EvaluateAsRValue(result, C))
8300     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
8301 
8302   // I think we only want to look through implicit casts here; if the
8303   // user has an explicit widening cast, we should treat the value as
8304   // being of the new, wider type.
8305   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8306     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8307       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8308 
8309     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8310 
8311     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8312                          CE->getCastKind() == CK_BooleanToSignedIntegral;
8313 
8314     // Assume that non-integer casts can span the full range of the type.
8315     if (!isIntegerCast)
8316       return OutputTypeRange;
8317 
8318     IntRange SubRange
8319       = GetExprRange(C, CE->getSubExpr(),
8320                      std::min(MaxWidth, OutputTypeRange.Width));
8321 
8322     // Bail out if the subexpr's range is as wide as the cast type.
8323     if (SubRange.Width >= OutputTypeRange.Width)
8324       return OutputTypeRange;
8325 
8326     // Otherwise, we take the smaller width, and we're non-negative if
8327     // either the output type or the subexpr is.
8328     return IntRange(SubRange.Width,
8329                     SubRange.NonNegative || OutputTypeRange.NonNegative);
8330   }
8331 
8332   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8333     // If we can fold the condition, just take that operand.
8334     bool CondResult;
8335     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8336       return GetExprRange(C, CondResult ? CO->getTrueExpr()
8337                                         : CO->getFalseExpr(),
8338                           MaxWidth);
8339 
8340     // Otherwise, conservatively merge.
8341     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8342     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8343     return IntRange::join(L, R);
8344   }
8345 
8346   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
8347     switch (BO->getOpcode()) {
8348 
8349     // Boolean-valued operations are single-bit and positive.
8350     case BO_LAnd:
8351     case BO_LOr:
8352     case BO_LT:
8353     case BO_GT:
8354     case BO_LE:
8355     case BO_GE:
8356     case BO_EQ:
8357     case BO_NE:
8358       return IntRange::forBoolType();
8359 
8360     // The type of the assignments is the type of the LHS, so the RHS
8361     // is not necessarily the same type.
8362     case BO_MulAssign:
8363     case BO_DivAssign:
8364     case BO_RemAssign:
8365     case BO_AddAssign:
8366     case BO_SubAssign:
8367     case BO_XorAssign:
8368     case BO_OrAssign:
8369       // TODO: bitfields?
8370       return IntRange::forValueOfType(C, GetExprType(E));
8371 
8372     // Simple assignments just pass through the RHS, which will have
8373     // been coerced to the LHS type.
8374     case BO_Assign:
8375       // TODO: bitfields?
8376       return GetExprRange(C, BO->getRHS(), MaxWidth);
8377 
8378     // Operations with opaque sources are black-listed.
8379     case BO_PtrMemD:
8380     case BO_PtrMemI:
8381       return IntRange::forValueOfType(C, GetExprType(E));
8382 
8383     // Bitwise-and uses the *infinum* of the two source ranges.
8384     case BO_And:
8385     case BO_AndAssign:
8386       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8387                             GetExprRange(C, BO->getRHS(), MaxWidth));
8388 
8389     // Left shift gets black-listed based on a judgement call.
8390     case BO_Shl:
8391       // ...except that we want to treat '1 << (blah)' as logically
8392       // positive.  It's an important idiom.
8393       if (IntegerLiteral *I
8394             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8395         if (I->getValue() == 1) {
8396           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8397           return IntRange(R.Width, /*NonNegative*/ true);
8398         }
8399       }
8400       // fallthrough
8401 
8402     case BO_ShlAssign:
8403       return IntRange::forValueOfType(C, GetExprType(E));
8404 
8405     // Right shift by a constant can narrow its left argument.
8406     case BO_Shr:
8407     case BO_ShrAssign: {
8408       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8409 
8410       // If the shift amount is a positive constant, drop the width by
8411       // that much.
8412       llvm::APSInt shift;
8413       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8414           shift.isNonNegative()) {
8415         unsigned zext = shift.getZExtValue();
8416         if (zext >= L.Width)
8417           L.Width = (L.NonNegative ? 0 : 1);
8418         else
8419           L.Width -= zext;
8420       }
8421 
8422       return L;
8423     }
8424 
8425     // Comma acts as its right operand.
8426     case BO_Comma:
8427       return GetExprRange(C, BO->getRHS(), MaxWidth);
8428 
8429     // Black-list pointer subtractions.
8430     case BO_Sub:
8431       if (BO->getLHS()->getType()->isPointerType())
8432         return IntRange::forValueOfType(C, GetExprType(E));
8433       break;
8434 
8435     // The width of a division result is mostly determined by the size
8436     // of the LHS.
8437     case BO_Div: {
8438       // Don't 'pre-truncate' the operands.
8439       unsigned opWidth = C.getIntWidth(GetExprType(E));
8440       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8441 
8442       // If the divisor is constant, use that.
8443       llvm::APSInt divisor;
8444       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8445         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
8446         if (log2 >= L.Width)
8447           L.Width = (L.NonNegative ? 0 : 1);
8448         else
8449           L.Width = std::min(L.Width - log2, MaxWidth);
8450         return L;
8451       }
8452 
8453       // Otherwise, just use the LHS's width.
8454       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8455       return IntRange(L.Width, L.NonNegative && R.NonNegative);
8456     }
8457 
8458     // The result of a remainder can't be larger than the result of
8459     // either side.
8460     case BO_Rem: {
8461       // Don't 'pre-truncate' the operands.
8462       unsigned opWidth = C.getIntWidth(GetExprType(E));
8463       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8464       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8465 
8466       IntRange meet = IntRange::meet(L, R);
8467       meet.Width = std::min(meet.Width, MaxWidth);
8468       return meet;
8469     }
8470 
8471     // The default behavior is okay for these.
8472     case BO_Mul:
8473     case BO_Add:
8474     case BO_Xor:
8475     case BO_Or:
8476       break;
8477     }
8478 
8479     // The default case is to treat the operation as if it were closed
8480     // on the narrowest type that encompasses both operands.
8481     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8482     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8483     return IntRange::join(L, R);
8484   }
8485 
8486   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
8487     switch (UO->getOpcode()) {
8488     // Boolean-valued operations are white-listed.
8489     case UO_LNot:
8490       return IntRange::forBoolType();
8491 
8492     // Operations with opaque sources are black-listed.
8493     case UO_Deref:
8494     case UO_AddrOf: // should be impossible
8495       return IntRange::forValueOfType(C, GetExprType(E));
8496 
8497     default:
8498       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8499     }
8500   }
8501 
8502   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8503     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8504 
8505   if (const auto *BitField = E->getSourceBitField())
8506     return IntRange(BitField->getBitWidthValue(C),
8507                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
8508 
8509   return IntRange::forValueOfType(C, GetExprType(E));
8510 }
8511 
8512 IntRange GetExprRange(ASTContext &C, const Expr *E) {
8513   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
8514 }
8515 
8516 /// Checks whether the given value, which currently has the given
8517 /// source semantics, has the same value when coerced through the
8518 /// target semantics.
8519 bool IsSameFloatAfterCast(const llvm::APFloat &value,
8520                           const llvm::fltSemantics &Src,
8521                           const llvm::fltSemantics &Tgt) {
8522   llvm::APFloat truncated = value;
8523 
8524   bool ignored;
8525   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8526   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8527 
8528   return truncated.bitwiseIsEqual(value);
8529 }
8530 
8531 /// Checks whether the given value, which currently has the given
8532 /// source semantics, has the same value when coerced through the
8533 /// target semantics.
8534 ///
8535 /// The value might be a vector of floats (or a complex number).
8536 bool IsSameFloatAfterCast(const APValue &value,
8537                           const llvm::fltSemantics &Src,
8538                           const llvm::fltSemantics &Tgt) {
8539   if (value.isFloat())
8540     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
8541 
8542   if (value.isVector()) {
8543     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
8544       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
8545         return false;
8546     return true;
8547   }
8548 
8549   assert(value.isComplexFloat());
8550   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
8551           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
8552 }
8553 
8554 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
8555 
8556 bool IsZero(Sema &S, Expr *E) {
8557   // Suppress cases where we are comparing against an enum constant.
8558   if (const DeclRefExpr *DR =
8559       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
8560     if (isa<EnumConstantDecl>(DR->getDecl()))
8561       return false;
8562 
8563   // Suppress cases where the '0' value is expanded from a macro.
8564   if (E->getLocStart().isMacroID())
8565     return false;
8566 
8567   llvm::APSInt Value;
8568   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
8569 }
8570 
8571 bool HasEnumType(Expr *E) {
8572   // Strip off implicit integral promotions.
8573   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8574     if (ICE->getCastKind() != CK_IntegralCast &&
8575         ICE->getCastKind() != CK_NoOp)
8576       break;
8577     E = ICE->getSubExpr();
8578   }
8579 
8580   return E->getType()->isEnumeralType();
8581 }
8582 
8583 bool isNonBooleanUnsignedValue(Expr *E) {
8584   // We are checking that the expression is not known to have boolean value,
8585   // is an integer type; and is either unsigned after implicit casts,
8586   // or was unsigned before implicit casts.
8587   return !E->isKnownToHaveBooleanValue() && E->getType()->isIntegerType() &&
8588          (!E->getType()->isSignedIntegerType() ||
8589           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
8590 }
8591 
8592 bool CheckTautologicalComparisonWithZero(Sema &S, BinaryOperator *E) {
8593   // Disable warning in template instantiations.
8594   if (S.inTemplateInstantiation())
8595     return false;
8596 
8597   // bool values are handled by DiagnoseOutOfRangeComparison().
8598 
8599   BinaryOperatorKind Op = E->getOpcode();
8600   if (E->isValueDependent())
8601     return false;
8602 
8603   Expr *LHS = E->getLHS();
8604   Expr *RHS = E->getRHS();
8605 
8606   bool Match = true;
8607 
8608   if (Op == BO_LT && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
8609     S.Diag(E->getOperatorLoc(),
8610            HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8611                             : diag::warn_lunsigned_always_true_comparison)
8612         << "< 0" << false << LHS->getSourceRange() << RHS->getSourceRange();
8613   } else if (Op == BO_GE && isNonBooleanUnsignedValue(LHS) && IsZero(S, RHS)) {
8614     S.Diag(E->getOperatorLoc(),
8615            HasEnumType(LHS) ? diag::warn_lunsigned_enum_always_true_comparison
8616                             : diag::warn_lunsigned_always_true_comparison)
8617         << ">= 0" << true << LHS->getSourceRange() << RHS->getSourceRange();
8618   } else if (Op == BO_GT && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
8619     S.Diag(E->getOperatorLoc(),
8620            HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8621                             : diag::warn_runsigned_always_true_comparison)
8622         << "0 >" << false << LHS->getSourceRange() << RHS->getSourceRange();
8623   } else if (Op == BO_LE && isNonBooleanUnsignedValue(RHS) && IsZero(S, LHS)) {
8624     S.Diag(E->getOperatorLoc(),
8625            HasEnumType(RHS) ? diag::warn_runsigned_enum_always_true_comparison
8626                             : diag::warn_runsigned_always_true_comparison)
8627         << "0 <=" << true << LHS->getSourceRange() << RHS->getSourceRange();
8628   } else
8629     Match = false;
8630 
8631   return Match;
8632 }
8633 
8634 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E, Expr *Constant,
8635                                   Expr *Other, const llvm::APSInt &Value,
8636                                   bool RhsConstant) {
8637   // Disable warning in template instantiations.
8638   if (S.inTemplateInstantiation())
8639     return;
8640 
8641   // TODO: Investigate using GetExprRange() to get tighter bounds
8642   // on the bit ranges.
8643   QualType OtherT = Other->getType();
8644   if (const auto *AT = OtherT->getAs<AtomicType>())
8645     OtherT = AT->getValueType();
8646   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
8647   unsigned OtherWidth = OtherRange.Width;
8648 
8649   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
8650 
8651   // 0 values are handled later by CheckTautologicalComparisonWithZero().
8652   if ((Value == 0) && (!OtherIsBooleanType))
8653     return;
8654 
8655   BinaryOperatorKind op = E->getOpcode();
8656   bool IsTrue = true;
8657 
8658   // Used for diagnostic printout.
8659   enum {
8660     LiteralConstant = 0,
8661     CXXBoolLiteralTrue,
8662     CXXBoolLiteralFalse
8663   } LiteralOrBoolConstant = LiteralConstant;
8664 
8665   if (!OtherIsBooleanType) {
8666     QualType ConstantT = Constant->getType();
8667     QualType CommonT = E->getLHS()->getType();
8668 
8669     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
8670       return;
8671     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
8672            "comparison with non-integer type");
8673 
8674     bool ConstantSigned = ConstantT->isSignedIntegerType();
8675     bool CommonSigned = CommonT->isSignedIntegerType();
8676 
8677     bool EqualityOnly = false;
8678 
8679     if (CommonSigned) {
8680       // The common type is signed, therefore no signed to unsigned conversion.
8681       if (!OtherRange.NonNegative) {
8682         // Check that the constant is representable in type OtherT.
8683         if (ConstantSigned) {
8684           if (OtherWidth >= Value.getMinSignedBits())
8685             return;
8686         } else { // !ConstantSigned
8687           if (OtherWidth >= Value.getActiveBits() + 1)
8688             return;
8689         }
8690       } else { // !OtherSigned
8691                // Check that the constant is representable in type OtherT.
8692         // Negative values are out of range.
8693         if (ConstantSigned) {
8694           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8695             return;
8696         } else { // !ConstantSigned
8697           if (OtherWidth >= Value.getActiveBits())
8698             return;
8699         }
8700       }
8701     } else { // !CommonSigned
8702       if (OtherRange.NonNegative) {
8703         if (OtherWidth >= Value.getActiveBits())
8704           return;
8705       } else { // OtherSigned
8706         assert(!ConstantSigned &&
8707                "Two signed types converted to unsigned types.");
8708         // Check to see if the constant is representable in OtherT.
8709         if (OtherWidth > Value.getActiveBits())
8710           return;
8711         // Check to see if the constant is equivalent to a negative value
8712         // cast to CommonT.
8713         if (S.Context.getIntWidth(ConstantT) ==
8714                 S.Context.getIntWidth(CommonT) &&
8715             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8716           return;
8717         // The constant value rests between values that OtherT can represent
8718         // after conversion.  Relational comparison still works, but equality
8719         // comparisons will be tautological.
8720         EqualityOnly = true;
8721       }
8722     }
8723 
8724     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8725 
8726     if (op == BO_EQ || op == BO_NE) {
8727       IsTrue = op == BO_NE;
8728     } else if (EqualityOnly) {
8729       return;
8730     } else if (RhsConstant) {
8731       if (op == BO_GT || op == BO_GE)
8732         IsTrue = !PositiveConstant;
8733       else // op == BO_LT || op == BO_LE
8734         IsTrue = PositiveConstant;
8735     } else {
8736       if (op == BO_LT || op == BO_LE)
8737         IsTrue = !PositiveConstant;
8738       else // op == BO_GT || op == BO_GE
8739         IsTrue = PositiveConstant;
8740     }
8741   } else {
8742     // Other isKnownToHaveBooleanValue
8743     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8744     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8745     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8746 
8747     static const struct LinkedConditions {
8748       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8749       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8750       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8751       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8752       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8753       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8754 
8755     } TruthTable = {
8756         // Constant on LHS.              | Constant on RHS.              |
8757         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
8758         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8759         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8760         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8761         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8762         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8763         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8764       };
8765 
8766     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8767 
8768     enum ConstantValue ConstVal = Zero;
8769     if (Value.isUnsigned() || Value.isNonNegative()) {
8770       if (Value == 0) {
8771         LiteralOrBoolConstant =
8772             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8773         ConstVal = Zero;
8774       } else if (Value == 1) {
8775         LiteralOrBoolConstant =
8776             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8777         ConstVal = One;
8778       } else {
8779         LiteralOrBoolConstant = LiteralConstant;
8780         ConstVal = GT_One;
8781       }
8782     } else {
8783       ConstVal = LT_Zero;
8784     }
8785 
8786     CompareBoolWithConstantResult CmpRes;
8787 
8788     switch (op) {
8789     case BO_LT:
8790       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8791       break;
8792     case BO_GT:
8793       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8794       break;
8795     case BO_LE:
8796       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8797       break;
8798     case BO_GE:
8799       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8800       break;
8801     case BO_EQ:
8802       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8803       break;
8804     case BO_NE:
8805       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8806       break;
8807     default:
8808       CmpRes = Unkwn;
8809       break;
8810     }
8811 
8812     if (CmpRes == AFals) {
8813       IsTrue = false;
8814     } else if (CmpRes == ATrue) {
8815       IsTrue = true;
8816     } else {
8817       return;
8818     }
8819   }
8820 
8821   // If this is a comparison to an enum constant, include that
8822   // constant in the diagnostic.
8823   const EnumConstantDecl *ED = nullptr;
8824   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8825     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8826 
8827   SmallString<64> PrettySourceValue;
8828   llvm::raw_svector_ostream OS(PrettySourceValue);
8829   if (ED)
8830     OS << '\'' << *ED << "' (" << Value << ")";
8831   else
8832     OS << Value;
8833 
8834   S.DiagRuntimeBehavior(
8835     E->getOperatorLoc(), E,
8836     S.PDiag(diag::warn_out_of_range_compare)
8837         << OS.str() << LiteralOrBoolConstant
8838         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
8839         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
8840 }
8841 
8842 /// Analyze the operands of the given comparison.  Implements the
8843 /// fallback case from AnalyzeComparison.
8844 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
8845   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
8846   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
8847 }
8848 
8849 /// \brief Implements -Wsign-compare.
8850 ///
8851 /// \param E the binary operator to check for warnings
8852 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
8853   // The type the comparison is being performed in.
8854   QualType T = E->getLHS()->getType();
8855 
8856   // Only analyze comparison operators where both sides have been converted to
8857   // the same type.
8858   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
8859     return AnalyzeImpConvsInComparison(S, E);
8860 
8861   // Don't analyze value-dependent comparisons directly.
8862   if (E->isValueDependent())
8863     return AnalyzeImpConvsInComparison(S, E);
8864 
8865   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
8866   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
8867 
8868   bool IsComparisonConstant = false;
8869 
8870   // Check whether an integer constant comparison results in a value
8871   // of 'true' or 'false'.
8872   if (T->isIntegralType(S.Context)) {
8873     llvm::APSInt RHSValue;
8874     bool IsRHSIntegralLiteral =
8875       RHS->isIntegerConstantExpr(RHSValue, S.Context);
8876     llvm::APSInt LHSValue;
8877     bool IsLHSIntegralLiteral =
8878       LHS->isIntegerConstantExpr(LHSValue, S.Context);
8879     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8880         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
8881     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8882       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
8883     else
8884       IsComparisonConstant =
8885         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8886   } else if (!T->hasUnsignedIntegerRepresentation())
8887       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
8888 
8889   // We don't care about value-dependent expressions or expressions
8890   // whose result is a constant.
8891   if (IsComparisonConstant)
8892     return AnalyzeImpConvsInComparison(S, E);
8893 
8894   // If this is a tautological comparison, suppress -Wsign-compare.
8895   if (CheckTautologicalComparisonWithZero(S, E))
8896     return AnalyzeImpConvsInComparison(S, E);
8897 
8898   // We don't do anything special if this isn't an unsigned integral
8899   // comparison:  we're only interested in integral comparisons, and
8900   // signed comparisons only happen in cases we don't care to warn about.
8901   if (!T->hasUnsignedIntegerRepresentation())
8902     return AnalyzeImpConvsInComparison(S, E);
8903 
8904   // Check to see if one of the (unmodified) operands is of different
8905   // signedness.
8906   Expr *signedOperand, *unsignedOperand;
8907   if (LHS->getType()->hasSignedIntegerRepresentation()) {
8908     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
8909            "unsigned comparison between two signed integer expressions?");
8910     signedOperand = LHS;
8911     unsignedOperand = RHS;
8912   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
8913     signedOperand = RHS;
8914     unsignedOperand = LHS;
8915   } else {
8916     return AnalyzeImpConvsInComparison(S, E);
8917   }
8918 
8919   // Otherwise, calculate the effective range of the signed operand.
8920   IntRange signedRange = GetExprRange(S.Context, signedOperand);
8921 
8922   // Go ahead and analyze implicit conversions in the operands.  Note
8923   // that we skip the implicit conversions on both sides.
8924   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
8925   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
8926 
8927   // If the signed range is non-negative, -Wsign-compare won't fire.
8928   if (signedRange.NonNegative)
8929     return;
8930 
8931   // For (in)equality comparisons, if the unsigned operand is a
8932   // constant which cannot collide with a overflowed signed operand,
8933   // then reinterpreting the signed operand as unsigned will not
8934   // change the result of the comparison.
8935   if (E->isEqualityOp()) {
8936     unsigned comparisonWidth = S.Context.getIntWidth(T);
8937     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
8938 
8939     // We should never be unable to prove that the unsigned operand is
8940     // non-negative.
8941     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
8942 
8943     if (unsignedRange.Width < comparisonWidth)
8944       return;
8945   }
8946 
8947   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
8948     S.PDiag(diag::warn_mixed_sign_comparison)
8949       << LHS->getType() << RHS->getType()
8950       << LHS->getSourceRange() << RHS->getSourceRange());
8951 }
8952 
8953 /// Analyzes an attempt to assign the given value to a bitfield.
8954 ///
8955 /// Returns true if there was something fishy about the attempt.
8956 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
8957                                SourceLocation InitLoc) {
8958   assert(Bitfield->isBitField());
8959   if (Bitfield->isInvalidDecl())
8960     return false;
8961 
8962   // White-list bool bitfields.
8963   QualType BitfieldType = Bitfield->getType();
8964   if (BitfieldType->isBooleanType())
8965      return false;
8966 
8967   if (BitfieldType->isEnumeralType()) {
8968     EnumDecl *BitfieldEnumDecl = BitfieldType->getAs<EnumType>()->getDecl();
8969     // If the underlying enum type was not explicitly specified as an unsigned
8970     // type and the enum contain only positive values, MSVC++ will cause an
8971     // inconsistency by storing this as a signed type.
8972     if (S.getLangOpts().CPlusPlus11 &&
8973         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
8974         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
8975         BitfieldEnumDecl->getNumNegativeBits() == 0) {
8976       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8977         << BitfieldEnumDecl->getNameAsString();
8978     }
8979   }
8980 
8981   if (Bitfield->getType()->isBooleanType())
8982     return false;
8983 
8984   // Ignore value- or type-dependent expressions.
8985   if (Bitfield->getBitWidth()->isValueDependent() ||
8986       Bitfield->getBitWidth()->isTypeDependent() ||
8987       Init->isValueDependent() ||
8988       Init->isTypeDependent())
8989     return false;
8990 
8991   Expr *OriginalInit = Init->IgnoreParenImpCasts();
8992   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
8993 
8994   llvm::APSInt Value;
8995   if (!OriginalInit->EvaluateAsInt(Value, S.Context,
8996                                    Expr::SE_AllowSideEffects)) {
8997     // The RHS is not constant.  If the RHS has an enum type, make sure the
8998     // bitfield is wide enough to hold all the values of the enum without
8999     // truncation.
9000     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
9001       EnumDecl *ED = EnumTy->getDecl();
9002       bool SignedBitfield = BitfieldType->isSignedIntegerType();
9003 
9004       // Enum types are implicitly signed on Windows, so check if there are any
9005       // negative enumerators to see if the enum was intended to be signed or
9006       // not.
9007       bool SignedEnum = ED->getNumNegativeBits() > 0;
9008 
9009       // Check for surprising sign changes when assigning enum values to a
9010       // bitfield of different signedness.  If the bitfield is signed and we
9011       // have exactly the right number of bits to store this unsigned enum,
9012       // suggest changing the enum to an unsigned type. This typically happens
9013       // on Windows where unfixed enums always use an underlying type of 'int'.
9014       unsigned DiagID = 0;
9015       if (SignedEnum && !SignedBitfield) {
9016         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
9017       } else if (SignedBitfield && !SignedEnum &&
9018                  ED->getNumPositiveBits() == FieldWidth) {
9019         DiagID = diag::warn_signed_bitfield_enum_conversion;
9020       }
9021 
9022       if (DiagID) {
9023         S.Diag(InitLoc, DiagID) << Bitfield << ED;
9024         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
9025         SourceRange TypeRange =
9026             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
9027         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
9028             << SignedEnum << TypeRange;
9029       }
9030 
9031       // Compute the required bitwidth. If the enum has negative values, we need
9032       // one more bit than the normal number of positive bits to represent the
9033       // sign bit.
9034       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
9035                                                   ED->getNumNegativeBits())
9036                                        : ED->getNumPositiveBits();
9037 
9038       // Check the bitwidth.
9039       if (BitsNeeded > FieldWidth) {
9040         Expr *WidthExpr = Bitfield->getBitWidth();
9041         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
9042             << Bitfield << ED;
9043         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
9044             << BitsNeeded << ED << WidthExpr->getSourceRange();
9045       }
9046     }
9047 
9048     return false;
9049   }
9050 
9051   unsigned OriginalWidth = Value.getBitWidth();
9052 
9053   if (!Value.isSigned() || Value.isNegative())
9054     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
9055       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
9056         OriginalWidth = Value.getMinSignedBits();
9057 
9058   if (OriginalWidth <= FieldWidth)
9059     return false;
9060 
9061   // Compute the value which the bitfield will contain.
9062   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
9063   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
9064 
9065   // Check whether the stored value is equal to the original value.
9066   TruncatedValue = TruncatedValue.extend(OriginalWidth);
9067   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
9068     return false;
9069 
9070   // Special-case bitfields of width 1: booleans are naturally 0/1, and
9071   // therefore don't strictly fit into a signed bitfield of width 1.
9072   if (FieldWidth == 1 && Value == 1)
9073     return false;
9074 
9075   std::string PrettyValue = Value.toString(10);
9076   std::string PrettyTrunc = TruncatedValue.toString(10);
9077 
9078   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
9079     << PrettyValue << PrettyTrunc << OriginalInit->getType()
9080     << Init->getSourceRange();
9081 
9082   return true;
9083 }
9084 
9085 /// Analyze the given simple or compound assignment for warning-worthy
9086 /// operations.
9087 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
9088   // Just recurse on the LHS.
9089   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
9090 
9091   // We want to recurse on the RHS as normal unless we're assigning to
9092   // a bitfield.
9093   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
9094     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
9095                                   E->getOperatorLoc())) {
9096       // Recurse, ignoring any implicit conversions on the RHS.
9097       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
9098                                         E->getOperatorLoc());
9099     }
9100   }
9101 
9102   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
9103 }
9104 
9105 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9106 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
9107                      SourceLocation CContext, unsigned diag,
9108                      bool pruneControlFlow = false) {
9109   if (pruneControlFlow) {
9110     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9111                           S.PDiag(diag)
9112                             << SourceType << T << E->getSourceRange()
9113                             << SourceRange(CContext));
9114     return;
9115   }
9116   S.Diag(E->getExprLoc(), diag)
9117     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
9118 }
9119 
9120 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
9121 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
9122                      unsigned diag, bool pruneControlFlow = false) {
9123   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
9124 }
9125 
9126 
9127 /// Diagnose an implicit cast from a floating point value to an integer value.
9128 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
9129 
9130                              SourceLocation CContext) {
9131   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
9132   const bool PruneWarnings = S.inTemplateInstantiation();
9133 
9134   Expr *InnerE = E->IgnoreParenImpCasts();
9135   // We also want to warn on, e.g., "int i = -1.234"
9136   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
9137     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
9138       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
9139 
9140   const bool IsLiteral =
9141       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
9142 
9143   llvm::APFloat Value(0.0);
9144   bool IsConstant =
9145     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
9146   if (!IsConstant) {
9147     return DiagnoseImpCast(S, E, T, CContext,
9148                            diag::warn_impcast_float_integer, PruneWarnings);
9149   }
9150 
9151   bool isExact = false;
9152 
9153   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
9154                             T->hasUnsignedIntegerRepresentation());
9155   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
9156                              &isExact) == llvm::APFloat::opOK &&
9157       isExact) {
9158     if (IsLiteral) return;
9159     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
9160                            PruneWarnings);
9161   }
9162 
9163   unsigned DiagID = 0;
9164   if (IsLiteral) {
9165     // Warn on floating point literal to integer.
9166     DiagID = diag::warn_impcast_literal_float_to_integer;
9167   } else if (IntegerValue == 0) {
9168     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
9169       return DiagnoseImpCast(S, E, T, CContext,
9170                              diag::warn_impcast_float_integer, PruneWarnings);
9171     }
9172     // Warn on non-zero to zero conversion.
9173     DiagID = diag::warn_impcast_float_to_integer_zero;
9174   } else {
9175     if (IntegerValue.isUnsigned()) {
9176       if (!IntegerValue.isMaxValue()) {
9177         return DiagnoseImpCast(S, E, T, CContext,
9178                                diag::warn_impcast_float_integer, PruneWarnings);
9179       }
9180     } else {  // IntegerValue.isSigned()
9181       if (!IntegerValue.isMaxSignedValue() &&
9182           !IntegerValue.isMinSignedValue()) {
9183         return DiagnoseImpCast(S, E, T, CContext,
9184                                diag::warn_impcast_float_integer, PruneWarnings);
9185       }
9186     }
9187     // Warn on evaluatable floating point expression to integer conversion.
9188     DiagID = diag::warn_impcast_float_to_integer;
9189   }
9190 
9191   // FIXME: Force the precision of the source value down so we don't print
9192   // digits which are usually useless (we don't really care here if we
9193   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
9194   // would automatically print the shortest representation, but it's a bit
9195   // tricky to implement.
9196   SmallString<16> PrettySourceValue;
9197   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9198   precision = (precision * 59 + 195) / 196;
9199   Value.toString(PrettySourceValue, precision);
9200 
9201   SmallString<16> PrettyTargetValue;
9202   if (IsBool)
9203     PrettyTargetValue = Value.isZero() ? "false" : "true";
9204   else
9205     IntegerValue.toString(PrettyTargetValue);
9206 
9207   if (PruneWarnings) {
9208     S.DiagRuntimeBehavior(E->getExprLoc(), E,
9209                           S.PDiag(DiagID)
9210                               << E->getType() << T.getUnqualifiedType()
9211                               << PrettySourceValue << PrettyTargetValue
9212                               << E->getSourceRange() << SourceRange(CContext));
9213   } else {
9214     S.Diag(E->getExprLoc(), DiagID)
9215         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
9216         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
9217   }
9218 }
9219 
9220 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
9221   if (!Range.Width) return "0";
9222 
9223   llvm::APSInt ValueInRange = Value;
9224   ValueInRange.setIsSigned(!Range.NonNegative);
9225   ValueInRange = ValueInRange.trunc(Range.Width);
9226   return ValueInRange.toString(10);
9227 }
9228 
9229 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
9230   if (!isa<ImplicitCastExpr>(Ex))
9231     return false;
9232 
9233   Expr *InnerE = Ex->IgnoreParenImpCasts();
9234   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
9235   const Type *Source =
9236     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
9237   if (Target->isDependentType())
9238     return false;
9239 
9240   const BuiltinType *FloatCandidateBT =
9241     dyn_cast<BuiltinType>(ToBool ? Source : Target);
9242   const Type *BoolCandidateType = ToBool ? Target : Source;
9243 
9244   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9245           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
9246 }
9247 
9248 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
9249                                       SourceLocation CC) {
9250   unsigned NumArgs = TheCall->getNumArgs();
9251   for (unsigned i = 0; i < NumArgs; ++i) {
9252     Expr *CurrA = TheCall->getArg(i);
9253     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
9254       continue;
9255 
9256     bool IsSwapped = ((i > 0) &&
9257         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
9258     IsSwapped |= ((i < (NumArgs - 1)) &&
9259         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
9260     if (IsSwapped) {
9261       // Warn on this floating-point to bool conversion.
9262       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
9263                       CurrA->getType(), CC,
9264                       diag::warn_impcast_floating_point_to_bool);
9265     }
9266   }
9267 }
9268 
9269 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
9270   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
9271                         E->getExprLoc()))
9272     return;
9273 
9274   // Don't warn on functions which have return type nullptr_t.
9275   if (isa<CallExpr>(E))
9276     return;
9277 
9278   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
9279   const Expr::NullPointerConstantKind NullKind =
9280       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
9281   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
9282     return;
9283 
9284   // Return if target type is a safe conversion.
9285   if (T->isAnyPointerType() || T->isBlockPointerType() ||
9286       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
9287     return;
9288 
9289   SourceLocation Loc = E->getSourceRange().getBegin();
9290 
9291   // Venture through the macro stacks to get to the source of macro arguments.
9292   // The new location is a better location than the complete location that was
9293   // passed in.
9294   while (S.SourceMgr.isMacroArgExpansion(Loc))
9295     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
9296 
9297   while (S.SourceMgr.isMacroArgExpansion(CC))
9298     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
9299 
9300   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
9301   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
9302     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
9303         Loc, S.SourceMgr, S.getLangOpts());
9304     if (MacroName == "NULL")
9305       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
9306   }
9307 
9308   // Only warn if the null and context location are in the same macro expansion.
9309   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
9310     return;
9311 
9312   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9313       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
9314       << FixItHint::CreateReplacement(Loc,
9315                                       S.getFixItZeroLiteralForType(T, Loc));
9316 }
9317 
9318 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9319                            ObjCArrayLiteral *ArrayLiteral);
9320 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9321                                 ObjCDictionaryLiteral *DictionaryLiteral);
9322 
9323 /// Check a single element within a collection literal against the
9324 /// target element type.
9325 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
9326                                        Expr *Element, unsigned ElementKind) {
9327   // Skip a bitcast to 'id' or qualified 'id'.
9328   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9329     if (ICE->getCastKind() == CK_BitCast &&
9330         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
9331       Element = ICE->getSubExpr();
9332   }
9333 
9334   QualType ElementType = Element->getType();
9335   ExprResult ElementResult(Element);
9336   if (ElementType->getAs<ObjCObjectPointerType>() &&
9337       S.CheckSingleAssignmentConstraints(TargetElementType,
9338                                          ElementResult,
9339                                          false, false)
9340         != Sema::Compatible) {
9341     S.Diag(Element->getLocStart(),
9342            diag::warn_objc_collection_literal_element)
9343       << ElementType << ElementKind << TargetElementType
9344       << Element->getSourceRange();
9345   }
9346 
9347   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9348     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9349   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9350     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9351 }
9352 
9353 /// Check an Objective-C array literal being converted to the given
9354 /// target type.
9355 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
9356                            ObjCArrayLiteral *ArrayLiteral) {
9357   if (!S.NSArrayDecl)
9358     return;
9359 
9360   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9361   if (!TargetObjCPtr)
9362     return;
9363 
9364   if (TargetObjCPtr->isUnspecialized() ||
9365       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9366         != S.NSArrayDecl->getCanonicalDecl())
9367     return;
9368 
9369   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9370   if (TypeArgs.size() != 1)
9371     return;
9372 
9373   QualType TargetElementType = TypeArgs[0];
9374   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
9375     checkObjCCollectionLiteralElement(S, TargetElementType,
9376                                       ArrayLiteral->getElement(I),
9377                                       0);
9378   }
9379 }
9380 
9381 /// Check an Objective-C dictionary literal being converted to the given
9382 /// target type.
9383 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
9384                                 ObjCDictionaryLiteral *DictionaryLiteral) {
9385   if (!S.NSDictionaryDecl)
9386     return;
9387 
9388   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
9389   if (!TargetObjCPtr)
9390     return;
9391 
9392   if (TargetObjCPtr->isUnspecialized() ||
9393       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9394         != S.NSDictionaryDecl->getCanonicalDecl())
9395     return;
9396 
9397   auto TypeArgs = TargetObjCPtr->getTypeArgs();
9398   if (TypeArgs.size() != 2)
9399     return;
9400 
9401   QualType TargetKeyType = TypeArgs[0];
9402   QualType TargetObjectType = TypeArgs[1];
9403   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
9404     auto Element = DictionaryLiteral->getKeyValueElement(I);
9405     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9406     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9407   }
9408 }
9409 
9410 // Helper function to filter out cases for constant width constant conversion.
9411 // Don't warn on char array initialization or for non-decimal values.
9412 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
9413                                    SourceLocation CC) {
9414   // If initializing from a constant, and the constant starts with '0',
9415   // then it is a binary, octal, or hexadecimal.  Allow these constants
9416   // to fill all the bits, even if there is a sign change.
9417   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
9418     const char FirstLiteralCharacter =
9419         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
9420     if (FirstLiteralCharacter == '0')
9421       return false;
9422   }
9423 
9424   // If the CC location points to a '{', and the type is char, then assume
9425   // assume it is an array initialization.
9426   if (CC.isValid() && T->isCharType()) {
9427     const char FirstContextCharacter =
9428         S.getSourceManager().getCharacterData(CC)[0];
9429     if (FirstContextCharacter == '{')
9430       return false;
9431   }
9432 
9433   return true;
9434 }
9435 
9436 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
9437                              SourceLocation CC, bool *ICContext = nullptr) {
9438   if (E->isTypeDependent() || E->isValueDependent()) return;
9439 
9440   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
9441   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
9442   if (Source == Target) return;
9443   if (Target->isDependentType()) return;
9444 
9445   // If the conversion context location is invalid don't complain. We also
9446   // don't want to emit a warning if the issue occurs from the expansion of
9447   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
9448   // delay this check as long as possible. Once we detect we are in that
9449   // scenario, we just return.
9450   if (CC.isInvalid())
9451     return;
9452 
9453   // Diagnose implicit casts to bool.
9454   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
9455     if (isa<StringLiteral>(E))
9456       // Warn on string literal to bool.  Checks for string literals in logical
9457       // and expressions, for instance, assert(0 && "error here"), are
9458       // prevented by a check in AnalyzeImplicitConversions().
9459       return DiagnoseImpCast(S, E, T, CC,
9460                              diag::warn_impcast_string_literal_to_bool);
9461     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
9462         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
9463       // This covers the literal expressions that evaluate to Objective-C
9464       // objects.
9465       return DiagnoseImpCast(S, E, T, CC,
9466                              diag::warn_impcast_objective_c_literal_to_bool);
9467     }
9468     if (Source->isPointerType() || Source->canDecayToPointerType()) {
9469       // Warn on pointer to bool conversion that is always true.
9470       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
9471                                      SourceRange(CC));
9472     }
9473   }
9474 
9475   // Check implicit casts from Objective-C collection literals to specialized
9476   // collection types, e.g., NSArray<NSString *> *.
9477   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9478     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
9479   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9480     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
9481 
9482   // Strip vector types.
9483   if (isa<VectorType>(Source)) {
9484     if (!isa<VectorType>(Target)) {
9485       if (S.SourceMgr.isInSystemMacro(CC))
9486         return;
9487       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9488     }
9489 
9490     // If the vector cast is cast between two vectors of the same size, it is
9491     // a bitcast, not a conversion.
9492     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
9493       return;
9494 
9495     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9496     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9497   }
9498   if (auto VecTy = dyn_cast<VectorType>(Target))
9499     Target = VecTy->getElementType().getTypePtr();
9500 
9501   // Strip complex types.
9502   if (isa<ComplexType>(Source)) {
9503     if (!isa<ComplexType>(Target)) {
9504       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
9505         return;
9506 
9507       return DiagnoseImpCast(S, E, T, CC,
9508                              S.getLangOpts().CPlusPlus
9509                                  ? diag::err_impcast_complex_scalar
9510                                  : diag::warn_impcast_complex_scalar);
9511     }
9512 
9513     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9514     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9515   }
9516 
9517   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
9518   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
9519 
9520   // If the source is floating point...
9521   if (SourceBT && SourceBT->isFloatingPoint()) {
9522     // ...and the target is floating point...
9523     if (TargetBT && TargetBT->isFloatingPoint()) {
9524       // ...then warn if we're dropping FP rank.
9525 
9526       // Builtin FP kinds are ordered by increasing FP rank.
9527       if (SourceBT->getKind() > TargetBT->getKind()) {
9528         // Don't warn about float constants that are precisely
9529         // representable in the target type.
9530         Expr::EvalResult result;
9531         if (E->EvaluateAsRValue(result, S.Context)) {
9532           // Value might be a float, a float vector, or a float complex.
9533           if (IsSameFloatAfterCast(result.Val,
9534                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
9535                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
9536             return;
9537         }
9538 
9539         if (S.SourceMgr.isInSystemMacro(CC))
9540           return;
9541 
9542         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9543       }
9544       // ... or possibly if we're increasing rank, too
9545       else if (TargetBT->getKind() > SourceBT->getKind()) {
9546         if (S.SourceMgr.isInSystemMacro(CC))
9547           return;
9548 
9549         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9550       }
9551       return;
9552     }
9553 
9554     // If the target is integral, always warn.
9555     if (TargetBT && TargetBT->isInteger()) {
9556       if (S.SourceMgr.isInSystemMacro(CC))
9557         return;
9558 
9559       DiagnoseFloatingImpCast(S, E, T, CC);
9560     }
9561 
9562     // Detect the case where a call result is converted from floating-point to
9563     // to bool, and the final argument to the call is converted from bool, to
9564     // discover this typo:
9565     //
9566     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
9567     //
9568     // FIXME: This is an incredibly special case; is there some more general
9569     // way to detect this class of misplaced-parentheses bug?
9570     if (Target->isBooleanType() && isa<CallExpr>(E)) {
9571       // Check last argument of function call to see if it is an
9572       // implicit cast from a type matching the type the result
9573       // is being cast to.
9574       CallExpr *CEx = cast<CallExpr>(E);
9575       if (unsigned NumArgs = CEx->getNumArgs()) {
9576         Expr *LastA = CEx->getArg(NumArgs - 1);
9577         Expr *InnerE = LastA->IgnoreParenImpCasts();
9578         if (isa<ImplicitCastExpr>(LastA) &&
9579             InnerE->getType()->isBooleanType()) {
9580           // Warn on this floating-point to bool conversion
9581           DiagnoseImpCast(S, E, T, CC,
9582                           diag::warn_impcast_floating_point_to_bool);
9583         }
9584       }
9585     }
9586     return;
9587   }
9588 
9589   DiagnoseNullConversion(S, E, T, CC);
9590 
9591   S.DiscardMisalignedMemberAddress(Target, E);
9592 
9593   if (!Source->isIntegerType() || !Target->isIntegerType())
9594     return;
9595 
9596   // TODO: remove this early return once the false positives for constant->bool
9597   // in templates, macros, etc, are reduced or removed.
9598   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
9599     return;
9600 
9601   IntRange SourceRange = GetExprRange(S.Context, E);
9602   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
9603 
9604   if (SourceRange.Width > TargetRange.Width) {
9605     // If the source is a constant, use a default-on diagnostic.
9606     // TODO: this should happen for bitfield stores, too.
9607     llvm::APSInt Value(32);
9608     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
9609       if (S.SourceMgr.isInSystemMacro(CC))
9610         return;
9611 
9612       std::string PrettySourceValue = Value.toString(10);
9613       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9614 
9615       S.DiagRuntimeBehavior(E->getExprLoc(), E,
9616         S.PDiag(diag::warn_impcast_integer_precision_constant)
9617             << PrettySourceValue << PrettyTargetValue
9618             << E->getType() << T << E->getSourceRange()
9619             << clang::SourceRange(CC));
9620       return;
9621     }
9622 
9623     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
9624     if (S.SourceMgr.isInSystemMacro(CC))
9625       return;
9626 
9627     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
9628       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9629                              /* pruneControlFlow */ true);
9630     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9631   }
9632 
9633   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9634       SourceRange.NonNegative && Source->isSignedIntegerType()) {
9635     // Warn when doing a signed to signed conversion, warn if the positive
9636     // source value is exactly the width of the target type, which will
9637     // cause a negative value to be stored.
9638 
9639     llvm::APSInt Value;
9640     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
9641         !S.SourceMgr.isInSystemMacro(CC)) {
9642       if (isSameWidthConstantConversion(S, E, T, CC)) {
9643         std::string PrettySourceValue = Value.toString(10);
9644         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9645 
9646         S.DiagRuntimeBehavior(
9647             E->getExprLoc(), E,
9648             S.PDiag(diag::warn_impcast_integer_precision_constant)
9649                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
9650                 << E->getSourceRange() << clang::SourceRange(CC));
9651         return;
9652       }
9653     }
9654 
9655     // Fall through for non-constants to give a sign conversion warning.
9656   }
9657 
9658   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9659       (!TargetRange.NonNegative && SourceRange.NonNegative &&
9660        SourceRange.Width == TargetRange.Width)) {
9661     if (S.SourceMgr.isInSystemMacro(CC))
9662       return;
9663 
9664     unsigned DiagID = diag::warn_impcast_integer_sign;
9665 
9666     // Traditionally, gcc has warned about this under -Wsign-compare.
9667     // We also want to warn about it in -Wconversion.
9668     // So if -Wconversion is off, use a completely identical diagnostic
9669     // in the sign-compare group.
9670     // The conditional-checking code will
9671     if (ICContext) {
9672       DiagID = diag::warn_impcast_integer_sign_conditional;
9673       *ICContext = true;
9674     }
9675 
9676     return DiagnoseImpCast(S, E, T, CC, DiagID);
9677   }
9678 
9679   // Diagnose conversions between different enumeration types.
9680   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
9681   // type, to give us better diagnostics.
9682   QualType SourceType = E->getType();
9683   if (!S.getLangOpts().CPlusPlus) {
9684     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
9685       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
9686         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9687         SourceType = S.Context.getTypeDeclType(Enum);
9688         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
9689       }
9690   }
9691 
9692   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
9693     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
9694       if (SourceEnum->getDecl()->hasNameForLinkage() &&
9695           TargetEnum->getDecl()->hasNameForLinkage() &&
9696           SourceEnum != TargetEnum) {
9697         if (S.SourceMgr.isInSystemMacro(CC))
9698           return;
9699 
9700         return DiagnoseImpCast(S, E, SourceType, T, CC,
9701                                diag::warn_impcast_different_enum_types);
9702       }
9703 }
9704 
9705 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9706                               SourceLocation CC, QualType T);
9707 
9708 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
9709                              SourceLocation CC, bool &ICContext) {
9710   E = E->IgnoreParenImpCasts();
9711 
9712   if (isa<ConditionalOperator>(E))
9713     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9714 
9715   AnalyzeImplicitConversions(S, E, CC);
9716   if (E->getType() != T)
9717     return CheckImplicitConversion(S, E, T, CC, &ICContext);
9718 }
9719 
9720 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
9721                               SourceLocation CC, QualType T) {
9722   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
9723 
9724   bool Suspicious = false;
9725   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
9726   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
9727 
9728   // If -Wconversion would have warned about either of the candidates
9729   // for a signedness conversion to the context type...
9730   if (!Suspicious) return;
9731 
9732   // ...but it's currently ignored...
9733   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9734     return;
9735 
9736   // ...then check whether it would have warned about either of the
9737   // candidates for a signedness conversion to the condition type.
9738   if (E->getType() == T) return;
9739 
9740   Suspicious = false;
9741   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
9742                           E->getType(), CC, &Suspicious);
9743   if (!Suspicious)
9744     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
9745                             E->getType(), CC, &Suspicious);
9746 }
9747 
9748 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
9749 /// Input argument E is a logical expression.
9750 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
9751   if (S.getLangOpts().Bool)
9752     return;
9753   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
9754 }
9755 
9756 /// AnalyzeImplicitConversions - Find and report any interesting
9757 /// implicit conversions in the given expression.  There are a couple
9758 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
9759 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
9760   QualType T = OrigE->getType();
9761   Expr *E = OrigE->IgnoreParenImpCasts();
9762 
9763   if (E->isTypeDependent() || E->isValueDependent())
9764     return;
9765 
9766   // For conditional operators, we analyze the arguments as if they
9767   // were being fed directly into the output.
9768   if (isa<ConditionalOperator>(E)) {
9769     ConditionalOperator *CO = cast<ConditionalOperator>(E);
9770     CheckConditionalOperator(S, CO, CC, T);
9771     return;
9772   }
9773 
9774   // Check implicit argument conversions for function calls.
9775   if (CallExpr *Call = dyn_cast<CallExpr>(E))
9776     CheckImplicitArgumentConversions(S, Call, CC);
9777 
9778   // Go ahead and check any implicit conversions we might have skipped.
9779   // The non-canonical typecheck is just an optimization;
9780   // CheckImplicitConversion will filter out dead implicit conversions.
9781   if (E->getType() != T)
9782     CheckImplicitConversion(S, E, T, CC);
9783 
9784   // Now continue drilling into this expression.
9785 
9786   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
9787     // The bound subexpressions in a PseudoObjectExpr are not reachable
9788     // as transitive children.
9789     // FIXME: Use a more uniform representation for this.
9790     for (auto *SE : POE->semantics())
9791       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9792         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9793   }
9794 
9795   // Skip past explicit casts.
9796   if (isa<ExplicitCastExpr>(E)) {
9797     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
9798     return AnalyzeImplicitConversions(S, E, CC);
9799   }
9800 
9801   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9802     // Do a somewhat different check with comparison operators.
9803     if (BO->isComparisonOp())
9804       return AnalyzeComparison(S, BO);
9805 
9806     // And with simple assignments.
9807     if (BO->getOpcode() == BO_Assign)
9808       return AnalyzeAssignment(S, BO);
9809   }
9810 
9811   // These break the otherwise-useful invariant below.  Fortunately,
9812   // we don't really need to recurse into them, because any internal
9813   // expressions should have been analyzed already when they were
9814   // built into statements.
9815   if (isa<StmtExpr>(E)) return;
9816 
9817   // Don't descend into unevaluated contexts.
9818   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
9819 
9820   // Now just recurse over the expression's children.
9821   CC = E->getExprLoc();
9822   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
9823   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
9824   for (Stmt *SubStmt : E->children()) {
9825     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9826     if (!ChildExpr)
9827       continue;
9828 
9829     if (IsLogicalAndOperator &&
9830         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
9831       // Ignore checking string literals that are in logical and operators.
9832       // This is a common pattern for asserts.
9833       continue;
9834     AnalyzeImplicitConversions(S, ChildExpr, CC);
9835   }
9836 
9837   if (BO && BO->isLogicalOp()) {
9838     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
9839     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9840       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9841 
9842     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
9843     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9844       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
9845   }
9846 
9847   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
9848     if (U->getOpcode() == UO_LNot)
9849       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9850 }
9851 
9852 } // end anonymous namespace
9853 
9854 /// Diagnose integer type and any valid implicit convertion to it.
9855 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
9856   // Taking into account implicit conversions,
9857   // allow any integer.
9858   if (!E->getType()->isIntegerType()) {
9859     S.Diag(E->getLocStart(),
9860            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9861     return true;
9862   }
9863   // Potentially emit standard warnings for implicit conversions if enabled
9864   // using -Wconversion.
9865   CheckImplicitConversion(S, E, IntT, E->getLocStart());
9866   return false;
9867 }
9868 
9869 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
9870 // Returns true when emitting a warning about taking the address of a reference.
9871 static bool CheckForReference(Sema &SemaRef, const Expr *E,
9872                               const PartialDiagnostic &PD) {
9873   E = E->IgnoreParenImpCasts();
9874 
9875   const FunctionDecl *FD = nullptr;
9876 
9877   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9878     if (!DRE->getDecl()->getType()->isReferenceType())
9879       return false;
9880   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9881     if (!M->getMemberDecl()->getType()->isReferenceType())
9882       return false;
9883   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9884     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
9885       return false;
9886     FD = Call->getDirectCallee();
9887   } else {
9888     return false;
9889   }
9890 
9891   SemaRef.Diag(E->getExprLoc(), PD);
9892 
9893   // If possible, point to location of function.
9894   if (FD) {
9895     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
9896   }
9897 
9898   return true;
9899 }
9900 
9901 // Returns true if the SourceLocation is expanded from any macro body.
9902 // Returns false if the SourceLocation is invalid, is from not in a macro
9903 // expansion, or is from expanded from a top-level macro argument.
9904 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
9905   if (Loc.isInvalid())
9906     return false;
9907 
9908   while (Loc.isMacroID()) {
9909     if (SM.isMacroBodyExpansion(Loc))
9910       return true;
9911     Loc = SM.getImmediateMacroCallerLoc(Loc);
9912   }
9913 
9914   return false;
9915 }
9916 
9917 /// \brief Diagnose pointers that are always non-null.
9918 /// \param E the expression containing the pointer
9919 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
9920 /// compared to a null pointer
9921 /// \param IsEqual True when the comparison is equal to a null pointer
9922 /// \param Range Extra SourceRange to highlight in the diagnostic
9923 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
9924                                         Expr::NullPointerConstantKind NullKind,
9925                                         bool IsEqual, SourceRange Range) {
9926   if (!E)
9927     return;
9928 
9929   // Don't warn inside macros.
9930   if (E->getExprLoc().isMacroID()) {
9931     const SourceManager &SM = getSourceManager();
9932     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
9933         IsInAnyMacroBody(SM, Range.getBegin()))
9934       return;
9935   }
9936   E = E->IgnoreImpCasts();
9937 
9938   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
9939 
9940   if (isa<CXXThisExpr>(E)) {
9941     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9942                                 : diag::warn_this_bool_conversion;
9943     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
9944     return;
9945   }
9946 
9947   bool IsAddressOf = false;
9948 
9949   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
9950     if (UO->getOpcode() != UO_AddrOf)
9951       return;
9952     IsAddressOf = true;
9953     E = UO->getSubExpr();
9954   }
9955 
9956   if (IsAddressOf) {
9957     unsigned DiagID = IsCompare
9958                           ? diag::warn_address_of_reference_null_compare
9959                           : diag::warn_address_of_reference_bool_conversion;
9960     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
9961                                          << IsEqual;
9962     if (CheckForReference(*this, E, PD)) {
9963       return;
9964     }
9965   }
9966 
9967   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
9968     bool IsParam = isa<NonNullAttr>(NonnullAttr);
9969     std::string Str;
9970     llvm::raw_string_ostream S(Str);
9971     E->printPretty(S, nullptr, getPrintingPolicy());
9972     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9973                                 : diag::warn_cast_nonnull_to_bool;
9974     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
9975       << E->getSourceRange() << Range << IsEqual;
9976     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9977   };
9978 
9979   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
9980   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
9981     if (auto *Callee = Call->getDirectCallee()) {
9982       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9983         ComplainAboutNonnullParamOrCall(A);
9984         return;
9985       }
9986     }
9987   }
9988 
9989   // Expect to find a single Decl.  Skip anything more complicated.
9990   ValueDecl *D = nullptr;
9991   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
9992     D = R->getDecl();
9993   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9994     D = M->getMemberDecl();
9995   }
9996 
9997   // Weak Decls can be null.
9998   if (!D || D->isWeak())
9999     return;
10000 
10001   // Check for parameter decl with nonnull attribute
10002   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
10003     if (getCurFunction() &&
10004         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
10005       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
10006         ComplainAboutNonnullParamOrCall(A);
10007         return;
10008       }
10009 
10010       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
10011         auto ParamIter = llvm::find(FD->parameters(), PV);
10012         assert(ParamIter != FD->param_end());
10013         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
10014 
10015         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
10016           if (!NonNull->args_size()) {
10017               ComplainAboutNonnullParamOrCall(NonNull);
10018               return;
10019           }
10020 
10021           for (unsigned ArgNo : NonNull->args()) {
10022             if (ArgNo == ParamNo) {
10023               ComplainAboutNonnullParamOrCall(NonNull);
10024               return;
10025             }
10026           }
10027         }
10028       }
10029     }
10030   }
10031 
10032   QualType T = D->getType();
10033   const bool IsArray = T->isArrayType();
10034   const bool IsFunction = T->isFunctionType();
10035 
10036   // Address of function is used to silence the function warning.
10037   if (IsAddressOf && IsFunction) {
10038     return;
10039   }
10040 
10041   // Found nothing.
10042   if (!IsAddressOf && !IsFunction && !IsArray)
10043     return;
10044 
10045   // Pretty print the expression for the diagnostic.
10046   std::string Str;
10047   llvm::raw_string_ostream S(Str);
10048   E->printPretty(S, nullptr, getPrintingPolicy());
10049 
10050   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
10051                               : diag::warn_impcast_pointer_to_bool;
10052   enum {
10053     AddressOf,
10054     FunctionPointer,
10055     ArrayPointer
10056   } DiagType;
10057   if (IsAddressOf)
10058     DiagType = AddressOf;
10059   else if (IsFunction)
10060     DiagType = FunctionPointer;
10061   else if (IsArray)
10062     DiagType = ArrayPointer;
10063   else
10064     llvm_unreachable("Could not determine diagnostic.");
10065   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
10066                                 << Range << IsEqual;
10067 
10068   if (!IsFunction)
10069     return;
10070 
10071   // Suggest '&' to silence the function warning.
10072   Diag(E->getExprLoc(), diag::note_function_warning_silence)
10073       << FixItHint::CreateInsertion(E->getLocStart(), "&");
10074 
10075   // Check to see if '()' fixit should be emitted.
10076   QualType ReturnType;
10077   UnresolvedSet<4> NonTemplateOverloads;
10078   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
10079   if (ReturnType.isNull())
10080     return;
10081 
10082   if (IsCompare) {
10083     // There are two cases here.  If there is null constant, the only suggest
10084     // for a pointer return type.  If the null is 0, then suggest if the return
10085     // type is a pointer or an integer type.
10086     if (!ReturnType->isPointerType()) {
10087       if (NullKind == Expr::NPCK_ZeroExpression ||
10088           NullKind == Expr::NPCK_ZeroLiteral) {
10089         if (!ReturnType->isIntegerType())
10090           return;
10091       } else {
10092         return;
10093       }
10094     }
10095   } else { // !IsCompare
10096     // For function to bool, only suggest if the function pointer has bool
10097     // return type.
10098     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
10099       return;
10100   }
10101   Diag(E->getExprLoc(), diag::note_function_to_function_call)
10102       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
10103 }
10104 
10105 /// Diagnoses "dangerous" implicit conversions within the given
10106 /// expression (which is a full expression).  Implements -Wconversion
10107 /// and -Wsign-compare.
10108 ///
10109 /// \param CC the "context" location of the implicit conversion, i.e.
10110 ///   the most location of the syntactic entity requiring the implicit
10111 ///   conversion
10112 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
10113   // Don't diagnose in unevaluated contexts.
10114   if (isUnevaluatedContext())
10115     return;
10116 
10117   // Don't diagnose for value- or type-dependent expressions.
10118   if (E->isTypeDependent() || E->isValueDependent())
10119     return;
10120 
10121   // Check for array bounds violations in cases where the check isn't triggered
10122   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
10123   // ArraySubscriptExpr is on the RHS of a variable initialization.
10124   CheckArrayAccess(E);
10125 
10126   // This is not the right CC for (e.g.) a variable initialization.
10127   AnalyzeImplicitConversions(*this, E, CC);
10128 }
10129 
10130 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
10131 /// Input argument E is a logical expression.
10132 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
10133   ::CheckBoolLikeConversion(*this, E, CC);
10134 }
10135 
10136 /// Diagnose when expression is an integer constant expression and its evaluation
10137 /// results in integer overflow
10138 void Sema::CheckForIntOverflow (Expr *E) {
10139   // Use a work list to deal with nested struct initializers.
10140   SmallVector<Expr *, 2> Exprs(1, E);
10141 
10142   do {
10143     Expr *E = Exprs.pop_back_val();
10144 
10145     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
10146       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10147       continue;
10148     }
10149 
10150     if (auto InitList = dyn_cast<InitListExpr>(E))
10151       Exprs.append(InitList->inits().begin(), InitList->inits().end());
10152 
10153     if (isa<ObjCBoxedExpr>(E))
10154       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
10155   } while (!Exprs.empty());
10156 }
10157 
10158 namespace {
10159 /// \brief Visitor for expressions which looks for unsequenced operations on the
10160 /// same object.
10161 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
10162   typedef EvaluatedExprVisitor<SequenceChecker> Base;
10163 
10164   /// \brief A tree of sequenced regions within an expression. Two regions are
10165   /// unsequenced if one is an ancestor or a descendent of the other. When we
10166   /// finish processing an expression with sequencing, such as a comma
10167   /// expression, we fold its tree nodes into its parent, since they are
10168   /// unsequenced with respect to nodes we will visit later.
10169   class SequenceTree {
10170     struct Value {
10171       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
10172       unsigned Parent : 31;
10173       unsigned Merged : 1;
10174     };
10175     SmallVector<Value, 8> Values;
10176 
10177   public:
10178     /// \brief A region within an expression which may be sequenced with respect
10179     /// to some other region.
10180     class Seq {
10181       explicit Seq(unsigned N) : Index(N) {}
10182       unsigned Index;
10183       friend class SequenceTree;
10184     public:
10185       Seq() : Index(0) {}
10186     };
10187 
10188     SequenceTree() { Values.push_back(Value(0)); }
10189     Seq root() const { return Seq(0); }
10190 
10191     /// \brief Create a new sequence of operations, which is an unsequenced
10192     /// subset of \p Parent. This sequence of operations is sequenced with
10193     /// respect to other children of \p Parent.
10194     Seq allocate(Seq Parent) {
10195       Values.push_back(Value(Parent.Index));
10196       return Seq(Values.size() - 1);
10197     }
10198 
10199     /// \brief Merge a sequence of operations into its parent.
10200     void merge(Seq S) {
10201       Values[S.Index].Merged = true;
10202     }
10203 
10204     /// \brief Determine whether two operations are unsequenced. This operation
10205     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
10206     /// should have been merged into its parent as appropriate.
10207     bool isUnsequenced(Seq Cur, Seq Old) {
10208       unsigned C = representative(Cur.Index);
10209       unsigned Target = representative(Old.Index);
10210       while (C >= Target) {
10211         if (C == Target)
10212           return true;
10213         C = Values[C].Parent;
10214       }
10215       return false;
10216     }
10217 
10218   private:
10219     /// \brief Pick a representative for a sequence.
10220     unsigned representative(unsigned K) {
10221       if (Values[K].Merged)
10222         // Perform path compression as we go.
10223         return Values[K].Parent = representative(Values[K].Parent);
10224       return K;
10225     }
10226   };
10227 
10228   /// An object for which we can track unsequenced uses.
10229   typedef NamedDecl *Object;
10230 
10231   /// Different flavors of object usage which we track. We only track the
10232   /// least-sequenced usage of each kind.
10233   enum UsageKind {
10234     /// A read of an object. Multiple unsequenced reads are OK.
10235     UK_Use,
10236     /// A modification of an object which is sequenced before the value
10237     /// computation of the expression, such as ++n in C++.
10238     UK_ModAsValue,
10239     /// A modification of an object which is not sequenced before the value
10240     /// computation of the expression, such as n++.
10241     UK_ModAsSideEffect,
10242 
10243     UK_Count = UK_ModAsSideEffect + 1
10244   };
10245 
10246   struct Usage {
10247     Usage() : Use(nullptr), Seq() {}
10248     Expr *Use;
10249     SequenceTree::Seq Seq;
10250   };
10251 
10252   struct UsageInfo {
10253     UsageInfo() : Diagnosed(false) {}
10254     Usage Uses[UK_Count];
10255     /// Have we issued a diagnostic for this variable already?
10256     bool Diagnosed;
10257   };
10258   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10259 
10260   Sema &SemaRef;
10261   /// Sequenced regions within the expression.
10262   SequenceTree Tree;
10263   /// Declaration modifications and references which we have seen.
10264   UsageInfoMap UsageMap;
10265   /// The region we are currently within.
10266   SequenceTree::Seq Region;
10267   /// Filled in with declarations which were modified as a side-effect
10268   /// (that is, post-increment operations).
10269   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10270   /// Expressions to check later. We defer checking these to reduce
10271   /// stack usage.
10272   SmallVectorImpl<Expr *> &WorkList;
10273 
10274   /// RAII object wrapping the visitation of a sequenced subexpression of an
10275   /// expression. At the end of this process, the side-effects of the evaluation
10276   /// become sequenced with respect to the value computation of the result, so
10277   /// we downgrade any UK_ModAsSideEffect within the evaluation to
10278   /// UK_ModAsValue.
10279   struct SequencedSubexpression {
10280     SequencedSubexpression(SequenceChecker &Self)
10281       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10282       Self.ModAsSideEffect = &ModAsSideEffect;
10283     }
10284     ~SequencedSubexpression() {
10285       for (auto &M : llvm::reverse(ModAsSideEffect)) {
10286         UsageInfo &U = Self.UsageMap[M.first];
10287         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10288         Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10289         SideEffectUsage = M.second;
10290       }
10291       Self.ModAsSideEffect = OldModAsSideEffect;
10292     }
10293 
10294     SequenceChecker &Self;
10295     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
10296     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10297   };
10298 
10299   /// RAII object wrapping the visitation of a subexpression which we might
10300   /// choose to evaluate as a constant. If any subexpression is evaluated and
10301   /// found to be non-constant, this allows us to suppress the evaluation of
10302   /// the outer expression.
10303   class EvaluationTracker {
10304   public:
10305     EvaluationTracker(SequenceChecker &Self)
10306         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
10307       Self.EvalTracker = this;
10308     }
10309     ~EvaluationTracker() {
10310       Self.EvalTracker = Prev;
10311       if (Prev)
10312         Prev->EvalOK &= EvalOK;
10313     }
10314 
10315     bool evaluate(const Expr *E, bool &Result) {
10316       if (!EvalOK || E->isValueDependent())
10317         return false;
10318       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
10319       return EvalOK;
10320     }
10321 
10322   private:
10323     SequenceChecker &Self;
10324     EvaluationTracker *Prev;
10325     bool EvalOK;
10326   } *EvalTracker;
10327 
10328   /// \brief Find the object which is produced by the specified expression,
10329   /// if any.
10330   Object getObject(Expr *E, bool Mod) const {
10331     E = E->IgnoreParenCasts();
10332     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
10333       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10334         return getObject(UO->getSubExpr(), Mod);
10335     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10336       if (BO->getOpcode() == BO_Comma)
10337         return getObject(BO->getRHS(), Mod);
10338       if (Mod && BO->isAssignmentOp())
10339         return getObject(BO->getLHS(), Mod);
10340     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10341       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
10342       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10343         return ME->getMemberDecl();
10344     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10345       // FIXME: If this is a reference, map through to its value.
10346       return DRE->getDecl();
10347     return nullptr;
10348   }
10349 
10350   /// \brief Note that an object was modified or used by an expression.
10351   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
10352     Usage &U = UI.Uses[UK];
10353     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10354       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10355         ModAsSideEffect->push_back(std::make_pair(O, U));
10356       U.Use = Ref;
10357       U.Seq = Region;
10358     }
10359   }
10360   /// \brief Check whether a modification or use conflicts with a prior usage.
10361   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
10362                   bool IsModMod) {
10363     if (UI.Diagnosed)
10364       return;
10365 
10366     const Usage &U = UI.Uses[OtherKind];
10367     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10368       return;
10369 
10370     Expr *Mod = U.Use;
10371     Expr *ModOrUse = Ref;
10372     if (OtherKind == UK_Use)
10373       std::swap(Mod, ModOrUse);
10374 
10375     SemaRef.Diag(Mod->getExprLoc(),
10376                  IsModMod ? diag::warn_unsequenced_mod_mod
10377                           : diag::warn_unsequenced_mod_use)
10378       << O << SourceRange(ModOrUse->getExprLoc());
10379     UI.Diagnosed = true;
10380   }
10381 
10382   void notePreUse(Object O, Expr *Use) {
10383     UsageInfo &U = UsageMap[O];
10384     // Uses conflict with other modifications.
10385     checkUsage(O, U, Use, UK_ModAsValue, false);
10386   }
10387   void notePostUse(Object O, Expr *Use) {
10388     UsageInfo &U = UsageMap[O];
10389     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
10390     addUsage(U, O, Use, UK_Use);
10391   }
10392 
10393   void notePreMod(Object O, Expr *Mod) {
10394     UsageInfo &U = UsageMap[O];
10395     // Modifications conflict with other modifications and with uses.
10396     checkUsage(O, U, Mod, UK_ModAsValue, true);
10397     checkUsage(O, U, Mod, UK_Use, false);
10398   }
10399   void notePostMod(Object O, Expr *Use, UsageKind UK) {
10400     UsageInfo &U = UsageMap[O];
10401     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
10402     addUsage(U, O, Use, UK);
10403   }
10404 
10405 public:
10406   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
10407       : Base(S.Context), SemaRef(S), Region(Tree.root()),
10408         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10409     Visit(E);
10410   }
10411 
10412   void VisitStmt(Stmt *S) {
10413     // Skip all statements which aren't expressions for now.
10414   }
10415 
10416   void VisitExpr(Expr *E) {
10417     // By default, just recurse to evaluated subexpressions.
10418     Base::VisitStmt(E);
10419   }
10420 
10421   void VisitCastExpr(CastExpr *E) {
10422     Object O = Object();
10423     if (E->getCastKind() == CK_LValueToRValue)
10424       O = getObject(E->getSubExpr(), false);
10425 
10426     if (O)
10427       notePreUse(O, E);
10428     VisitExpr(E);
10429     if (O)
10430       notePostUse(O, E);
10431   }
10432 
10433   void VisitBinComma(BinaryOperator *BO) {
10434     // C++11 [expr.comma]p1:
10435     //   Every value computation and side effect associated with the left
10436     //   expression is sequenced before every value computation and side
10437     //   effect associated with the right expression.
10438     SequenceTree::Seq LHS = Tree.allocate(Region);
10439     SequenceTree::Seq RHS = Tree.allocate(Region);
10440     SequenceTree::Seq OldRegion = Region;
10441 
10442     {
10443       SequencedSubexpression SeqLHS(*this);
10444       Region = LHS;
10445       Visit(BO->getLHS());
10446     }
10447 
10448     Region = RHS;
10449     Visit(BO->getRHS());
10450 
10451     Region = OldRegion;
10452 
10453     // Forget that LHS and RHS are sequenced. They are both unsequenced
10454     // with respect to other stuff.
10455     Tree.merge(LHS);
10456     Tree.merge(RHS);
10457   }
10458 
10459   void VisitBinAssign(BinaryOperator *BO) {
10460     // The modification is sequenced after the value computation of the LHS
10461     // and RHS, so check it before inspecting the operands and update the
10462     // map afterwards.
10463     Object O = getObject(BO->getLHS(), true);
10464     if (!O)
10465       return VisitExpr(BO);
10466 
10467     notePreMod(O, BO);
10468 
10469     // C++11 [expr.ass]p7:
10470     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
10471     //   only once.
10472     //
10473     // Therefore, for a compound assignment operator, O is considered used
10474     // everywhere except within the evaluation of E1 itself.
10475     if (isa<CompoundAssignOperator>(BO))
10476       notePreUse(O, BO);
10477 
10478     Visit(BO->getLHS());
10479 
10480     if (isa<CompoundAssignOperator>(BO))
10481       notePostUse(O, BO);
10482 
10483     Visit(BO->getRHS());
10484 
10485     // C++11 [expr.ass]p1:
10486     //   the assignment is sequenced [...] before the value computation of the
10487     //   assignment expression.
10488     // C11 6.5.16/3 has no such rule.
10489     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10490                                                        : UK_ModAsSideEffect);
10491   }
10492 
10493   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
10494     VisitBinAssign(CAO);
10495   }
10496 
10497   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10498   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10499   void VisitUnaryPreIncDec(UnaryOperator *UO) {
10500     Object O = getObject(UO->getSubExpr(), true);
10501     if (!O)
10502       return VisitExpr(UO);
10503 
10504     notePreMod(O, UO);
10505     Visit(UO->getSubExpr());
10506     // C++11 [expr.pre.incr]p1:
10507     //   the expression ++x is equivalent to x+=1
10508     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10509                                                        : UK_ModAsSideEffect);
10510   }
10511 
10512   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10513   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10514   void VisitUnaryPostIncDec(UnaryOperator *UO) {
10515     Object O = getObject(UO->getSubExpr(), true);
10516     if (!O)
10517       return VisitExpr(UO);
10518 
10519     notePreMod(O, UO);
10520     Visit(UO->getSubExpr());
10521     notePostMod(O, UO, UK_ModAsSideEffect);
10522   }
10523 
10524   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
10525   void VisitBinLOr(BinaryOperator *BO) {
10526     // The side-effects of the LHS of an '&&' are sequenced before the
10527     // value computation of the RHS, and hence before the value computation
10528     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
10529     // as if they were unconditionally sequenced.
10530     EvaluationTracker Eval(*this);
10531     {
10532       SequencedSubexpression Sequenced(*this);
10533       Visit(BO->getLHS());
10534     }
10535 
10536     bool Result;
10537     if (Eval.evaluate(BO->getLHS(), Result)) {
10538       if (!Result)
10539         Visit(BO->getRHS());
10540     } else {
10541       // Check for unsequenced operations in the RHS, treating it as an
10542       // entirely separate evaluation.
10543       //
10544       // FIXME: If there are operations in the RHS which are unsequenced
10545       // with respect to operations outside the RHS, and those operations
10546       // are unconditionally evaluated, diagnose them.
10547       WorkList.push_back(BO->getRHS());
10548     }
10549   }
10550   void VisitBinLAnd(BinaryOperator *BO) {
10551     EvaluationTracker Eval(*this);
10552     {
10553       SequencedSubexpression Sequenced(*this);
10554       Visit(BO->getLHS());
10555     }
10556 
10557     bool Result;
10558     if (Eval.evaluate(BO->getLHS(), Result)) {
10559       if (Result)
10560         Visit(BO->getRHS());
10561     } else {
10562       WorkList.push_back(BO->getRHS());
10563     }
10564   }
10565 
10566   // Only visit the condition, unless we can be sure which subexpression will
10567   // be chosen.
10568   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
10569     EvaluationTracker Eval(*this);
10570     {
10571       SequencedSubexpression Sequenced(*this);
10572       Visit(CO->getCond());
10573     }
10574 
10575     bool Result;
10576     if (Eval.evaluate(CO->getCond(), Result))
10577       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
10578     else {
10579       WorkList.push_back(CO->getTrueExpr());
10580       WorkList.push_back(CO->getFalseExpr());
10581     }
10582   }
10583 
10584   void VisitCallExpr(CallExpr *CE) {
10585     // C++11 [intro.execution]p15:
10586     //   When calling a function [...], every value computation and side effect
10587     //   associated with any argument expression, or with the postfix expression
10588     //   designating the called function, is sequenced before execution of every
10589     //   expression or statement in the body of the function [and thus before
10590     //   the value computation of its result].
10591     SequencedSubexpression Sequenced(*this);
10592     Base::VisitCallExpr(CE);
10593 
10594     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
10595   }
10596 
10597   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
10598     // This is a call, so all subexpressions are sequenced before the result.
10599     SequencedSubexpression Sequenced(*this);
10600 
10601     if (!CCE->isListInitialization())
10602       return VisitExpr(CCE);
10603 
10604     // In C++11, list initializations are sequenced.
10605     SmallVector<SequenceTree::Seq, 32> Elts;
10606     SequenceTree::Seq Parent = Region;
10607     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
10608                                         E = CCE->arg_end();
10609          I != E; ++I) {
10610       Region = Tree.allocate(Parent);
10611       Elts.push_back(Region);
10612       Visit(*I);
10613     }
10614 
10615     // Forget that the initializers are sequenced.
10616     Region = Parent;
10617     for (unsigned I = 0; I < Elts.size(); ++I)
10618       Tree.merge(Elts[I]);
10619   }
10620 
10621   void VisitInitListExpr(InitListExpr *ILE) {
10622     if (!SemaRef.getLangOpts().CPlusPlus11)
10623       return VisitExpr(ILE);
10624 
10625     // In C++11, list initializations are sequenced.
10626     SmallVector<SequenceTree::Seq, 32> Elts;
10627     SequenceTree::Seq Parent = Region;
10628     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
10629       Expr *E = ILE->getInit(I);
10630       if (!E) continue;
10631       Region = Tree.allocate(Parent);
10632       Elts.push_back(Region);
10633       Visit(E);
10634     }
10635 
10636     // Forget that the initializers are sequenced.
10637     Region = Parent;
10638     for (unsigned I = 0; I < Elts.size(); ++I)
10639       Tree.merge(Elts[I]);
10640   }
10641 };
10642 } // end anonymous namespace
10643 
10644 void Sema::CheckUnsequencedOperations(Expr *E) {
10645   SmallVector<Expr *, 8> WorkList;
10646   WorkList.push_back(E);
10647   while (!WorkList.empty()) {
10648     Expr *Item = WorkList.pop_back_val();
10649     SequenceChecker(*this, Item, WorkList);
10650   }
10651 }
10652 
10653 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
10654                               bool IsConstexpr) {
10655   CheckImplicitConversions(E, CheckLoc);
10656   if (!E->isInstantiationDependent())
10657     CheckUnsequencedOperations(E);
10658   if (!IsConstexpr && !E->isValueDependent())
10659     CheckForIntOverflow(E);
10660   DiagnoseMisalignedMembers();
10661 }
10662 
10663 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
10664                                        FieldDecl *BitField,
10665                                        Expr *Init) {
10666   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
10667 }
10668 
10669 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
10670                                          SourceLocation Loc) {
10671   if (!PType->isVariablyModifiedType())
10672     return;
10673   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10674     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
10675     return;
10676   }
10677   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10678     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
10679     return;
10680   }
10681   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10682     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
10683     return;
10684   }
10685 
10686   const ArrayType *AT = S.Context.getAsArrayType(PType);
10687   if (!AT)
10688     return;
10689 
10690   if (AT->getSizeModifier() != ArrayType::Star) {
10691     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
10692     return;
10693   }
10694 
10695   S.Diag(Loc, diag::err_array_star_in_function_definition);
10696 }
10697 
10698 /// CheckParmsForFunctionDef - Check that the parameters of the given
10699 /// function are appropriate for the definition of a function. This
10700 /// takes care of any checks that cannot be performed on the
10701 /// declaration itself, e.g., that the types of each of the function
10702 /// parameters are complete.
10703 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
10704                                     bool CheckParameterNames) {
10705   bool HasInvalidParm = false;
10706   for (ParmVarDecl *Param : Parameters) {
10707     // C99 6.7.5.3p4: the parameters in a parameter type list in a
10708     // function declarator that is part of a function definition of
10709     // that function shall not have incomplete type.
10710     //
10711     // This is also C++ [dcl.fct]p6.
10712     if (!Param->isInvalidDecl() &&
10713         RequireCompleteType(Param->getLocation(), Param->getType(),
10714                             diag::err_typecheck_decl_incomplete_type)) {
10715       Param->setInvalidDecl();
10716       HasInvalidParm = true;
10717     }
10718 
10719     // C99 6.9.1p5: If the declarator includes a parameter type list, the
10720     // declaration of each parameter shall include an identifier.
10721     if (CheckParameterNames &&
10722         Param->getIdentifier() == nullptr &&
10723         !Param->isImplicit() &&
10724         !getLangOpts().CPlusPlus)
10725       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10726 
10727     // C99 6.7.5.3p12:
10728     //   If the function declarator is not part of a definition of that
10729     //   function, parameters may have incomplete type and may use the [*]
10730     //   notation in their sequences of declarator specifiers to specify
10731     //   variable length array types.
10732     QualType PType = Param->getOriginalType();
10733     // FIXME: This diagnostic should point the '[*]' if source-location
10734     // information is added for it.
10735     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
10736 
10737     // MSVC destroys objects passed by value in the callee.  Therefore a
10738     // function definition which takes such a parameter must be able to call the
10739     // object's destructor.  However, we don't perform any direct access check
10740     // on the dtor.
10741     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
10742                                        .getCXXABI()
10743                                        .areArgsDestroyedLeftToRightInCallee()) {
10744       if (!Param->isInvalidDecl()) {
10745         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
10746           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10747           if (!ClassDecl->isInvalidDecl() &&
10748               !ClassDecl->hasIrrelevantDestructor() &&
10749               !ClassDecl->isDependentContext()) {
10750             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
10751             MarkFunctionReferenced(Param->getLocation(), Destructor);
10752             DiagnoseUseOfDecl(Destructor, Param->getLocation());
10753           }
10754         }
10755       }
10756     }
10757 
10758     // Parameters with the pass_object_size attribute only need to be marked
10759     // constant at function definitions. Because we lack information about
10760     // whether we're on a declaration or definition when we're instantiating the
10761     // attribute, we need to check for constness here.
10762     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
10763       if (!Param->getType().isConstQualified())
10764         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10765             << Attr->getSpelling() << 1;
10766   }
10767 
10768   return HasInvalidParm;
10769 }
10770 
10771 /// A helper function to get the alignment of a Decl referred to by DeclRefExpr
10772 /// or MemberExpr.
10773 static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign,
10774                               ASTContext &Context) {
10775   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
10776     return Context.getDeclAlign(DRE->getDecl());
10777 
10778   if (const auto *ME = dyn_cast<MemberExpr>(E))
10779     return Context.getDeclAlign(ME->getMemberDecl());
10780 
10781   return TypeAlign;
10782 }
10783 
10784 /// CheckCastAlign - Implements -Wcast-align, which warns when a
10785 /// pointer cast increases the alignment requirements.
10786 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
10787   // This is actually a lot of work to potentially be doing on every
10788   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
10789   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
10790     return;
10791 
10792   // Ignore dependent types.
10793   if (T->isDependentType() || Op->getType()->isDependentType())
10794     return;
10795 
10796   // Require that the destination be a pointer type.
10797   const PointerType *DestPtr = T->getAs<PointerType>();
10798   if (!DestPtr) return;
10799 
10800   // If the destination has alignment 1, we're done.
10801   QualType DestPointee = DestPtr->getPointeeType();
10802   if (DestPointee->isIncompleteType()) return;
10803   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
10804   if (DestAlign.isOne()) return;
10805 
10806   // Require that the source be a pointer type.
10807   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
10808   if (!SrcPtr) return;
10809   QualType SrcPointee = SrcPtr->getPointeeType();
10810 
10811   // Whitelist casts from cv void*.  We already implicitly
10812   // whitelisted casts to cv void*, since they have alignment 1.
10813   // Also whitelist casts involving incomplete types, which implicitly
10814   // includes 'void'.
10815   if (SrcPointee->isIncompleteType()) return;
10816 
10817   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
10818 
10819   if (auto *CE = dyn_cast<CastExpr>(Op)) {
10820     if (CE->getCastKind() == CK_ArrayToPointerDecay)
10821       SrcAlign = getDeclAlign(CE->getSubExpr(), SrcAlign, Context);
10822   } else if (auto *UO = dyn_cast<UnaryOperator>(Op)) {
10823     if (UO->getOpcode() == UO_AddrOf)
10824       SrcAlign = getDeclAlign(UO->getSubExpr(), SrcAlign, Context);
10825   }
10826 
10827   if (SrcAlign >= DestAlign) return;
10828 
10829   Diag(TRange.getBegin(), diag::warn_cast_align)
10830     << Op->getType() << T
10831     << static_cast<unsigned>(SrcAlign.getQuantity())
10832     << static_cast<unsigned>(DestAlign.getQuantity())
10833     << TRange << Op->getSourceRange();
10834 }
10835 
10836 /// \brief Check whether this array fits the idiom of a size-one tail padded
10837 /// array member of a struct.
10838 ///
10839 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
10840 /// commonly used to emulate flexible arrays in C89 code.
10841 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
10842                                     const NamedDecl *ND) {
10843   if (Size != 1 || !ND) return false;
10844 
10845   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
10846   if (!FD) return false;
10847 
10848   // Don't consider sizes resulting from macro expansions or template argument
10849   // substitution to form C89 tail-padded arrays.
10850 
10851   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
10852   while (TInfo) {
10853     TypeLoc TL = TInfo->getTypeLoc();
10854     // Look through typedefs.
10855     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
10856       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
10857       TInfo = TDL->getTypeSourceInfo();
10858       continue;
10859     }
10860     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
10861       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
10862       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
10863         return false;
10864     }
10865     break;
10866   }
10867 
10868   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
10869   if (!RD) return false;
10870   if (RD->isUnion()) return false;
10871   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10872     if (!CRD->isStandardLayout()) return false;
10873   }
10874 
10875   // See if this is the last field decl in the record.
10876   const Decl *D = FD;
10877   while ((D = D->getNextDeclInContext()))
10878     if (isa<FieldDecl>(D))
10879       return false;
10880   return true;
10881 }
10882 
10883 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
10884                             const ArraySubscriptExpr *ASE,
10885                             bool AllowOnePastEnd, bool IndexNegated) {
10886   IndexExpr = IndexExpr->IgnoreParenImpCasts();
10887   if (IndexExpr->isValueDependent())
10888     return;
10889 
10890   const Type *EffectiveType =
10891       BaseExpr->getType()->getPointeeOrArrayElementType();
10892   BaseExpr = BaseExpr->IgnoreParenCasts();
10893   const ConstantArrayType *ArrayTy =
10894     Context.getAsConstantArrayType(BaseExpr->getType());
10895   if (!ArrayTy)
10896     return;
10897 
10898   llvm::APSInt index;
10899   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
10900     return;
10901   if (IndexNegated)
10902     index = -index;
10903 
10904   const NamedDecl *ND = nullptr;
10905   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10906     ND = dyn_cast<NamedDecl>(DRE->getDecl());
10907   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10908     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10909 
10910   if (index.isUnsigned() || !index.isNegative()) {
10911     llvm::APInt size = ArrayTy->getSize();
10912     if (!size.isStrictlyPositive())
10913       return;
10914 
10915     const Type *BaseType = BaseExpr->getType()->getPointeeOrArrayElementType();
10916     if (BaseType != EffectiveType) {
10917       // Make sure we're comparing apples to apples when comparing index to size
10918       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
10919       uint64_t array_typesize = Context.getTypeSize(BaseType);
10920       // Handle ptrarith_typesize being zero, such as when casting to void*
10921       if (!ptrarith_typesize) ptrarith_typesize = 1;
10922       if (ptrarith_typesize != array_typesize) {
10923         // There's a cast to a different size type involved
10924         uint64_t ratio = array_typesize / ptrarith_typesize;
10925         // TODO: Be smarter about handling cases where array_typesize is not a
10926         // multiple of ptrarith_typesize
10927         if (ptrarith_typesize * ratio == array_typesize)
10928           size *= llvm::APInt(size.getBitWidth(), ratio);
10929       }
10930     }
10931 
10932     if (size.getBitWidth() > index.getBitWidth())
10933       index = index.zext(size.getBitWidth());
10934     else if (size.getBitWidth() < index.getBitWidth())
10935       size = size.zext(index.getBitWidth());
10936 
10937     // For array subscripting the index must be less than size, but for pointer
10938     // arithmetic also allow the index (offset) to be equal to size since
10939     // computing the next address after the end of the array is legal and
10940     // commonly done e.g. in C++ iterators and range-based for loops.
10941     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10942       return;
10943 
10944     // Also don't warn for arrays of size 1 which are members of some
10945     // structure. These are often used to approximate flexible arrays in C89
10946     // code.
10947     if (IsTailPaddedMemberArray(*this, size, ND))
10948       return;
10949 
10950     // Suppress the warning if the subscript expression (as identified by the
10951     // ']' location) and the index expression are both from macro expansions
10952     // within a system header.
10953     if (ASE) {
10954       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
10955           ASE->getRBracketLoc());
10956       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
10957         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
10958             IndexExpr->getLocStart());
10959         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10960           return;
10961       }
10962     }
10963 
10964     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10965     if (ASE)
10966       DiagID = diag::warn_array_index_exceeds_bounds;
10967 
10968     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10969                         PDiag(DiagID) << index.toString(10, true)
10970                           << size.toString(10, true)
10971                           << (unsigned)size.getLimitedValue(~0U)
10972                           << IndexExpr->getSourceRange());
10973   } else {
10974     unsigned DiagID = diag::warn_array_index_precedes_bounds;
10975     if (!ASE) {
10976       DiagID = diag::warn_ptr_arith_precedes_bounds;
10977       if (index.isNegative()) index = -index;
10978     }
10979 
10980     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
10981                         PDiag(DiagID) << index.toString(10, true)
10982                           << IndexExpr->getSourceRange());
10983   }
10984 
10985   if (!ND) {
10986     // Try harder to find a NamedDecl to point at in the note.
10987     while (const ArraySubscriptExpr *ASE =
10988            dyn_cast<ArraySubscriptExpr>(BaseExpr))
10989       BaseExpr = ASE->getBase()->IgnoreParenCasts();
10990     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10991       ND = dyn_cast<NamedDecl>(DRE->getDecl());
10992     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10993       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10994   }
10995 
10996   if (ND)
10997     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
10998                         PDiag(diag::note_array_index_out_of_bounds)
10999                           << ND->getDeclName());
11000 }
11001 
11002 void Sema::CheckArrayAccess(const Expr *expr) {
11003   int AllowOnePastEnd = 0;
11004   while (expr) {
11005     expr = expr->IgnoreParenImpCasts();
11006     switch (expr->getStmtClass()) {
11007       case Stmt::ArraySubscriptExprClass: {
11008         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
11009         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
11010                          AllowOnePastEnd > 0);
11011         return;
11012       }
11013       case Stmt::OMPArraySectionExprClass: {
11014         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
11015         if (ASE->getLowerBound())
11016           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
11017                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
11018         return;
11019       }
11020       case Stmt::UnaryOperatorClass: {
11021         // Only unwrap the * and & unary operators
11022         const UnaryOperator *UO = cast<UnaryOperator>(expr);
11023         expr = UO->getSubExpr();
11024         switch (UO->getOpcode()) {
11025           case UO_AddrOf:
11026             AllowOnePastEnd++;
11027             break;
11028           case UO_Deref:
11029             AllowOnePastEnd--;
11030             break;
11031           default:
11032             return;
11033         }
11034         break;
11035       }
11036       case Stmt::ConditionalOperatorClass: {
11037         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
11038         if (const Expr *lhs = cond->getLHS())
11039           CheckArrayAccess(lhs);
11040         if (const Expr *rhs = cond->getRHS())
11041           CheckArrayAccess(rhs);
11042         return;
11043       }
11044       case Stmt::CXXOperatorCallExprClass: {
11045         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
11046         for (const auto *Arg : OCE->arguments())
11047           CheckArrayAccess(Arg);
11048         return;
11049       }
11050       default:
11051         return;
11052     }
11053   }
11054 }
11055 
11056 //===--- CHECK: Objective-C retain cycles ----------------------------------//
11057 
11058 namespace {
11059   struct RetainCycleOwner {
11060     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
11061     VarDecl *Variable;
11062     SourceRange Range;
11063     SourceLocation Loc;
11064     bool Indirect;
11065 
11066     void setLocsFrom(Expr *e) {
11067       Loc = e->getExprLoc();
11068       Range = e->getSourceRange();
11069     }
11070   };
11071 } // end anonymous namespace
11072 
11073 /// Consider whether capturing the given variable can possibly lead to
11074 /// a retain cycle.
11075 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
11076   // In ARC, it's captured strongly iff the variable has __strong
11077   // lifetime.  In MRR, it's captured strongly if the variable is
11078   // __block and has an appropriate type.
11079   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11080     return false;
11081 
11082   owner.Variable = var;
11083   if (ref)
11084     owner.setLocsFrom(ref);
11085   return true;
11086 }
11087 
11088 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
11089   while (true) {
11090     e = e->IgnoreParens();
11091     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
11092       switch (cast->getCastKind()) {
11093       case CK_BitCast:
11094       case CK_LValueBitCast:
11095       case CK_LValueToRValue:
11096       case CK_ARCReclaimReturnedObject:
11097         e = cast->getSubExpr();
11098         continue;
11099 
11100       default:
11101         return false;
11102       }
11103     }
11104 
11105     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
11106       ObjCIvarDecl *ivar = ref->getDecl();
11107       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
11108         return false;
11109 
11110       // Try to find a retain cycle in the base.
11111       if (!findRetainCycleOwner(S, ref->getBase(), owner))
11112         return false;
11113 
11114       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
11115       owner.Indirect = true;
11116       return true;
11117     }
11118 
11119     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
11120       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
11121       if (!var) return false;
11122       return considerVariable(var, ref, owner);
11123     }
11124 
11125     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
11126       if (member->isArrow()) return false;
11127 
11128       // Don't count this as an indirect ownership.
11129       e = member->getBase();
11130       continue;
11131     }
11132 
11133     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
11134       // Only pay attention to pseudo-objects on property references.
11135       ObjCPropertyRefExpr *pre
11136         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
11137                                               ->IgnoreParens());
11138       if (!pre) return false;
11139       if (pre->isImplicitProperty()) return false;
11140       ObjCPropertyDecl *property = pre->getExplicitProperty();
11141       if (!property->isRetaining() &&
11142           !(property->getPropertyIvarDecl() &&
11143             property->getPropertyIvarDecl()->getType()
11144               .getObjCLifetime() == Qualifiers::OCL_Strong))
11145           return false;
11146 
11147       owner.Indirect = true;
11148       if (pre->isSuperReceiver()) {
11149         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
11150         if (!owner.Variable)
11151           return false;
11152         owner.Loc = pre->getLocation();
11153         owner.Range = pre->getSourceRange();
11154         return true;
11155       }
11156       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
11157                               ->getSourceExpr());
11158       continue;
11159     }
11160 
11161     // Array ivars?
11162 
11163     return false;
11164   }
11165 }
11166 
11167 namespace {
11168   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
11169     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
11170       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
11171         Context(Context), Variable(variable), Capturer(nullptr),
11172         VarWillBeReased(false) {}
11173     ASTContext &Context;
11174     VarDecl *Variable;
11175     Expr *Capturer;
11176     bool VarWillBeReased;
11177 
11178     void VisitDeclRefExpr(DeclRefExpr *ref) {
11179       if (ref->getDecl() == Variable && !Capturer)
11180         Capturer = ref;
11181     }
11182 
11183     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
11184       if (Capturer) return;
11185       Visit(ref->getBase());
11186       if (Capturer && ref->isFreeIvar())
11187         Capturer = ref;
11188     }
11189 
11190     void VisitBlockExpr(BlockExpr *block) {
11191       // Look inside nested blocks
11192       if (block->getBlockDecl()->capturesVariable(Variable))
11193         Visit(block->getBlockDecl()->getBody());
11194     }
11195 
11196     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
11197       if (Capturer) return;
11198       if (OVE->getSourceExpr())
11199         Visit(OVE->getSourceExpr());
11200     }
11201     void VisitBinaryOperator(BinaryOperator *BinOp) {
11202       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
11203         return;
11204       Expr *LHS = BinOp->getLHS();
11205       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11206         if (DRE->getDecl() != Variable)
11207           return;
11208         if (Expr *RHS = BinOp->getRHS()) {
11209           RHS = RHS->IgnoreParenCasts();
11210           llvm::APSInt Value;
11211           VarWillBeReased =
11212             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11213         }
11214       }
11215     }
11216   };
11217 } // end anonymous namespace
11218 
11219 /// Check whether the given argument is a block which captures a
11220 /// variable.
11221 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
11222   assert(owner.Variable && owner.Loc.isValid());
11223 
11224   e = e->IgnoreParenCasts();
11225 
11226   // Look through [^{...} copy] and Block_copy(^{...}).
11227   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
11228     Selector Cmd = ME->getSelector();
11229     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
11230       e = ME->getInstanceReceiver();
11231       if (!e)
11232         return nullptr;
11233       e = e->IgnoreParenCasts();
11234     }
11235   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
11236     if (CE->getNumArgs() == 1) {
11237       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
11238       if (Fn) {
11239         const IdentifierInfo *FnI = Fn->getIdentifier();
11240         if (FnI && FnI->isStr("_Block_copy")) {
11241           e = CE->getArg(0)->IgnoreParenCasts();
11242         }
11243       }
11244     }
11245   }
11246 
11247   BlockExpr *block = dyn_cast<BlockExpr>(e);
11248   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
11249     return nullptr;
11250 
11251   FindCaptureVisitor visitor(S.Context, owner.Variable);
11252   visitor.Visit(block->getBlockDecl()->getBody());
11253   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
11254 }
11255 
11256 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
11257                                 RetainCycleOwner &owner) {
11258   assert(capturer);
11259   assert(owner.Variable && owner.Loc.isValid());
11260 
11261   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
11262     << owner.Variable << capturer->getSourceRange();
11263   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11264     << owner.Indirect << owner.Range;
11265 }
11266 
11267 /// Check for a keyword selector that starts with the word 'add' or
11268 /// 'set'.
11269 static bool isSetterLikeSelector(Selector sel) {
11270   if (sel.isUnarySelector()) return false;
11271 
11272   StringRef str = sel.getNameForSlot(0);
11273   while (!str.empty() && str.front() == '_') str = str.substr(1);
11274   if (str.startswith("set"))
11275     str = str.substr(3);
11276   else if (str.startswith("add")) {
11277     // Specially whitelist 'addOperationWithBlock:'.
11278     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
11279       return false;
11280     str = str.substr(3);
11281   }
11282   else
11283     return false;
11284 
11285   if (str.empty()) return true;
11286   return !isLowercase(str.front());
11287 }
11288 
11289 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
11290                                                     ObjCMessageExpr *Message) {
11291   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
11292                                                 Message->getReceiverInterface(),
11293                                                 NSAPI::ClassId_NSMutableArray);
11294   if (!IsMutableArray) {
11295     return None;
11296   }
11297 
11298   Selector Sel = Message->getSelector();
11299 
11300   Optional<NSAPI::NSArrayMethodKind> MKOpt =
11301     S.NSAPIObj->getNSArrayMethodKind(Sel);
11302   if (!MKOpt) {
11303     return None;
11304   }
11305 
11306   NSAPI::NSArrayMethodKind MK = *MKOpt;
11307 
11308   switch (MK) {
11309     case NSAPI::NSMutableArr_addObject:
11310     case NSAPI::NSMutableArr_insertObjectAtIndex:
11311     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
11312       return 0;
11313     case NSAPI::NSMutableArr_replaceObjectAtIndex:
11314       return 1;
11315 
11316     default:
11317       return None;
11318   }
11319 
11320   return None;
11321 }
11322 
11323 static
11324 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
11325                                                   ObjCMessageExpr *Message) {
11326   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
11327                                             Message->getReceiverInterface(),
11328                                             NSAPI::ClassId_NSMutableDictionary);
11329   if (!IsMutableDictionary) {
11330     return None;
11331   }
11332 
11333   Selector Sel = Message->getSelector();
11334 
11335   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11336     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
11337   if (!MKOpt) {
11338     return None;
11339   }
11340 
11341   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
11342 
11343   switch (MK) {
11344     case NSAPI::NSMutableDict_setObjectForKey:
11345     case NSAPI::NSMutableDict_setValueForKey:
11346     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
11347       return 0;
11348 
11349     default:
11350       return None;
11351   }
11352 
11353   return None;
11354 }
11355 
11356 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
11357   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
11358                                                 Message->getReceiverInterface(),
11359                                                 NSAPI::ClassId_NSMutableSet);
11360 
11361   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
11362                                             Message->getReceiverInterface(),
11363                                             NSAPI::ClassId_NSMutableOrderedSet);
11364   if (!IsMutableSet && !IsMutableOrderedSet) {
11365     return None;
11366   }
11367 
11368   Selector Sel = Message->getSelector();
11369 
11370   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
11371   if (!MKOpt) {
11372     return None;
11373   }
11374 
11375   NSAPI::NSSetMethodKind MK = *MKOpt;
11376 
11377   switch (MK) {
11378     case NSAPI::NSMutableSet_addObject:
11379     case NSAPI::NSOrderedSet_setObjectAtIndex:
11380     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
11381     case NSAPI::NSOrderedSet_insertObjectAtIndex:
11382       return 0;
11383     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
11384       return 1;
11385   }
11386 
11387   return None;
11388 }
11389 
11390 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
11391   if (!Message->isInstanceMessage()) {
11392     return;
11393   }
11394 
11395   Optional<int> ArgOpt;
11396 
11397   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
11398       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
11399       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
11400     return;
11401   }
11402 
11403   int ArgIndex = *ArgOpt;
11404 
11405   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
11406   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
11407     Arg = OE->getSourceExpr()->IgnoreImpCasts();
11408   }
11409 
11410   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
11411     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11412       if (ArgRE->isObjCSelfExpr()) {
11413         Diag(Message->getSourceRange().getBegin(),
11414              diag::warn_objc_circular_container)
11415           << ArgRE->getDecl()->getName() << StringRef("super");
11416       }
11417     }
11418   } else {
11419     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
11420 
11421     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
11422       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
11423     }
11424 
11425     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11426       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11427         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11428           ValueDecl *Decl = ReceiverRE->getDecl();
11429           Diag(Message->getSourceRange().getBegin(),
11430                diag::warn_objc_circular_container)
11431             << Decl->getName() << Decl->getName();
11432           if (!ArgRE->isObjCSelfExpr()) {
11433             Diag(Decl->getLocation(),
11434                  diag::note_objc_circular_container_declared_here)
11435               << Decl->getName();
11436           }
11437         }
11438       }
11439     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11440       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
11441         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11442           ObjCIvarDecl *Decl = IvarRE->getDecl();
11443           Diag(Message->getSourceRange().getBegin(),
11444                diag::warn_objc_circular_container)
11445             << Decl->getName() << Decl->getName();
11446           Diag(Decl->getLocation(),
11447                diag::note_objc_circular_container_declared_here)
11448             << Decl->getName();
11449         }
11450       }
11451     }
11452   }
11453 }
11454 
11455 /// Check a message send to see if it's likely to cause a retain cycle.
11456 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
11457   // Only check instance methods whose selector looks like a setter.
11458   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
11459     return;
11460 
11461   // Try to find a variable that the receiver is strongly owned by.
11462   RetainCycleOwner owner;
11463   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
11464     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
11465       return;
11466   } else {
11467     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
11468     owner.Variable = getCurMethodDecl()->getSelfDecl();
11469     owner.Loc = msg->getSuperLoc();
11470     owner.Range = msg->getSuperLoc();
11471   }
11472 
11473   // Check whether the receiver is captured by any of the arguments.
11474   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
11475     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
11476       return diagnoseRetainCycle(*this, capturer, owner);
11477 }
11478 
11479 /// Check a property assign to see if it's likely to cause a retain cycle.
11480 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
11481   RetainCycleOwner owner;
11482   if (!findRetainCycleOwner(*this, receiver, owner))
11483     return;
11484 
11485   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
11486     diagnoseRetainCycle(*this, capturer, owner);
11487 }
11488 
11489 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
11490   RetainCycleOwner Owner;
11491   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
11492     return;
11493 
11494   // Because we don't have an expression for the variable, we have to set the
11495   // location explicitly here.
11496   Owner.Loc = Var->getLocation();
11497   Owner.Range = Var->getSourceRange();
11498 
11499   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
11500     diagnoseRetainCycle(*this, Capturer, Owner);
11501 }
11502 
11503 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
11504                                      Expr *RHS, bool isProperty) {
11505   // Check if RHS is an Objective-C object literal, which also can get
11506   // immediately zapped in a weak reference.  Note that we explicitly
11507   // allow ObjCStringLiterals, since those are designed to never really die.
11508   RHS = RHS->IgnoreParenImpCasts();
11509 
11510   // This enum needs to match with the 'select' in
11511   // warn_objc_arc_literal_assign (off-by-1).
11512   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
11513   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
11514     return false;
11515 
11516   S.Diag(Loc, diag::warn_arc_literal_assign)
11517     << (unsigned) Kind
11518     << (isProperty ? 0 : 1)
11519     << RHS->getSourceRange();
11520 
11521   return true;
11522 }
11523 
11524 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
11525                                     Qualifiers::ObjCLifetime LT,
11526                                     Expr *RHS, bool isProperty) {
11527   // Strip off any implicit cast added to get to the one ARC-specific.
11528   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11529     if (cast->getCastKind() == CK_ARCConsumeObject) {
11530       S.Diag(Loc, diag::warn_arc_retained_assign)
11531         << (LT == Qualifiers::OCL_ExplicitNone)
11532         << (isProperty ? 0 : 1)
11533         << RHS->getSourceRange();
11534       return true;
11535     }
11536     RHS = cast->getSubExpr();
11537   }
11538 
11539   if (LT == Qualifiers::OCL_Weak &&
11540       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
11541     return true;
11542 
11543   return false;
11544 }
11545 
11546 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
11547                               QualType LHS, Expr *RHS) {
11548   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
11549 
11550   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
11551     return false;
11552 
11553   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
11554     return true;
11555 
11556   return false;
11557 }
11558 
11559 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
11560                               Expr *LHS, Expr *RHS) {
11561   QualType LHSType;
11562   // PropertyRef on LHS type need be directly obtained from
11563   // its declaration as it has a PseudoType.
11564   ObjCPropertyRefExpr *PRE
11565     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
11566   if (PRE && !PRE->isImplicitProperty()) {
11567     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11568     if (PD)
11569       LHSType = PD->getType();
11570   }
11571 
11572   if (LHSType.isNull())
11573     LHSType = LHS->getType();
11574 
11575   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
11576 
11577   if (LT == Qualifiers::OCL_Weak) {
11578     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11579       getCurFunction()->markSafeWeakUse(LHS);
11580   }
11581 
11582   if (checkUnsafeAssigns(Loc, LHSType, RHS))
11583     return;
11584 
11585   // FIXME. Check for other life times.
11586   if (LT != Qualifiers::OCL_None)
11587     return;
11588 
11589   if (PRE) {
11590     if (PRE->isImplicitProperty())
11591       return;
11592     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
11593     if (!PD)
11594       return;
11595 
11596     unsigned Attributes = PD->getPropertyAttributes();
11597     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
11598       // when 'assign' attribute was not explicitly specified
11599       // by user, ignore it and rely on property type itself
11600       // for lifetime info.
11601       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
11602       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11603           LHSType->isObjCRetainableType())
11604         return;
11605 
11606       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
11607         if (cast->getCastKind() == CK_ARCConsumeObject) {
11608           Diag(Loc, diag::warn_arc_retained_property_assign)
11609           << RHS->getSourceRange();
11610           return;
11611         }
11612         RHS = cast->getSubExpr();
11613       }
11614     }
11615     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
11616       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
11617         return;
11618     }
11619   }
11620 }
11621 
11622 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
11623 
11624 namespace {
11625 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
11626                                  SourceLocation StmtLoc,
11627                                  const NullStmt *Body) {
11628   // Do not warn if the body is a macro that expands to nothing, e.g:
11629   //
11630   // #define CALL(x)
11631   // if (condition)
11632   //   CALL(0);
11633   //
11634   if (Body->hasLeadingEmptyMacro())
11635     return false;
11636 
11637   // Get line numbers of statement and body.
11638   bool StmtLineInvalid;
11639   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
11640                                                       &StmtLineInvalid);
11641   if (StmtLineInvalid)
11642     return false;
11643 
11644   bool BodyLineInvalid;
11645   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
11646                                                       &BodyLineInvalid);
11647   if (BodyLineInvalid)
11648     return false;
11649 
11650   // Warn if null statement and body are on the same line.
11651   if (StmtLine != BodyLine)
11652     return false;
11653 
11654   return true;
11655 }
11656 } // end anonymous namespace
11657 
11658 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
11659                                  const Stmt *Body,
11660                                  unsigned DiagID) {
11661   // Since this is a syntactic check, don't emit diagnostic for template
11662   // instantiations, this just adds noise.
11663   if (CurrentInstantiationScope)
11664     return;
11665 
11666   // The body should be a null statement.
11667   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11668   if (!NBody)
11669     return;
11670 
11671   // Do the usual checks.
11672   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11673     return;
11674 
11675   Diag(NBody->getSemiLoc(), DiagID);
11676   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11677 }
11678 
11679 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
11680                                  const Stmt *PossibleBody) {
11681   assert(!CurrentInstantiationScope); // Ensured by caller
11682 
11683   SourceLocation StmtLoc;
11684   const Stmt *Body;
11685   unsigned DiagID;
11686   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11687     StmtLoc = FS->getRParenLoc();
11688     Body = FS->getBody();
11689     DiagID = diag::warn_empty_for_body;
11690   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11691     StmtLoc = WS->getCond()->getSourceRange().getEnd();
11692     Body = WS->getBody();
11693     DiagID = diag::warn_empty_while_body;
11694   } else
11695     return; // Neither `for' nor `while'.
11696 
11697   // The body should be a null statement.
11698   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
11699   if (!NBody)
11700     return;
11701 
11702   // Skip expensive checks if diagnostic is disabled.
11703   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
11704     return;
11705 
11706   // Do the usual checks.
11707   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11708     return;
11709 
11710   // `for(...);' and `while(...);' are popular idioms, so in order to keep
11711   // noise level low, emit diagnostics only if for/while is followed by a
11712   // CompoundStmt, e.g.:
11713   //    for (int i = 0; i < n; i++);
11714   //    {
11715   //      a(i);
11716   //    }
11717   // or if for/while is followed by a statement with more indentation
11718   // than for/while itself:
11719   //    for (int i = 0; i < n; i++);
11720   //      a(i);
11721   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11722   if (!ProbableTypo) {
11723     bool BodyColInvalid;
11724     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
11725                              PossibleBody->getLocStart(),
11726                              &BodyColInvalid);
11727     if (BodyColInvalid)
11728       return;
11729 
11730     bool StmtColInvalid;
11731     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
11732                              S->getLocStart(),
11733                              &StmtColInvalid);
11734     if (StmtColInvalid)
11735       return;
11736 
11737     if (BodyCol > StmtCol)
11738       ProbableTypo = true;
11739   }
11740 
11741   if (ProbableTypo) {
11742     Diag(NBody->getSemiLoc(), DiagID);
11743     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
11744   }
11745 }
11746 
11747 //===--- CHECK: Warn on self move with std::move. -------------------------===//
11748 
11749 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
11750 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
11751                              SourceLocation OpLoc) {
11752   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11753     return;
11754 
11755   if (inTemplateInstantiation())
11756     return;
11757 
11758   // Strip parens and casts away.
11759   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11760   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11761 
11762   // Check for a call expression
11763   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
11764   if (!CE || CE->getNumArgs() != 1)
11765     return;
11766 
11767   // Check for a call to std::move
11768   if (!CE->isCallToStdMove())
11769     return;
11770 
11771   // Get argument from std::move
11772   RHSExpr = CE->getArg(0);
11773 
11774   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11775   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11776 
11777   // Two DeclRefExpr's, check that the decls are the same.
11778   if (LHSDeclRef && RHSDeclRef) {
11779     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11780       return;
11781     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11782         RHSDeclRef->getDecl()->getCanonicalDecl())
11783       return;
11784 
11785     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11786                                         << LHSExpr->getSourceRange()
11787                                         << RHSExpr->getSourceRange();
11788     return;
11789   }
11790 
11791   // Member variables require a different approach to check for self moves.
11792   // MemberExpr's are the same if every nested MemberExpr refers to the same
11793   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
11794   // the base Expr's are CXXThisExpr's.
11795   const Expr *LHSBase = LHSExpr;
11796   const Expr *RHSBase = RHSExpr;
11797   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
11798   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
11799   if (!LHSME || !RHSME)
11800     return;
11801 
11802   while (LHSME && RHSME) {
11803     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
11804         RHSME->getMemberDecl()->getCanonicalDecl())
11805       return;
11806 
11807     LHSBase = LHSME->getBase();
11808     RHSBase = RHSME->getBase();
11809     LHSME = dyn_cast<MemberExpr>(LHSBase);
11810     RHSME = dyn_cast<MemberExpr>(RHSBase);
11811   }
11812 
11813   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
11814   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
11815   if (LHSDeclRef && RHSDeclRef) {
11816     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
11817       return;
11818     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
11819         RHSDeclRef->getDecl()->getCanonicalDecl())
11820       return;
11821 
11822     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11823                                         << LHSExpr->getSourceRange()
11824                                         << RHSExpr->getSourceRange();
11825     return;
11826   }
11827 
11828   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11829     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
11830                                         << LHSExpr->getSourceRange()
11831                                         << RHSExpr->getSourceRange();
11832 }
11833 
11834 //===--- Layout compatibility ----------------------------------------------//
11835 
11836 namespace {
11837 
11838 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
11839 
11840 /// \brief Check if two enumeration types are layout-compatible.
11841 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
11842   // C++11 [dcl.enum] p8:
11843   // Two enumeration types are layout-compatible if they have the same
11844   // underlying type.
11845   return ED1->isComplete() && ED2->isComplete() &&
11846          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
11847 }
11848 
11849 /// \brief Check if two fields are layout-compatible.
11850 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
11851   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
11852     return false;
11853 
11854   if (Field1->isBitField() != Field2->isBitField())
11855     return false;
11856 
11857   if (Field1->isBitField()) {
11858     // Make sure that the bit-fields are the same length.
11859     unsigned Bits1 = Field1->getBitWidthValue(C);
11860     unsigned Bits2 = Field2->getBitWidthValue(C);
11861 
11862     if (Bits1 != Bits2)
11863       return false;
11864   }
11865 
11866   return true;
11867 }
11868 
11869 /// \brief Check if two standard-layout structs are layout-compatible.
11870 /// (C++11 [class.mem] p17)
11871 bool isLayoutCompatibleStruct(ASTContext &C,
11872                               RecordDecl *RD1,
11873                               RecordDecl *RD2) {
11874   // If both records are C++ classes, check that base classes match.
11875   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11876     // If one of records is a CXXRecordDecl we are in C++ mode,
11877     // thus the other one is a CXXRecordDecl, too.
11878     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
11879     // Check number of base classes.
11880     if (D1CXX->getNumBases() != D2CXX->getNumBases())
11881       return false;
11882 
11883     // Check the base classes.
11884     for (CXXRecordDecl::base_class_const_iterator
11885                Base1 = D1CXX->bases_begin(),
11886            BaseEnd1 = D1CXX->bases_end(),
11887               Base2 = D2CXX->bases_begin();
11888          Base1 != BaseEnd1;
11889          ++Base1, ++Base2) {
11890       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11891         return false;
11892     }
11893   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11894     // If only RD2 is a C++ class, it should have zero base classes.
11895     if (D2CXX->getNumBases() > 0)
11896       return false;
11897   }
11898 
11899   // Check the fields.
11900   RecordDecl::field_iterator Field2 = RD2->field_begin(),
11901                              Field2End = RD2->field_end(),
11902                              Field1 = RD1->field_begin(),
11903                              Field1End = RD1->field_end();
11904   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11905     if (!isLayoutCompatible(C, *Field1, *Field2))
11906       return false;
11907   }
11908   if (Field1 != Field1End || Field2 != Field2End)
11909     return false;
11910 
11911   return true;
11912 }
11913 
11914 /// \brief Check if two standard-layout unions are layout-compatible.
11915 /// (C++11 [class.mem] p18)
11916 bool isLayoutCompatibleUnion(ASTContext &C,
11917                              RecordDecl *RD1,
11918                              RecordDecl *RD2) {
11919   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11920   for (auto *Field2 : RD2->fields())
11921     UnmatchedFields.insert(Field2);
11922 
11923   for (auto *Field1 : RD1->fields()) {
11924     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11925         I = UnmatchedFields.begin(),
11926         E = UnmatchedFields.end();
11927 
11928     for ( ; I != E; ++I) {
11929       if (isLayoutCompatible(C, Field1, *I)) {
11930         bool Result = UnmatchedFields.erase(*I);
11931         (void) Result;
11932         assert(Result);
11933         break;
11934       }
11935     }
11936     if (I == E)
11937       return false;
11938   }
11939 
11940   return UnmatchedFields.empty();
11941 }
11942 
11943 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
11944   if (RD1->isUnion() != RD2->isUnion())
11945     return false;
11946 
11947   if (RD1->isUnion())
11948     return isLayoutCompatibleUnion(C, RD1, RD2);
11949   else
11950     return isLayoutCompatibleStruct(C, RD1, RD2);
11951 }
11952 
11953 /// \brief Check if two types are layout-compatible in C++11 sense.
11954 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
11955   if (T1.isNull() || T2.isNull())
11956     return false;
11957 
11958   // C++11 [basic.types] p11:
11959   // If two types T1 and T2 are the same type, then T1 and T2 are
11960   // layout-compatible types.
11961   if (C.hasSameType(T1, T2))
11962     return true;
11963 
11964   T1 = T1.getCanonicalType().getUnqualifiedType();
11965   T2 = T2.getCanonicalType().getUnqualifiedType();
11966 
11967   const Type::TypeClass TC1 = T1->getTypeClass();
11968   const Type::TypeClass TC2 = T2->getTypeClass();
11969 
11970   if (TC1 != TC2)
11971     return false;
11972 
11973   if (TC1 == Type::Enum) {
11974     return isLayoutCompatible(C,
11975                               cast<EnumType>(T1)->getDecl(),
11976                               cast<EnumType>(T2)->getDecl());
11977   } else if (TC1 == Type::Record) {
11978     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
11979       return false;
11980 
11981     return isLayoutCompatible(C,
11982                               cast<RecordType>(T1)->getDecl(),
11983                               cast<RecordType>(T2)->getDecl());
11984   }
11985 
11986   return false;
11987 }
11988 } // end anonymous namespace
11989 
11990 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
11991 
11992 namespace {
11993 /// \brief Given a type tag expression find the type tag itself.
11994 ///
11995 /// \param TypeExpr Type tag expression, as it appears in user's code.
11996 ///
11997 /// \param VD Declaration of an identifier that appears in a type tag.
11998 ///
11999 /// \param MagicValue Type tag magic value.
12000 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
12001                      const ValueDecl **VD, uint64_t *MagicValue) {
12002   while(true) {
12003     if (!TypeExpr)
12004       return false;
12005 
12006     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
12007 
12008     switch (TypeExpr->getStmtClass()) {
12009     case Stmt::UnaryOperatorClass: {
12010       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
12011       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
12012         TypeExpr = UO->getSubExpr();
12013         continue;
12014       }
12015       return false;
12016     }
12017 
12018     case Stmt::DeclRefExprClass: {
12019       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
12020       *VD = DRE->getDecl();
12021       return true;
12022     }
12023 
12024     case Stmt::IntegerLiteralClass: {
12025       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
12026       llvm::APInt MagicValueAPInt = IL->getValue();
12027       if (MagicValueAPInt.getActiveBits() <= 64) {
12028         *MagicValue = MagicValueAPInt.getZExtValue();
12029         return true;
12030       } else
12031         return false;
12032     }
12033 
12034     case Stmt::BinaryConditionalOperatorClass:
12035     case Stmt::ConditionalOperatorClass: {
12036       const AbstractConditionalOperator *ACO =
12037           cast<AbstractConditionalOperator>(TypeExpr);
12038       bool Result;
12039       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
12040         if (Result)
12041           TypeExpr = ACO->getTrueExpr();
12042         else
12043           TypeExpr = ACO->getFalseExpr();
12044         continue;
12045       }
12046       return false;
12047     }
12048 
12049     case Stmt::BinaryOperatorClass: {
12050       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
12051       if (BO->getOpcode() == BO_Comma) {
12052         TypeExpr = BO->getRHS();
12053         continue;
12054       }
12055       return false;
12056     }
12057 
12058     default:
12059       return false;
12060     }
12061   }
12062 }
12063 
12064 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
12065 ///
12066 /// \param TypeExpr Expression that specifies a type tag.
12067 ///
12068 /// \param MagicValues Registered magic values.
12069 ///
12070 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
12071 ///        kind.
12072 ///
12073 /// \param TypeInfo Information about the corresponding C type.
12074 ///
12075 /// \returns true if the corresponding C type was found.
12076 bool GetMatchingCType(
12077         const IdentifierInfo *ArgumentKind,
12078         const Expr *TypeExpr, const ASTContext &Ctx,
12079         const llvm::DenseMap<Sema::TypeTagMagicValue,
12080                              Sema::TypeTagData> *MagicValues,
12081         bool &FoundWrongKind,
12082         Sema::TypeTagData &TypeInfo) {
12083   FoundWrongKind = false;
12084 
12085   // Variable declaration that has type_tag_for_datatype attribute.
12086   const ValueDecl *VD = nullptr;
12087 
12088   uint64_t MagicValue;
12089 
12090   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
12091     return false;
12092 
12093   if (VD) {
12094     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
12095       if (I->getArgumentKind() != ArgumentKind) {
12096         FoundWrongKind = true;
12097         return false;
12098       }
12099       TypeInfo.Type = I->getMatchingCType();
12100       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
12101       TypeInfo.MustBeNull = I->getMustBeNull();
12102       return true;
12103     }
12104     return false;
12105   }
12106 
12107   if (!MagicValues)
12108     return false;
12109 
12110   llvm::DenseMap<Sema::TypeTagMagicValue,
12111                  Sema::TypeTagData>::const_iterator I =
12112       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
12113   if (I == MagicValues->end())
12114     return false;
12115 
12116   TypeInfo = I->second;
12117   return true;
12118 }
12119 } // end anonymous namespace
12120 
12121 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
12122                                       uint64_t MagicValue, QualType Type,
12123                                       bool LayoutCompatible,
12124                                       bool MustBeNull) {
12125   if (!TypeTagForDatatypeMagicValues)
12126     TypeTagForDatatypeMagicValues.reset(
12127         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
12128 
12129   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
12130   (*TypeTagForDatatypeMagicValues)[Magic] =
12131       TypeTagData(Type, LayoutCompatible, MustBeNull);
12132 }
12133 
12134 namespace {
12135 bool IsSameCharType(QualType T1, QualType T2) {
12136   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
12137   if (!BT1)
12138     return false;
12139 
12140   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
12141   if (!BT2)
12142     return false;
12143 
12144   BuiltinType::Kind T1Kind = BT1->getKind();
12145   BuiltinType::Kind T2Kind = BT2->getKind();
12146 
12147   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
12148          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
12149          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
12150          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
12151 }
12152 } // end anonymous namespace
12153 
12154 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
12155                                     const Expr * const *ExprArgs) {
12156   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
12157   bool IsPointerAttr = Attr->getIsPointer();
12158 
12159   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
12160   bool FoundWrongKind;
12161   TypeTagData TypeInfo;
12162   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
12163                         TypeTagForDatatypeMagicValues.get(),
12164                         FoundWrongKind, TypeInfo)) {
12165     if (FoundWrongKind)
12166       Diag(TypeTagExpr->getExprLoc(),
12167            diag::warn_type_tag_for_datatype_wrong_kind)
12168         << TypeTagExpr->getSourceRange();
12169     return;
12170   }
12171 
12172   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
12173   if (IsPointerAttr) {
12174     // Skip implicit cast of pointer to `void *' (as a function argument).
12175     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
12176       if (ICE->getType()->isVoidPointerType() &&
12177           ICE->getCastKind() == CK_BitCast)
12178         ArgumentExpr = ICE->getSubExpr();
12179   }
12180   QualType ArgumentType = ArgumentExpr->getType();
12181 
12182   // Passing a `void*' pointer shouldn't trigger a warning.
12183   if (IsPointerAttr && ArgumentType->isVoidPointerType())
12184     return;
12185 
12186   if (TypeInfo.MustBeNull) {
12187     // Type tag with matching void type requires a null pointer.
12188     if (!ArgumentExpr->isNullPointerConstant(Context,
12189                                              Expr::NPC_ValueDependentIsNotNull)) {
12190       Diag(ArgumentExpr->getExprLoc(),
12191            diag::warn_type_safety_null_pointer_required)
12192           << ArgumentKind->getName()
12193           << ArgumentExpr->getSourceRange()
12194           << TypeTagExpr->getSourceRange();
12195     }
12196     return;
12197   }
12198 
12199   QualType RequiredType = TypeInfo.Type;
12200   if (IsPointerAttr)
12201     RequiredType = Context.getPointerType(RequiredType);
12202 
12203   bool mismatch = false;
12204   if (!TypeInfo.LayoutCompatible) {
12205     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
12206 
12207     // C++11 [basic.fundamental] p1:
12208     // Plain char, signed char, and unsigned char are three distinct types.
12209     //
12210     // But we treat plain `char' as equivalent to `signed char' or `unsigned
12211     // char' depending on the current char signedness mode.
12212     if (mismatch)
12213       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
12214                                            RequiredType->getPointeeType())) ||
12215           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12216         mismatch = false;
12217   } else
12218     if (IsPointerAttr)
12219       mismatch = !isLayoutCompatible(Context,
12220                                      ArgumentType->getPointeeType(),
12221                                      RequiredType->getPointeeType());
12222     else
12223       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12224 
12225   if (mismatch)
12226     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
12227         << ArgumentType << ArgumentKind
12228         << TypeInfo.LayoutCompatible << RequiredType
12229         << ArgumentExpr->getSourceRange()
12230         << TypeTagExpr->getSourceRange();
12231 }
12232 
12233 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
12234                                          CharUnits Alignment) {
12235   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12236 }
12237 
12238 void Sema::DiagnoseMisalignedMembers() {
12239   for (MisalignedMember &m : MisalignedMembers) {
12240     const NamedDecl *ND = m.RD;
12241     if (ND->getName().empty()) {
12242       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
12243         ND = TD;
12244     }
12245     Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12246         << m.MD << ND << m.E->getSourceRange();
12247   }
12248   MisalignedMembers.clear();
12249 }
12250 
12251 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
12252   E = E->IgnoreParens();
12253   if (!T->isPointerType() && !T->isIntegerType())
12254     return;
12255   if (isa<UnaryOperator>(E) &&
12256       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
12257     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12258     if (isa<MemberExpr>(Op)) {
12259       auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12260                           MisalignedMember(Op));
12261       if (MA != MisalignedMembers.end() &&
12262           (T->isIntegerType() ||
12263            (T->isPointerType() &&
12264             Context.getTypeAlignInChars(T->getPointeeType()) <= MA->Alignment)))
12265         MisalignedMembers.erase(MA);
12266     }
12267   }
12268 }
12269 
12270 void Sema::RefersToMemberWithReducedAlignment(
12271     Expr *E,
12272     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
12273         Action) {
12274   const auto *ME = dyn_cast<MemberExpr>(E);
12275   if (!ME)
12276     return;
12277 
12278   // No need to check expressions with an __unaligned-qualified type.
12279   if (E->getType().getQualifiers().hasUnaligned())
12280     return;
12281 
12282   // For a chain of MemberExpr like "a.b.c.d" this list
12283   // will keep FieldDecl's like [d, c, b].
12284   SmallVector<FieldDecl *, 4> ReverseMemberChain;
12285   const MemberExpr *TopME = nullptr;
12286   bool AnyIsPacked = false;
12287   do {
12288     QualType BaseType = ME->getBase()->getType();
12289     if (ME->isArrow())
12290       BaseType = BaseType->getPointeeType();
12291     RecordDecl *RD = BaseType->getAs<RecordType>()->getDecl();
12292     if (RD->isInvalidDecl())
12293       return;
12294 
12295     ValueDecl *MD = ME->getMemberDecl();
12296     auto *FD = dyn_cast<FieldDecl>(MD);
12297     // We do not care about non-data members.
12298     if (!FD || FD->isInvalidDecl())
12299       return;
12300 
12301     AnyIsPacked =
12302         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
12303     ReverseMemberChain.push_back(FD);
12304 
12305     TopME = ME;
12306     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
12307   } while (ME);
12308   assert(TopME && "We did not compute a topmost MemberExpr!");
12309 
12310   // Not the scope of this diagnostic.
12311   if (!AnyIsPacked)
12312     return;
12313 
12314   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
12315   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
12316   // TODO: The innermost base of the member expression may be too complicated.
12317   // For now, just disregard these cases. This is left for future
12318   // improvement.
12319   if (!DRE && !isa<CXXThisExpr>(TopBase))
12320       return;
12321 
12322   // Alignment expected by the whole expression.
12323   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
12324 
12325   // No need to do anything else with this case.
12326   if (ExpectedAlignment.isOne())
12327     return;
12328 
12329   // Synthesize offset of the whole access.
12330   CharUnits Offset;
12331   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12332        I++) {
12333     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
12334   }
12335 
12336   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
12337   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
12338       ReverseMemberChain.back()->getParent()->getTypeForDecl());
12339 
12340   // The base expression of the innermost MemberExpr may give
12341   // stronger guarantees than the class containing the member.
12342   if (DRE && !TopME->isArrow()) {
12343     const ValueDecl *VD = DRE->getDecl();
12344     if (!VD->getType()->isReferenceType())
12345       CompleteObjectAlignment =
12346           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
12347   }
12348 
12349   // Check if the synthesized offset fulfills the alignment.
12350   if (Offset % ExpectedAlignment != 0 ||
12351       // It may fulfill the offset it but the effective alignment may still be
12352       // lower than the expected expression alignment.
12353       CompleteObjectAlignment < ExpectedAlignment) {
12354     // If this happens, we want to determine a sensible culprit of this.
12355     // Intuitively, watching the chain of member expressions from right to
12356     // left, we start with the required alignment (as required by the field
12357     // type) but some packed attribute in that chain has reduced the alignment.
12358     // It may happen that another packed structure increases it again. But if
12359     // we are here such increase has not been enough. So pointing the first
12360     // FieldDecl that either is packed or else its RecordDecl is,
12361     // seems reasonable.
12362     FieldDecl *FD = nullptr;
12363     CharUnits Alignment;
12364     for (FieldDecl *FDI : ReverseMemberChain) {
12365       if (FDI->hasAttr<PackedAttr>() ||
12366           FDI->getParent()->hasAttr<PackedAttr>()) {
12367         FD = FDI;
12368         Alignment = std::min(
12369             Context.getTypeAlignInChars(FD->getType()),
12370             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
12371         break;
12372       }
12373     }
12374     assert(FD && "We did not find a packed FieldDecl!");
12375     Action(E, FD->getParent(), FD, Alignment);
12376   }
12377 }
12378 
12379 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
12380   using namespace std::placeholders;
12381   RefersToMemberWithReducedAlignment(
12382       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
12383                      _2, _3, _4));
12384 }
12385 
12386