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/Sema/SemaInternal.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/CharUnits.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/EvaluatedExprVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/ExprOpenMP.h"
25 #include "clang/AST/StmtCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/Analysis/Analyses/FormatString.h"
28 #include "clang/Basic/CharInfo.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 "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/Format.h"
40 #include "llvm/Support/Locale.h"
41 #include "llvm/Support/ConvertUTF.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <limits>
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 /// Check that the argument to __builtin_addressof is a glvalue, and set the
103 /// result type to the corresponding pointer type.
104 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
105   if (checkArgCount(S, TheCall, 1))
106     return true;
107 
108   ExprResult Arg(TheCall->getArg(0));
109   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
110   if (ResultType.isNull())
111     return true;
112 
113   TheCall->setArg(0, Arg.get());
114   TheCall->setType(ResultType);
115   return false;
116 }
117 
118 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall) {
119   if (checkArgCount(S, TheCall, 3))
120     return true;
121 
122   // First two arguments should be integers.
123   for (unsigned I = 0; I < 2; ++I) {
124     Expr *Arg = TheCall->getArg(I);
125     QualType Ty = Arg->getType();
126     if (!Ty->isIntegerType()) {
127       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
128           << Ty << Arg->getSourceRange();
129       return true;
130     }
131   }
132 
133   // Third argument should be a pointer to a non-const integer.
134   // IRGen correctly handles volatile, restrict, and address spaces, and
135   // the other qualifiers aren't possible.
136   {
137     Expr *Arg = TheCall->getArg(2);
138     QualType Ty = Arg->getType();
139     const auto *PtrTy = Ty->getAs<PointerType>();
140     if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
141           !PtrTy->getPointeeType().isConstQualified())) {
142       S.Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
143           << Ty << Arg->getSourceRange();
144       return true;
145     }
146   }
147 
148   return false;
149 }
150 
151 static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl,
152 		                  CallExpr *TheCall, unsigned SizeIdx,
153                                   unsigned DstSizeIdx) {
154   if (TheCall->getNumArgs() <= SizeIdx ||
155       TheCall->getNumArgs() <= DstSizeIdx)
156     return;
157 
158   const Expr *SizeArg = TheCall->getArg(SizeIdx);
159   const Expr *DstSizeArg = TheCall->getArg(DstSizeIdx);
160 
161   llvm::APSInt Size, DstSize;
162 
163   // find out if both sizes are known at compile time
164   if (!SizeArg->EvaluateAsInt(Size, S.Context) ||
165       !DstSizeArg->EvaluateAsInt(DstSize, S.Context))
166     return;
167 
168   if (Size.ule(DstSize))
169     return;
170 
171   // confirmed overflow so generate the diagnostic.
172   IdentifierInfo *FnName = FDecl->getIdentifier();
173   SourceLocation SL = TheCall->getLocStart();
174   SourceRange SR = TheCall->getSourceRange();
175 
176   S.Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
177 }
178 
179 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
180   if (checkArgCount(S, BuiltinCall, 2))
181     return true;
182 
183   SourceLocation BuiltinLoc = BuiltinCall->getLocStart();
184   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
185   Expr *Call = BuiltinCall->getArg(0);
186   Expr *Chain = BuiltinCall->getArg(1);
187 
188   if (Call->getStmtClass() != Stmt::CallExprClass) {
189     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
190         << Call->getSourceRange();
191     return true;
192   }
193 
194   auto CE = cast<CallExpr>(Call);
195   if (CE->getCallee()->getType()->isBlockPointerType()) {
196     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
197         << Call->getSourceRange();
198     return true;
199   }
200 
201   const Decl *TargetDecl = CE->getCalleeDecl();
202   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
203     if (FD->getBuiltinID()) {
204       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
205           << Call->getSourceRange();
206       return true;
207     }
208 
209   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
210     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
211         << Call->getSourceRange();
212     return true;
213   }
214 
215   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
216   if (ChainResult.isInvalid())
217     return true;
218   if (!ChainResult.get()->getType()->isPointerType()) {
219     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
220         << Chain->getSourceRange();
221     return true;
222   }
223 
224   QualType ReturnTy = CE->getCallReturnType(S.Context);
225   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
226   QualType BuiltinTy = S.Context.getFunctionType(
227       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
228   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
229 
230   Builtin =
231       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
232 
233   BuiltinCall->setType(CE->getType());
234   BuiltinCall->setValueKind(CE->getValueKind());
235   BuiltinCall->setObjectKind(CE->getObjectKind());
236   BuiltinCall->setCallee(Builtin);
237   BuiltinCall->setArg(1, ChainResult.get());
238 
239   return false;
240 }
241 
242 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
243                                      Scope::ScopeFlags NeededScopeFlags,
244                                      unsigned DiagID) {
245   // Scopes aren't available during instantiation. Fortunately, builtin
246   // functions cannot be template args so they cannot be formed through template
247   // instantiation. Therefore checking once during the parse is sufficient.
248   if (!SemaRef.ActiveTemplateInstantiations.empty())
249     return false;
250 
251   Scope *S = SemaRef.getCurScope();
252   while (S && !S->isSEHExceptScope())
253     S = S->getParent();
254   if (!S || !(S->getFlags() & NeededScopeFlags)) {
255     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
256     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
257         << DRE->getDecl()->getIdentifier();
258     return true;
259   }
260 
261   return false;
262 }
263 
264 /// Returns OpenCL access qual.
265 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
266     return D->getAttr<OpenCLAccessAttr>();
267 }
268 
269 /// Returns true if pipe element type is different from the pointer.
270 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
271   const Expr *Arg0 = Call->getArg(0);
272   // First argument type should always be pipe.
273   if (!Arg0->getType()->isPipeType()) {
274     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
275         << Call->getDirectCallee() << Arg0->getSourceRange();
276     return true;
277   }
278   OpenCLAccessAttr *AccessQual =
279       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
280   // Validates the access qualifier is compatible with the call.
281   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
282   // read_only and write_only, and assumed to be read_only if no qualifier is
283   // specified.
284   switch (Call->getDirectCallee()->getBuiltinID()) {
285   case Builtin::BIread_pipe:
286   case Builtin::BIreserve_read_pipe:
287   case Builtin::BIcommit_read_pipe:
288   case Builtin::BIwork_group_reserve_read_pipe:
289   case Builtin::BIsub_group_reserve_read_pipe:
290   case Builtin::BIwork_group_commit_read_pipe:
291   case Builtin::BIsub_group_commit_read_pipe:
292     if (!(!AccessQual || AccessQual->isReadOnly())) {
293       S.Diag(Arg0->getLocStart(),
294              diag::err_opencl_builtin_pipe_invalid_access_modifier)
295           << "read_only" << Arg0->getSourceRange();
296       return true;
297     }
298     break;
299   case Builtin::BIwrite_pipe:
300   case Builtin::BIreserve_write_pipe:
301   case Builtin::BIcommit_write_pipe:
302   case Builtin::BIwork_group_reserve_write_pipe:
303   case Builtin::BIsub_group_reserve_write_pipe:
304   case Builtin::BIwork_group_commit_write_pipe:
305   case Builtin::BIsub_group_commit_write_pipe:
306     if (!(AccessQual && AccessQual->isWriteOnly())) {
307       S.Diag(Arg0->getLocStart(),
308              diag::err_opencl_builtin_pipe_invalid_access_modifier)
309           << "write_only" << Arg0->getSourceRange();
310       return true;
311     }
312     break;
313   default:
314     break;
315   }
316   return false;
317 }
318 
319 /// Returns true if pipe element type is different from the pointer.
320 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
321   const Expr *Arg0 = Call->getArg(0);
322   const Expr *ArgIdx = Call->getArg(Idx);
323   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
324   const QualType EltTy = PipeTy->getElementType();
325   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
326   // The Idx argument should be a pointer and the type of the pointer and
327   // the type of pipe element should also be the same.
328   if (!ArgTy ||
329       !S.Context.hasSameType(
330           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
331     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
332         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
333         << ArgIdx->getType() << ArgIdx->getSourceRange();
334     return true;
335   }
336   return false;
337 }
338 
339 // \brief Performs semantic analysis for the read/write_pipe call.
340 // \param S Reference to the semantic analyzer.
341 // \param Call A pointer to the builtin call.
342 // \return True if a semantic error has been found, false otherwise.
343 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
344   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
345   // functions have two forms.
346   switch (Call->getNumArgs()) {
347   case 2: {
348     if (checkOpenCLPipeArg(S, Call))
349       return true;
350     // The call with 2 arguments should be
351     // read/write_pipe(pipe T, T*).
352     // Check packet type T.
353     if (checkOpenCLPipePacketType(S, Call, 1))
354       return true;
355   } break;
356 
357   case 4: {
358     if (checkOpenCLPipeArg(S, Call))
359       return true;
360     // The call with 4 arguments should be
361     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
362     // Check reserve_id_t.
363     if (!Call->getArg(1)->getType()->isReserveIDT()) {
364       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
365           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
366           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
367       return true;
368     }
369 
370     // Check the index.
371     const Expr *Arg2 = Call->getArg(2);
372     if (!Arg2->getType()->isIntegerType() &&
373         !Arg2->getType()->isUnsignedIntegerType()) {
374       S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
375           << Call->getDirectCallee() << S.Context.UnsignedIntTy
376           << Arg2->getType() << Arg2->getSourceRange();
377       return true;
378     }
379 
380     // Check packet type T.
381     if (checkOpenCLPipePacketType(S, Call, 3))
382       return true;
383   } break;
384   default:
385     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_arg_num)
386         << Call->getDirectCallee() << Call->getSourceRange();
387     return true;
388   }
389 
390   return false;
391 }
392 
393 // \brief Performs a semantic analysis on the {work_group_/sub_group_
394 //        /_}reserve_{read/write}_pipe
395 // \param S Reference to the semantic analyzer.
396 // \param Call The call to the builtin function to be analyzed.
397 // \return True if a semantic error was found, false otherwise.
398 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
399   if (checkArgCount(S, Call, 2))
400     return true;
401 
402   if (checkOpenCLPipeArg(S, Call))
403     return true;
404 
405   // Check the reserve size.
406   if (!Call->getArg(1)->getType()->isIntegerType() &&
407       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
408     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
409         << Call->getDirectCallee() << S.Context.UnsignedIntTy
410         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
411     return true;
412   }
413 
414   return false;
415 }
416 
417 // \brief Performs a semantic analysis on {work_group_/sub_group_
418 //        /_}commit_{read/write}_pipe
419 // \param S Reference to the semantic analyzer.
420 // \param Call The call to the builtin function to be analyzed.
421 // \return True if a semantic error was found, false otherwise.
422 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
423   if (checkArgCount(S, Call, 2))
424     return true;
425 
426   if (checkOpenCLPipeArg(S, Call))
427     return true;
428 
429   // Check reserve_id_t.
430   if (!Call->getArg(1)->getType()->isReserveIDT()) {
431     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_invalid_arg)
432         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
433         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
434     return true;
435   }
436 
437   return false;
438 }
439 
440 // \brief Performs a semantic analysis on the call to built-in Pipe
441 //        Query Functions.
442 // \param S Reference to the semantic analyzer.
443 // \param Call The call to the builtin function to be analyzed.
444 // \return True if a semantic error was found, false otherwise.
445 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
446   if (checkArgCount(S, Call, 1))
447     return true;
448 
449   if (!Call->getArg(0)->getType()->isPipeType()) {
450     S.Diag(Call->getLocStart(), diag::err_opencl_builtin_pipe_first_arg)
451         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
452     return true;
453   }
454 
455   return false;
456 }
457 
458 ExprResult
459 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
460                                CallExpr *TheCall) {
461   ExprResult TheCallResult(TheCall);
462 
463   // Find out if any arguments are required to be integer constant expressions.
464   unsigned ICEArguments = 0;
465   ASTContext::GetBuiltinTypeError Error;
466   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
467   if (Error != ASTContext::GE_None)
468     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
469 
470   // If any arguments are required to be ICE's, check and diagnose.
471   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
472     // Skip arguments not required to be ICE's.
473     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
474 
475     llvm::APSInt Result;
476     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
477       return true;
478     ICEArguments &= ~(1 << ArgNo);
479   }
480 
481   switch (BuiltinID) {
482   case Builtin::BI__builtin___CFStringMakeConstantString:
483     assert(TheCall->getNumArgs() == 1 &&
484            "Wrong # arguments to builtin CFStringMakeConstantString");
485     if (CheckObjCString(TheCall->getArg(0)))
486       return ExprError();
487     break;
488   case Builtin::BI__builtin_stdarg_start:
489   case Builtin::BI__builtin_va_start:
490     if (SemaBuiltinVAStart(TheCall))
491       return ExprError();
492     break;
493   case Builtin::BI__va_start: {
494     switch (Context.getTargetInfo().getTriple().getArch()) {
495     case llvm::Triple::arm:
496     case llvm::Triple::thumb:
497       if (SemaBuiltinVAStartARM(TheCall))
498         return ExprError();
499       break;
500     default:
501       if (SemaBuiltinVAStart(TheCall))
502         return ExprError();
503       break;
504     }
505     break;
506   }
507   case Builtin::BI__builtin_isgreater:
508   case Builtin::BI__builtin_isgreaterequal:
509   case Builtin::BI__builtin_isless:
510   case Builtin::BI__builtin_islessequal:
511   case Builtin::BI__builtin_islessgreater:
512   case Builtin::BI__builtin_isunordered:
513     if (SemaBuiltinUnorderedCompare(TheCall))
514       return ExprError();
515     break;
516   case Builtin::BI__builtin_fpclassify:
517     if (SemaBuiltinFPClassification(TheCall, 6))
518       return ExprError();
519     break;
520   case Builtin::BI__builtin_isfinite:
521   case Builtin::BI__builtin_isinf:
522   case Builtin::BI__builtin_isinf_sign:
523   case Builtin::BI__builtin_isnan:
524   case Builtin::BI__builtin_isnormal:
525     if (SemaBuiltinFPClassification(TheCall, 1))
526       return ExprError();
527     break;
528   case Builtin::BI__builtin_shufflevector:
529     return SemaBuiltinShuffleVector(TheCall);
530     // TheCall will be freed by the smart pointer here, but that's fine, since
531     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
532   case Builtin::BI__builtin_prefetch:
533     if (SemaBuiltinPrefetch(TheCall))
534       return ExprError();
535     break;
536   case Builtin::BI__assume:
537   case Builtin::BI__builtin_assume:
538     if (SemaBuiltinAssume(TheCall))
539       return ExprError();
540     break;
541   case Builtin::BI__builtin_assume_aligned:
542     if (SemaBuiltinAssumeAligned(TheCall))
543       return ExprError();
544     break;
545   case Builtin::BI__builtin_object_size:
546     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
547       return ExprError();
548     break;
549   case Builtin::BI__builtin_longjmp:
550     if (SemaBuiltinLongjmp(TheCall))
551       return ExprError();
552     break;
553   case Builtin::BI__builtin_setjmp:
554     if (SemaBuiltinSetjmp(TheCall))
555       return ExprError();
556     break;
557   case Builtin::BI_setjmp:
558   case Builtin::BI_setjmpex:
559     if (checkArgCount(*this, TheCall, 1))
560       return true;
561     break;
562 
563   case Builtin::BI__builtin_classify_type:
564     if (checkArgCount(*this, TheCall, 1)) return true;
565     TheCall->setType(Context.IntTy);
566     break;
567   case Builtin::BI__builtin_constant_p:
568     if (checkArgCount(*this, TheCall, 1)) return true;
569     TheCall->setType(Context.IntTy);
570     break;
571   case Builtin::BI__sync_fetch_and_add:
572   case Builtin::BI__sync_fetch_and_add_1:
573   case Builtin::BI__sync_fetch_and_add_2:
574   case Builtin::BI__sync_fetch_and_add_4:
575   case Builtin::BI__sync_fetch_and_add_8:
576   case Builtin::BI__sync_fetch_and_add_16:
577   case Builtin::BI__sync_fetch_and_sub:
578   case Builtin::BI__sync_fetch_and_sub_1:
579   case Builtin::BI__sync_fetch_and_sub_2:
580   case Builtin::BI__sync_fetch_and_sub_4:
581   case Builtin::BI__sync_fetch_and_sub_8:
582   case Builtin::BI__sync_fetch_and_sub_16:
583   case Builtin::BI__sync_fetch_and_or:
584   case Builtin::BI__sync_fetch_and_or_1:
585   case Builtin::BI__sync_fetch_and_or_2:
586   case Builtin::BI__sync_fetch_and_or_4:
587   case Builtin::BI__sync_fetch_and_or_8:
588   case Builtin::BI__sync_fetch_and_or_16:
589   case Builtin::BI__sync_fetch_and_and:
590   case Builtin::BI__sync_fetch_and_and_1:
591   case Builtin::BI__sync_fetch_and_and_2:
592   case Builtin::BI__sync_fetch_and_and_4:
593   case Builtin::BI__sync_fetch_and_and_8:
594   case Builtin::BI__sync_fetch_and_and_16:
595   case Builtin::BI__sync_fetch_and_xor:
596   case Builtin::BI__sync_fetch_and_xor_1:
597   case Builtin::BI__sync_fetch_and_xor_2:
598   case Builtin::BI__sync_fetch_and_xor_4:
599   case Builtin::BI__sync_fetch_and_xor_8:
600   case Builtin::BI__sync_fetch_and_xor_16:
601   case Builtin::BI__sync_fetch_and_nand:
602   case Builtin::BI__sync_fetch_and_nand_1:
603   case Builtin::BI__sync_fetch_and_nand_2:
604   case Builtin::BI__sync_fetch_and_nand_4:
605   case Builtin::BI__sync_fetch_and_nand_8:
606   case Builtin::BI__sync_fetch_and_nand_16:
607   case Builtin::BI__sync_add_and_fetch:
608   case Builtin::BI__sync_add_and_fetch_1:
609   case Builtin::BI__sync_add_and_fetch_2:
610   case Builtin::BI__sync_add_and_fetch_4:
611   case Builtin::BI__sync_add_and_fetch_8:
612   case Builtin::BI__sync_add_and_fetch_16:
613   case Builtin::BI__sync_sub_and_fetch:
614   case Builtin::BI__sync_sub_and_fetch_1:
615   case Builtin::BI__sync_sub_and_fetch_2:
616   case Builtin::BI__sync_sub_and_fetch_4:
617   case Builtin::BI__sync_sub_and_fetch_8:
618   case Builtin::BI__sync_sub_and_fetch_16:
619   case Builtin::BI__sync_and_and_fetch:
620   case Builtin::BI__sync_and_and_fetch_1:
621   case Builtin::BI__sync_and_and_fetch_2:
622   case Builtin::BI__sync_and_and_fetch_4:
623   case Builtin::BI__sync_and_and_fetch_8:
624   case Builtin::BI__sync_and_and_fetch_16:
625   case Builtin::BI__sync_or_and_fetch:
626   case Builtin::BI__sync_or_and_fetch_1:
627   case Builtin::BI__sync_or_and_fetch_2:
628   case Builtin::BI__sync_or_and_fetch_4:
629   case Builtin::BI__sync_or_and_fetch_8:
630   case Builtin::BI__sync_or_and_fetch_16:
631   case Builtin::BI__sync_xor_and_fetch:
632   case Builtin::BI__sync_xor_and_fetch_1:
633   case Builtin::BI__sync_xor_and_fetch_2:
634   case Builtin::BI__sync_xor_and_fetch_4:
635   case Builtin::BI__sync_xor_and_fetch_8:
636   case Builtin::BI__sync_xor_and_fetch_16:
637   case Builtin::BI__sync_nand_and_fetch:
638   case Builtin::BI__sync_nand_and_fetch_1:
639   case Builtin::BI__sync_nand_and_fetch_2:
640   case Builtin::BI__sync_nand_and_fetch_4:
641   case Builtin::BI__sync_nand_and_fetch_8:
642   case Builtin::BI__sync_nand_and_fetch_16:
643   case Builtin::BI__sync_val_compare_and_swap:
644   case Builtin::BI__sync_val_compare_and_swap_1:
645   case Builtin::BI__sync_val_compare_and_swap_2:
646   case Builtin::BI__sync_val_compare_and_swap_4:
647   case Builtin::BI__sync_val_compare_and_swap_8:
648   case Builtin::BI__sync_val_compare_and_swap_16:
649   case Builtin::BI__sync_bool_compare_and_swap:
650   case Builtin::BI__sync_bool_compare_and_swap_1:
651   case Builtin::BI__sync_bool_compare_and_swap_2:
652   case Builtin::BI__sync_bool_compare_and_swap_4:
653   case Builtin::BI__sync_bool_compare_and_swap_8:
654   case Builtin::BI__sync_bool_compare_and_swap_16:
655   case Builtin::BI__sync_lock_test_and_set:
656   case Builtin::BI__sync_lock_test_and_set_1:
657   case Builtin::BI__sync_lock_test_and_set_2:
658   case Builtin::BI__sync_lock_test_and_set_4:
659   case Builtin::BI__sync_lock_test_and_set_8:
660   case Builtin::BI__sync_lock_test_and_set_16:
661   case Builtin::BI__sync_lock_release:
662   case Builtin::BI__sync_lock_release_1:
663   case Builtin::BI__sync_lock_release_2:
664   case Builtin::BI__sync_lock_release_4:
665   case Builtin::BI__sync_lock_release_8:
666   case Builtin::BI__sync_lock_release_16:
667   case Builtin::BI__sync_swap:
668   case Builtin::BI__sync_swap_1:
669   case Builtin::BI__sync_swap_2:
670   case Builtin::BI__sync_swap_4:
671   case Builtin::BI__sync_swap_8:
672   case Builtin::BI__sync_swap_16:
673     return SemaBuiltinAtomicOverloaded(TheCallResult);
674   case Builtin::BI__builtin_nontemporal_load:
675   case Builtin::BI__builtin_nontemporal_store:
676     return SemaBuiltinNontemporalOverloaded(TheCallResult);
677 #define BUILTIN(ID, TYPE, ATTRS)
678 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
679   case Builtin::BI##ID: \
680     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
681 #include "clang/Basic/Builtins.def"
682   case Builtin::BI__builtin_annotation:
683     if (SemaBuiltinAnnotation(*this, TheCall))
684       return ExprError();
685     break;
686   case Builtin::BI__builtin_addressof:
687     if (SemaBuiltinAddressof(*this, TheCall))
688       return ExprError();
689     break;
690   case Builtin::BI__builtin_add_overflow:
691   case Builtin::BI__builtin_sub_overflow:
692   case Builtin::BI__builtin_mul_overflow:
693     if (SemaBuiltinOverflow(*this, TheCall))
694       return ExprError();
695     break;
696   case Builtin::BI__builtin_operator_new:
697   case Builtin::BI__builtin_operator_delete:
698     if (!getLangOpts().CPlusPlus) {
699       Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
700         << (BuiltinID == Builtin::BI__builtin_operator_new
701                 ? "__builtin_operator_new"
702                 : "__builtin_operator_delete")
703         << "C++";
704       return ExprError();
705     }
706     // CodeGen assumes it can find the global new and delete to call,
707     // so ensure that they are declared.
708     DeclareGlobalNewDelete();
709     break;
710 
711   // check secure string manipulation functions where overflows
712   // are detectable at compile time
713   case Builtin::BI__builtin___memcpy_chk:
714   case Builtin::BI__builtin___memmove_chk:
715   case Builtin::BI__builtin___memset_chk:
716   case Builtin::BI__builtin___strlcat_chk:
717   case Builtin::BI__builtin___strlcpy_chk:
718   case Builtin::BI__builtin___strncat_chk:
719   case Builtin::BI__builtin___strncpy_chk:
720   case Builtin::BI__builtin___stpncpy_chk:
721     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 2, 3);
722     break;
723   case Builtin::BI__builtin___memccpy_chk:
724     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 3, 4);
725     break;
726   case Builtin::BI__builtin___snprintf_chk:
727   case Builtin::BI__builtin___vsnprintf_chk:
728     SemaBuiltinMemChkCall(*this, FDecl, TheCall, 1, 3);
729     break;
730   case Builtin::BI__builtin_call_with_static_chain:
731     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
732       return ExprError();
733     break;
734   case Builtin::BI__exception_code:
735   case Builtin::BI_exception_code:
736     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
737                                  diag::err_seh___except_block))
738       return ExprError();
739     break;
740   case Builtin::BI__exception_info:
741   case Builtin::BI_exception_info:
742     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
743                                  diag::err_seh___except_filter))
744       return ExprError();
745     break;
746   case Builtin::BI__GetExceptionInfo:
747     if (checkArgCount(*this, TheCall, 1))
748       return ExprError();
749 
750     if (CheckCXXThrowOperand(
751             TheCall->getLocStart(),
752             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
753             TheCall))
754       return ExprError();
755 
756     TheCall->setType(Context.VoidPtrTy);
757     break;
758   case Builtin::BIread_pipe:
759   case Builtin::BIwrite_pipe:
760     // Since those two functions are declared with var args, we need a semantic
761     // check for the argument.
762     if (SemaBuiltinRWPipe(*this, TheCall))
763       return ExprError();
764     break;
765   case Builtin::BIreserve_read_pipe:
766   case Builtin::BIreserve_write_pipe:
767   case Builtin::BIwork_group_reserve_read_pipe:
768   case Builtin::BIwork_group_reserve_write_pipe:
769   case Builtin::BIsub_group_reserve_read_pipe:
770   case Builtin::BIsub_group_reserve_write_pipe:
771     if (SemaBuiltinReserveRWPipe(*this, TheCall))
772       return ExprError();
773     // Since return type of reserve_read/write_pipe built-in function is
774     // reserve_id_t, which is not defined in the builtin def file , we used int
775     // as return type and need to override the return type of these functions.
776     TheCall->setType(Context.OCLReserveIDTy);
777     break;
778   case Builtin::BIcommit_read_pipe:
779   case Builtin::BIcommit_write_pipe:
780   case Builtin::BIwork_group_commit_read_pipe:
781   case Builtin::BIwork_group_commit_write_pipe:
782   case Builtin::BIsub_group_commit_read_pipe:
783   case Builtin::BIsub_group_commit_write_pipe:
784     if (SemaBuiltinCommitRWPipe(*this, TheCall))
785       return ExprError();
786     break;
787   case Builtin::BIget_pipe_num_packets:
788   case Builtin::BIget_pipe_max_packets:
789     if (SemaBuiltinPipePackets(*this, TheCall))
790       return ExprError();
791     break;
792   }
793 
794   // Since the target specific builtins for each arch overlap, only check those
795   // of the arch we are compiling for.
796   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
797     switch (Context.getTargetInfo().getTriple().getArch()) {
798       case llvm::Triple::arm:
799       case llvm::Triple::armeb:
800       case llvm::Triple::thumb:
801       case llvm::Triple::thumbeb:
802         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
803           return ExprError();
804         break;
805       case llvm::Triple::aarch64:
806       case llvm::Triple::aarch64_be:
807         if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
808           return ExprError();
809         break;
810       case llvm::Triple::mips:
811       case llvm::Triple::mipsel:
812       case llvm::Triple::mips64:
813       case llvm::Triple::mips64el:
814         if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
815           return ExprError();
816         break;
817       case llvm::Triple::systemz:
818         if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
819           return ExprError();
820         break;
821       case llvm::Triple::x86:
822       case llvm::Triple::x86_64:
823         if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
824           return ExprError();
825         break;
826       case llvm::Triple::ppc:
827       case llvm::Triple::ppc64:
828       case llvm::Triple::ppc64le:
829         if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
830           return ExprError();
831         break;
832       default:
833         break;
834     }
835   }
836 
837   return TheCallResult;
838 }
839 
840 // Get the valid immediate range for the specified NEON type code.
841 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
842   NeonTypeFlags Type(t);
843   int IsQuad = ForceQuad ? true : Type.isQuad();
844   switch (Type.getEltType()) {
845   case NeonTypeFlags::Int8:
846   case NeonTypeFlags::Poly8:
847     return shift ? 7 : (8 << IsQuad) - 1;
848   case NeonTypeFlags::Int16:
849   case NeonTypeFlags::Poly16:
850     return shift ? 15 : (4 << IsQuad) - 1;
851   case NeonTypeFlags::Int32:
852     return shift ? 31 : (2 << IsQuad) - 1;
853   case NeonTypeFlags::Int64:
854   case NeonTypeFlags::Poly64:
855     return shift ? 63 : (1 << IsQuad) - 1;
856   case NeonTypeFlags::Poly128:
857     return shift ? 127 : (1 << IsQuad) - 1;
858   case NeonTypeFlags::Float16:
859     assert(!shift && "cannot shift float types!");
860     return (4 << IsQuad) - 1;
861   case NeonTypeFlags::Float32:
862     assert(!shift && "cannot shift float types!");
863     return (2 << IsQuad) - 1;
864   case NeonTypeFlags::Float64:
865     assert(!shift && "cannot shift float types!");
866     return (1 << IsQuad) - 1;
867   }
868   llvm_unreachable("Invalid NeonTypeFlag!");
869 }
870 
871 /// getNeonEltType - Return the QualType corresponding to the elements of
872 /// the vector type specified by the NeonTypeFlags.  This is used to check
873 /// the pointer arguments for Neon load/store intrinsics.
874 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
875                                bool IsPolyUnsigned, bool IsInt64Long) {
876   switch (Flags.getEltType()) {
877   case NeonTypeFlags::Int8:
878     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
879   case NeonTypeFlags::Int16:
880     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
881   case NeonTypeFlags::Int32:
882     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
883   case NeonTypeFlags::Int64:
884     if (IsInt64Long)
885       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
886     else
887       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
888                                 : Context.LongLongTy;
889   case NeonTypeFlags::Poly8:
890     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
891   case NeonTypeFlags::Poly16:
892     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
893   case NeonTypeFlags::Poly64:
894     if (IsInt64Long)
895       return Context.UnsignedLongTy;
896     else
897       return Context.UnsignedLongLongTy;
898   case NeonTypeFlags::Poly128:
899     break;
900   case NeonTypeFlags::Float16:
901     return Context.HalfTy;
902   case NeonTypeFlags::Float32:
903     return Context.FloatTy;
904   case NeonTypeFlags::Float64:
905     return Context.DoubleTy;
906   }
907   llvm_unreachable("Invalid NeonTypeFlag!");
908 }
909 
910 bool Sema::CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
911   llvm::APSInt Result;
912   uint64_t mask = 0;
913   unsigned TV = 0;
914   int PtrArgNum = -1;
915   bool HasConstPtr = false;
916   switch (BuiltinID) {
917 #define GET_NEON_OVERLOAD_CHECK
918 #include "clang/Basic/arm_neon.inc"
919 #undef GET_NEON_OVERLOAD_CHECK
920   }
921 
922   // For NEON intrinsics which are overloaded on vector element type, validate
923   // the immediate which specifies which variant to emit.
924   unsigned ImmArg = TheCall->getNumArgs()-1;
925   if (mask) {
926     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
927       return true;
928 
929     TV = Result.getLimitedValue(64);
930     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
931       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
932         << TheCall->getArg(ImmArg)->getSourceRange();
933   }
934 
935   if (PtrArgNum >= 0) {
936     // Check that pointer arguments have the specified type.
937     Expr *Arg = TheCall->getArg(PtrArgNum);
938     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
939       Arg = ICE->getSubExpr();
940     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
941     QualType RHSTy = RHS.get()->getType();
942 
943     llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
944     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
945     bool IsInt64Long =
946         Context.getTargetInfo().getInt64Type() == TargetInfo::SignedLong;
947     QualType EltTy =
948         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
949     if (HasConstPtr)
950       EltTy = EltTy.withConst();
951     QualType LHSTy = Context.getPointerType(EltTy);
952     AssignConvertType ConvTy;
953     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
954     if (RHS.isInvalid())
955       return true;
956     if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
957                                  RHS.get(), AA_Assigning))
958       return true;
959   }
960 
961   // For NEON intrinsics which take an immediate value as part of the
962   // instruction, range check them here.
963   unsigned i = 0, l = 0, u = 0;
964   switch (BuiltinID) {
965   default:
966     return false;
967 #define GET_NEON_IMMEDIATE_CHECK
968 #include "clang/Basic/arm_neon.inc"
969 #undef GET_NEON_IMMEDIATE_CHECK
970   }
971 
972   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
973 }
974 
975 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
976                                         unsigned MaxWidth) {
977   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
978           BuiltinID == ARM::BI__builtin_arm_ldaex ||
979           BuiltinID == ARM::BI__builtin_arm_strex ||
980           BuiltinID == ARM::BI__builtin_arm_stlex ||
981           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
982           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
983           BuiltinID == AArch64::BI__builtin_arm_strex ||
984           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
985          "unexpected ARM builtin");
986   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
987                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
988                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
989                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
990 
991   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
992 
993   // Ensure that we have the proper number of arguments.
994   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
995     return true;
996 
997   // Inspect the pointer argument of the atomic builtin.  This should always be
998   // a pointer type, whose element is an integral scalar or pointer type.
999   // Because it is a pointer type, we don't have to worry about any implicit
1000   // casts here.
1001   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
1002   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1003   if (PointerArgRes.isInvalid())
1004     return true;
1005   PointerArg = PointerArgRes.get();
1006 
1007   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
1008   if (!pointerType) {
1009     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1010       << PointerArg->getType() << PointerArg->getSourceRange();
1011     return true;
1012   }
1013 
1014   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
1015   // task is to insert the appropriate casts into the AST. First work out just
1016   // what the appropriate type is.
1017   QualType ValType = pointerType->getPointeeType();
1018   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
1019   if (IsLdrex)
1020     AddrType.addConst();
1021 
1022   // Issue a warning if the cast is dodgy.
1023   CastKind CastNeeded = CK_NoOp;
1024   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
1025     CastNeeded = CK_BitCast;
1026     Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1027       << PointerArg->getType()
1028       << Context.getPointerType(AddrType)
1029       << AA_Passing << PointerArg->getSourceRange();
1030   }
1031 
1032   // Finally, do the cast and replace the argument with the corrected version.
1033   AddrType = Context.getPointerType(AddrType);
1034   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1035   if (PointerArgRes.isInvalid())
1036     return true;
1037   PointerArg = PointerArgRes.get();
1038 
1039   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
1040 
1041   // In general, we allow ints, floats and pointers to be loaded and stored.
1042   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1043       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
1044     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1045       << PointerArg->getType() << PointerArg->getSourceRange();
1046     return true;
1047   }
1048 
1049   // But ARM doesn't have instructions to deal with 128-bit versions.
1050   if (Context.getTypeSize(ValType) > MaxWidth) {
1051     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
1052     Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1053       << PointerArg->getType() << PointerArg->getSourceRange();
1054     return true;
1055   }
1056 
1057   switch (ValType.getObjCLifetime()) {
1058   case Qualifiers::OCL_None:
1059   case Qualifiers::OCL_ExplicitNone:
1060     // okay
1061     break;
1062 
1063   case Qualifiers::OCL_Weak:
1064   case Qualifiers::OCL_Strong:
1065   case Qualifiers::OCL_Autoreleasing:
1066     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1067       << ValType << PointerArg->getSourceRange();
1068     return true;
1069   }
1070 
1071   if (IsLdrex) {
1072     TheCall->setType(ValType);
1073     return false;
1074   }
1075 
1076   // Initialize the argument to be stored.
1077   ExprResult ValArg = TheCall->getArg(0);
1078   InitializedEntity Entity = InitializedEntity::InitializeParameter(
1079       Context, ValType, /*consume*/ false);
1080   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
1081   if (ValArg.isInvalid())
1082     return true;
1083   TheCall->setArg(0, ValArg.get());
1084 
1085   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
1086   // but the custom checker bypasses all default analysis.
1087   TheCall->setType(Context.IntTy);
1088   return false;
1089 }
1090 
1091 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1092   llvm::APSInt Result;
1093 
1094   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1095       BuiltinID == ARM::BI__builtin_arm_ldaex ||
1096       BuiltinID == ARM::BI__builtin_arm_strex ||
1097       BuiltinID == ARM::BI__builtin_arm_stlex) {
1098     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1099   }
1100 
1101   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1102     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1103       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1104   }
1105 
1106   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1107       BuiltinID == ARM::BI__builtin_arm_wsr64)
1108     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
1109 
1110   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1111       BuiltinID == ARM::BI__builtin_arm_rsrp ||
1112       BuiltinID == ARM::BI__builtin_arm_wsr ||
1113       BuiltinID == ARM::BI__builtin_arm_wsrp)
1114     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1115 
1116   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1117     return true;
1118 
1119   // For intrinsics which take an immediate value as part of the instruction,
1120   // range check them here.
1121   unsigned i = 0, l = 0, u = 0;
1122   switch (BuiltinID) {
1123   default: return false;
1124   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
1125   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
1126   case ARM::BI__builtin_arm_vcvtr_f:
1127   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
1128   case ARM::BI__builtin_arm_dmb:
1129   case ARM::BI__builtin_arm_dsb:
1130   case ARM::BI__builtin_arm_isb:
1131   case ARM::BI__builtin_arm_dbg: l = 0; u = 15; break;
1132   }
1133 
1134   // FIXME: VFP Intrinsics should error if VFP not present.
1135   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1136 }
1137 
1138 bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
1139                                          CallExpr *TheCall) {
1140   llvm::APSInt Result;
1141 
1142   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1143       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1144       BuiltinID == AArch64::BI__builtin_arm_strex ||
1145       BuiltinID == AArch64::BI__builtin_arm_stlex) {
1146     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1147   }
1148 
1149   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1150     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1151       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1152       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1153       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1154   }
1155 
1156   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1157       BuiltinID == AArch64::BI__builtin_arm_wsr64)
1158     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1159 
1160   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1161       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1162       BuiltinID == AArch64::BI__builtin_arm_wsr ||
1163       BuiltinID == AArch64::BI__builtin_arm_wsrp)
1164     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
1165 
1166   if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1167     return true;
1168 
1169   // For intrinsics which take an immediate value as part of the instruction,
1170   // range check them here.
1171   unsigned i = 0, l = 0, u = 0;
1172   switch (BuiltinID) {
1173   default: return false;
1174   case AArch64::BI__builtin_arm_dmb:
1175   case AArch64::BI__builtin_arm_dsb:
1176   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
1177   }
1178 
1179   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1180 }
1181 
1182 bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1183   unsigned i = 0, l = 0, u = 0;
1184   switch (BuiltinID) {
1185   default: return false;
1186   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
1187   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
1188   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
1189   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
1190   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
1191   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
1192   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
1193   }
1194 
1195   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1196 }
1197 
1198 bool Sema::CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1199   unsigned i = 0, l = 0, u = 0;
1200   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1201                       BuiltinID == PPC::BI__builtin_divdeu ||
1202                       BuiltinID == PPC::BI__builtin_bpermd;
1203   bool IsTarget64Bit = Context.getTargetInfo()
1204                               .getTypeWidth(Context
1205                                             .getTargetInfo()
1206                                             .getIntPtrType()) == 64;
1207   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1208                        BuiltinID == PPC::BI__builtin_divweu ||
1209                        BuiltinID == PPC::BI__builtin_divde ||
1210                        BuiltinID == PPC::BI__builtin_divdeu;
1211 
1212   if (Is64BitBltin && !IsTarget64Bit)
1213       return Diag(TheCall->getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1214              << TheCall->getSourceRange();
1215 
1216   if ((IsBltinExtDiv && !Context.getTargetInfo().hasFeature("extdiv")) ||
1217       (BuiltinID == PPC::BI__builtin_bpermd &&
1218        !Context.getTargetInfo().hasFeature("bpermd")))
1219     return Diag(TheCall->getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1220            << TheCall->getSourceRange();
1221 
1222   switch (BuiltinID) {
1223   default: return false;
1224   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1225   case PPC::BI__builtin_altivec_crypto_vshasigmad:
1226     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1227            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1228   case PPC::BI__builtin_tbegin:
1229   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
1230   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
1231   case PPC::BI__builtin_tabortwc:
1232   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
1233   case PPC::BI__builtin_tabortwci:
1234   case PPC::BI__builtin_tabortdci:
1235     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1236            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1237   }
1238   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1239 }
1240 
1241 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
1242                                            CallExpr *TheCall) {
1243   if (BuiltinID == SystemZ::BI__builtin_tabort) {
1244     Expr *Arg = TheCall->getArg(0);
1245     llvm::APSInt AbortCode(32);
1246     if (Arg->isIntegerConstantExpr(AbortCode, Context) &&
1247         AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1248       return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1249              << Arg->getSourceRange();
1250   }
1251 
1252   // For intrinsics which take an immediate value as part of the instruction,
1253   // range check them here.
1254   unsigned i = 0, l = 0, u = 0;
1255   switch (BuiltinID) {
1256   default: return false;
1257   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
1258   case SystemZ::BI__builtin_s390_verimb:
1259   case SystemZ::BI__builtin_s390_verimh:
1260   case SystemZ::BI__builtin_s390_verimf:
1261   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
1262   case SystemZ::BI__builtin_s390_vfaeb:
1263   case SystemZ::BI__builtin_s390_vfaeh:
1264   case SystemZ::BI__builtin_s390_vfaef:
1265   case SystemZ::BI__builtin_s390_vfaebs:
1266   case SystemZ::BI__builtin_s390_vfaehs:
1267   case SystemZ::BI__builtin_s390_vfaefs:
1268   case SystemZ::BI__builtin_s390_vfaezb:
1269   case SystemZ::BI__builtin_s390_vfaezh:
1270   case SystemZ::BI__builtin_s390_vfaezf:
1271   case SystemZ::BI__builtin_s390_vfaezbs:
1272   case SystemZ::BI__builtin_s390_vfaezhs:
1273   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
1274   case SystemZ::BI__builtin_s390_vfidb:
1275     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1276            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1277   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
1278   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
1279   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
1280   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
1281   case SystemZ::BI__builtin_s390_vstrcb:
1282   case SystemZ::BI__builtin_s390_vstrch:
1283   case SystemZ::BI__builtin_s390_vstrcf:
1284   case SystemZ::BI__builtin_s390_vstrczb:
1285   case SystemZ::BI__builtin_s390_vstrczh:
1286   case SystemZ::BI__builtin_s390_vstrczf:
1287   case SystemZ::BI__builtin_s390_vstrcbs:
1288   case SystemZ::BI__builtin_s390_vstrchs:
1289   case SystemZ::BI__builtin_s390_vstrcfs:
1290   case SystemZ::BI__builtin_s390_vstrczbs:
1291   case SystemZ::BI__builtin_s390_vstrczhs:
1292   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
1293   }
1294   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1295 }
1296 
1297 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
1298 /// This checks that the target supports __builtin_cpu_supports and
1299 /// that the string argument is constant and valid.
1300 static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall) {
1301   Expr *Arg = TheCall->getArg(0);
1302 
1303   // Check if the argument is a string literal.
1304   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
1305     return S.Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
1306            << Arg->getSourceRange();
1307 
1308   // Check the contents of the string.
1309   StringRef Feature =
1310       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
1311   if (!S.Context.getTargetInfo().validateCpuSupports(Feature))
1312     return S.Diag(TheCall->getLocStart(), diag::err_invalid_cpu_supports)
1313            << Arg->getSourceRange();
1314   return false;
1315 }
1316 
1317 bool Sema::CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
1318   unsigned i = 0, l = 0, u = 0;
1319   switch (BuiltinID) {
1320   default:
1321     return false;
1322   case X86::BI__builtin_cpu_supports:
1323     return SemaBuiltinCpuSupports(*this, TheCall);
1324   case X86::BI__builtin_ms_va_start:
1325     return SemaBuiltinMSVAStart(TheCall);
1326   case X86::BI_mm_prefetch:
1327     i = 1;
1328     l = 0;
1329     u = 3;
1330     break;
1331   case X86::BI__builtin_ia32_sha1rnds4:
1332     i = 2;
1333     l = 0;
1334     u = 3;
1335     break;
1336   case X86::BI__builtin_ia32_vpermil2pd:
1337   case X86::BI__builtin_ia32_vpermil2pd256:
1338   case X86::BI__builtin_ia32_vpermil2ps:
1339   case X86::BI__builtin_ia32_vpermil2ps256:
1340     i = 3;
1341     l = 0;
1342     u = 3;
1343     break;
1344   case X86::BI__builtin_ia32_cmpb128_mask:
1345   case X86::BI__builtin_ia32_cmpw128_mask:
1346   case X86::BI__builtin_ia32_cmpd128_mask:
1347   case X86::BI__builtin_ia32_cmpq128_mask:
1348   case X86::BI__builtin_ia32_cmpb256_mask:
1349   case X86::BI__builtin_ia32_cmpw256_mask:
1350   case X86::BI__builtin_ia32_cmpd256_mask:
1351   case X86::BI__builtin_ia32_cmpq256_mask:
1352   case X86::BI__builtin_ia32_cmpb512_mask:
1353   case X86::BI__builtin_ia32_cmpw512_mask:
1354   case X86::BI__builtin_ia32_cmpd512_mask:
1355   case X86::BI__builtin_ia32_cmpq512_mask:
1356   case X86::BI__builtin_ia32_ucmpb128_mask:
1357   case X86::BI__builtin_ia32_ucmpw128_mask:
1358   case X86::BI__builtin_ia32_ucmpd128_mask:
1359   case X86::BI__builtin_ia32_ucmpq128_mask:
1360   case X86::BI__builtin_ia32_ucmpb256_mask:
1361   case X86::BI__builtin_ia32_ucmpw256_mask:
1362   case X86::BI__builtin_ia32_ucmpd256_mask:
1363   case X86::BI__builtin_ia32_ucmpq256_mask:
1364   case X86::BI__builtin_ia32_ucmpb512_mask:
1365   case X86::BI__builtin_ia32_ucmpw512_mask:
1366   case X86::BI__builtin_ia32_ucmpd512_mask:
1367   case X86::BI__builtin_ia32_ucmpq512_mask:
1368     i = 2;
1369     l = 0;
1370     u = 7;
1371     break;
1372   case X86::BI__builtin_ia32_roundps:
1373   case X86::BI__builtin_ia32_roundpd:
1374   case X86::BI__builtin_ia32_roundps256:
1375   case X86::BI__builtin_ia32_roundpd256:
1376     i = 1;
1377     l = 0;
1378     u = 15;
1379     break;
1380   case X86::BI__builtin_ia32_roundss:
1381   case X86::BI__builtin_ia32_roundsd:
1382     i = 2;
1383     l = 0;
1384     u = 15;
1385     break;
1386   case X86::BI__builtin_ia32_cmpps:
1387   case X86::BI__builtin_ia32_cmpss:
1388   case X86::BI__builtin_ia32_cmppd:
1389   case X86::BI__builtin_ia32_cmpsd:
1390   case X86::BI__builtin_ia32_cmpps256:
1391   case X86::BI__builtin_ia32_cmppd256:
1392   case X86::BI__builtin_ia32_cmpps512_mask:
1393   case X86::BI__builtin_ia32_cmppd512_mask:
1394     i = 2;
1395     l = 0;
1396     u = 31;
1397     break;
1398   case X86::BI__builtin_ia32_vpcomub:
1399   case X86::BI__builtin_ia32_vpcomuw:
1400   case X86::BI__builtin_ia32_vpcomud:
1401   case X86::BI__builtin_ia32_vpcomuq:
1402   case X86::BI__builtin_ia32_vpcomb:
1403   case X86::BI__builtin_ia32_vpcomw:
1404   case X86::BI__builtin_ia32_vpcomd:
1405   case X86::BI__builtin_ia32_vpcomq:
1406     i = 2;
1407     l = 0;
1408     u = 7;
1409     break;
1410   }
1411   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1412 }
1413 
1414 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
1415 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
1416 /// Returns true when the format fits the function and the FormatStringInfo has
1417 /// been populated.
1418 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
1419                                FormatStringInfo *FSI) {
1420   FSI->HasVAListArg = Format->getFirstArg() == 0;
1421   FSI->FormatIdx = Format->getFormatIdx() - 1;
1422   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1423 
1424   // The way the format attribute works in GCC, the implicit this argument
1425   // of member functions is counted. However, it doesn't appear in our own
1426   // lists, so decrement format_idx in that case.
1427   if (IsCXXMember) {
1428     if(FSI->FormatIdx == 0)
1429       return false;
1430     --FSI->FormatIdx;
1431     if (FSI->FirstDataArg != 0)
1432       --FSI->FirstDataArg;
1433   }
1434   return true;
1435 }
1436 
1437 /// Checks if a the given expression evaluates to null.
1438 ///
1439 /// \brief Returns true if the value evaluates to null.
1440 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
1441   // If the expression has non-null type, it doesn't evaluate to null.
1442   if (auto nullability
1443         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
1444     if (*nullability == NullabilityKind::NonNull)
1445       return false;
1446   }
1447 
1448   // As a special case, transparent unions initialized with zero are
1449   // considered null for the purposes of the nonnull attribute.
1450   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
1451     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1452       if (const CompoundLiteralExpr *CLE =
1453           dyn_cast<CompoundLiteralExpr>(Expr))
1454         if (const InitListExpr *ILE =
1455             dyn_cast<InitListExpr>(CLE->getInitializer()))
1456           Expr = ILE->getInit(0);
1457   }
1458 
1459   bool Result;
1460   return (!Expr->isValueDependent() &&
1461           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
1462           !Result);
1463 }
1464 
1465 static void CheckNonNullArgument(Sema &S,
1466                                  const Expr *ArgExpr,
1467                                  SourceLocation CallSiteLoc) {
1468   if (CheckNonNullExpr(S, ArgExpr))
1469     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
1470            S.PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1471 }
1472 
1473 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
1474   FormatStringInfo FSI;
1475   if ((GetFormatStringType(Format) == FST_NSString) &&
1476       getFormatStringInfo(Format, false, &FSI)) {
1477     Idx = FSI.FormatIdx;
1478     return true;
1479   }
1480   return false;
1481 }
1482 /// \brief Diagnose use of %s directive in an NSString which is being passed
1483 /// as formatting string to formatting method.
1484 static void
1485 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
1486                                         const NamedDecl *FDecl,
1487                                         Expr **Args,
1488                                         unsigned NumArgs) {
1489   unsigned Idx = 0;
1490   bool Format = false;
1491   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
1492   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
1493     Idx = 2;
1494     Format = true;
1495   }
1496   else
1497     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1498       if (S.GetFormatNSStringIdx(I, Idx)) {
1499         Format = true;
1500         break;
1501       }
1502     }
1503   if (!Format || NumArgs <= Idx)
1504     return;
1505   const Expr *FormatExpr = Args[Idx];
1506   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1507     FormatExpr = CSCE->getSubExpr();
1508   const StringLiteral *FormatString;
1509   if (const ObjCStringLiteral *OSL =
1510       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
1511     FormatString = OSL->getString();
1512   else
1513     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
1514   if (!FormatString)
1515     return;
1516   if (S.FormatStringHasSArg(FormatString)) {
1517     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
1518       << "%s" << 1 << 1;
1519     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
1520       << FDecl->getDeclName();
1521   }
1522 }
1523 
1524 /// Determine whether the given type has a non-null nullability annotation.
1525 static bool isNonNullType(ASTContext &ctx, QualType type) {
1526   if (auto nullability = type->getNullability(ctx))
1527     return *nullability == NullabilityKind::NonNull;
1528 
1529   return false;
1530 }
1531 
1532 static void CheckNonNullArguments(Sema &S,
1533                                   const NamedDecl *FDecl,
1534                                   const FunctionProtoType *Proto,
1535                                   ArrayRef<const Expr *> Args,
1536                                   SourceLocation CallSiteLoc) {
1537   assert((FDecl || Proto) && "Need a function declaration or prototype");
1538 
1539   // Check the attributes attached to the method/function itself.
1540   llvm::SmallBitVector NonNullArgs;
1541   if (FDecl) {
1542     // Handle the nonnull attribute on the function/method declaration itself.
1543     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
1544       if (!NonNull->args_size()) {
1545         // Easy case: all pointer arguments are nonnull.
1546         for (const auto *Arg : Args)
1547           if (S.isValidPointerAttrType(Arg->getType()))
1548             CheckNonNullArgument(S, Arg, CallSiteLoc);
1549         return;
1550       }
1551 
1552       for (unsigned Val : NonNull->args()) {
1553         if (Val >= Args.size())
1554           continue;
1555         if (NonNullArgs.empty())
1556           NonNullArgs.resize(Args.size());
1557         NonNullArgs.set(Val);
1558       }
1559     }
1560   }
1561 
1562   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1563     // Handle the nonnull attribute on the parameters of the
1564     // function/method.
1565     ArrayRef<ParmVarDecl*> parms;
1566     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1567       parms = FD->parameters();
1568     else
1569       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1570 
1571     unsigned ParamIndex = 0;
1572     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
1573          I != E; ++I, ++ParamIndex) {
1574       const ParmVarDecl *PVD = *I;
1575       if (PVD->hasAttr<NonNullAttr>() ||
1576           isNonNullType(S.Context, PVD->getType())) {
1577         if (NonNullArgs.empty())
1578           NonNullArgs.resize(Args.size());
1579 
1580         NonNullArgs.set(ParamIndex);
1581       }
1582     }
1583   } else {
1584     // If we have a non-function, non-method declaration but no
1585     // function prototype, try to dig out the function prototype.
1586     if (!Proto) {
1587       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1588         QualType type = VD->getType().getNonReferenceType();
1589         if (auto pointerType = type->getAs<PointerType>())
1590           type = pointerType->getPointeeType();
1591         else if (auto blockType = type->getAs<BlockPointerType>())
1592           type = blockType->getPointeeType();
1593         // FIXME: data member pointers?
1594 
1595         // Dig out the function prototype, if there is one.
1596         Proto = type->getAs<FunctionProtoType>();
1597       }
1598     }
1599 
1600     // Fill in non-null argument information from the nullability
1601     // information on the parameter types (if we have them).
1602     if (Proto) {
1603       unsigned Index = 0;
1604       for (auto paramType : Proto->getParamTypes()) {
1605         if (isNonNullType(S.Context, paramType)) {
1606           if (NonNullArgs.empty())
1607             NonNullArgs.resize(Args.size());
1608 
1609           NonNullArgs.set(Index);
1610         }
1611 
1612         ++Index;
1613       }
1614     }
1615   }
1616 
1617   // Check for non-null arguments.
1618   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1619        ArgIndex != ArgIndexEnd; ++ArgIndex) {
1620     if (NonNullArgs[ArgIndex])
1621       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
1622   }
1623 }
1624 
1625 /// Handles the checks for format strings, non-POD arguments to vararg
1626 /// functions, and NULL arguments passed to non-NULL parameters.
1627 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
1628                      ArrayRef<const Expr *> Args, bool IsMemberFunction,
1629                      SourceLocation Loc, SourceRange Range,
1630                      VariadicCallType CallType) {
1631   // FIXME: We should check as much as we can in the template definition.
1632   if (CurContext->isDependentContext())
1633     return;
1634 
1635   // Printf and scanf checking.
1636   llvm::SmallBitVector CheckedVarArgs;
1637   if (FDecl) {
1638     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
1639       // Only create vector if there are format attributes.
1640       CheckedVarArgs.resize(Args.size());
1641 
1642       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1643                            CheckedVarArgs);
1644     }
1645   }
1646 
1647   // Refuse POD arguments that weren't caught by the format string
1648   // checks above.
1649   if (CallType != VariadicDoesNotApply) {
1650     unsigned NumParams = Proto ? Proto->getNumParams()
1651                        : FDecl && isa<FunctionDecl>(FDecl)
1652                            ? cast<FunctionDecl>(FDecl)->getNumParams()
1653                        : FDecl && isa<ObjCMethodDecl>(FDecl)
1654                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
1655                        : 0;
1656 
1657     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1658       // Args[ArgIdx] can be null in malformed code.
1659       if (const Expr *Arg = Args[ArgIdx]) {
1660         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1661           checkVariadicArgument(Arg, CallType);
1662       }
1663     }
1664   }
1665 
1666   if (FDecl || Proto) {
1667     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
1668 
1669     // Type safety checking.
1670     if (FDecl) {
1671       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
1672         CheckArgumentWithTypeTag(I, Args.data());
1673     }
1674   }
1675 }
1676 
1677 /// CheckConstructorCall - Check a constructor call for correctness and safety
1678 /// properties not enforced by the C type system.
1679 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
1680                                 ArrayRef<const Expr *> Args,
1681                                 const FunctionProtoType *Proto,
1682                                 SourceLocation Loc) {
1683   VariadicCallType CallType =
1684     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1685   checkCall(FDecl, Proto, Args, /*IsMemberFunction=*/true, Loc, SourceRange(),
1686             CallType);
1687 }
1688 
1689 /// CheckFunctionCall - Check a direct function call for various correctness
1690 /// and safety properties not strictly enforced by the C type system.
1691 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
1692                              const FunctionProtoType *Proto) {
1693   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1694                               isa<CXXMethodDecl>(FDecl);
1695   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1696                           IsMemberOperatorCall;
1697   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1698                                                   TheCall->getCallee());
1699   Expr** Args = TheCall->getArgs();
1700   unsigned NumArgs = TheCall->getNumArgs();
1701   if (IsMemberOperatorCall) {
1702     // If this is a call to a member operator, hide the first argument
1703     // from checkCall.
1704     // FIXME: Our choice of AST representation here is less than ideal.
1705     ++Args;
1706     --NumArgs;
1707   }
1708   checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1709             IsMemberFunction, TheCall->getRParenLoc(),
1710             TheCall->getCallee()->getSourceRange(), CallType);
1711 
1712   IdentifierInfo *FnInfo = FDecl->getIdentifier();
1713   // None of the checks below are needed for functions that don't have
1714   // simple names (e.g., C++ conversion functions).
1715   if (!FnInfo)
1716     return false;
1717 
1718   CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1719   if (getLangOpts().ObjC1)
1720     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
1721 
1722   unsigned CMId = FDecl->getMemoryFunctionKind();
1723   if (CMId == 0)
1724     return false;
1725 
1726   // Handle memory setting and copying functions.
1727   if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1728     CheckStrlcpycatArguments(TheCall, FnInfo);
1729   else if (CMId == Builtin::BIstrncat)
1730     CheckStrncatArguments(TheCall, FnInfo);
1731   else
1732     CheckMemaccessArguments(TheCall, CMId, FnInfo);
1733 
1734   return false;
1735 }
1736 
1737 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
1738                                ArrayRef<const Expr *> Args) {
1739   VariadicCallType CallType =
1740       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1741 
1742   checkCall(Method, nullptr, Args,
1743             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
1744             CallType);
1745 
1746   return false;
1747 }
1748 
1749 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
1750                             const FunctionProtoType *Proto) {
1751   QualType Ty;
1752   if (const auto *V = dyn_cast<VarDecl>(NDecl))
1753     Ty = V->getType().getNonReferenceType();
1754   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
1755     Ty = F->getType().getNonReferenceType();
1756   else
1757     return false;
1758 
1759   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
1760       !Ty->isFunctionProtoType())
1761     return false;
1762 
1763   VariadicCallType CallType;
1764   if (!Proto || !Proto->isVariadic()) {
1765     CallType = VariadicDoesNotApply;
1766   } else if (Ty->isBlockPointerType()) {
1767     CallType = VariadicBlock;
1768   } else { // Ty->isFunctionPointerType()
1769     CallType = VariadicFunction;
1770   }
1771 
1772   checkCall(NDecl, Proto,
1773             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1774             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1775             TheCall->getCallee()->getSourceRange(), CallType);
1776 
1777   return false;
1778 }
1779 
1780 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
1781 /// such as function pointers returned from functions.
1782 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
1783   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
1784                                                   TheCall->getCallee());
1785   checkCall(/*FDecl=*/nullptr, Proto,
1786             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
1787             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
1788             TheCall->getCallee()->getSourceRange(), CallType);
1789 
1790   return false;
1791 }
1792 
1793 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
1794   if (!llvm::isValidAtomicOrderingCABI(Ordering))
1795     return false;
1796 
1797   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
1798   switch (Op) {
1799   case AtomicExpr::AO__c11_atomic_init:
1800     llvm_unreachable("There is no ordering argument for an init");
1801 
1802   case AtomicExpr::AO__c11_atomic_load:
1803   case AtomicExpr::AO__atomic_load_n:
1804   case AtomicExpr::AO__atomic_load:
1805     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
1806            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
1807 
1808   case AtomicExpr::AO__c11_atomic_store:
1809   case AtomicExpr::AO__atomic_store:
1810   case AtomicExpr::AO__atomic_store_n:
1811     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
1812            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
1813            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
1814 
1815   default:
1816     return true;
1817   }
1818 }
1819 
1820 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
1821                                          AtomicExpr::AtomicOp Op) {
1822   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
1823   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1824 
1825   // All these operations take one of the following forms:
1826   enum {
1827     // C    __c11_atomic_init(A *, C)
1828     Init,
1829     // C    __c11_atomic_load(A *, int)
1830     Load,
1831     // void __atomic_load(A *, CP, int)
1832     LoadCopy,
1833     // void __atomic_store(A *, CP, int)
1834     Copy,
1835     // C    __c11_atomic_add(A *, M, int)
1836     Arithmetic,
1837     // C    __atomic_exchange_n(A *, CP, int)
1838     Xchg,
1839     // void __atomic_exchange(A *, C *, CP, int)
1840     GNUXchg,
1841     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
1842     C11CmpXchg,
1843     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
1844     GNUCmpXchg
1845   } Form = Init;
1846   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
1847   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
1848   // where:
1849   //   C is an appropriate type,
1850   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
1851   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
1852   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
1853   //   the int parameters are for orderings.
1854 
1855   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1856                     AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1857                         AtomicExpr::AO__atomic_load,
1858                 "need to update code for modified C11 atomics");
1859   bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1860                Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1861   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1862              Op == AtomicExpr::AO__atomic_store_n ||
1863              Op == AtomicExpr::AO__atomic_exchange_n ||
1864              Op == AtomicExpr::AO__atomic_compare_exchange_n;
1865   bool IsAddSub = false;
1866 
1867   switch (Op) {
1868   case AtomicExpr::AO__c11_atomic_init:
1869     Form = Init;
1870     break;
1871 
1872   case AtomicExpr::AO__c11_atomic_load:
1873   case AtomicExpr::AO__atomic_load_n:
1874     Form = Load;
1875     break;
1876 
1877   case AtomicExpr::AO__atomic_load:
1878     Form = LoadCopy;
1879     break;
1880 
1881   case AtomicExpr::AO__c11_atomic_store:
1882   case AtomicExpr::AO__atomic_store:
1883   case AtomicExpr::AO__atomic_store_n:
1884     Form = Copy;
1885     break;
1886 
1887   case AtomicExpr::AO__c11_atomic_fetch_add:
1888   case AtomicExpr::AO__c11_atomic_fetch_sub:
1889   case AtomicExpr::AO__atomic_fetch_add:
1890   case AtomicExpr::AO__atomic_fetch_sub:
1891   case AtomicExpr::AO__atomic_add_fetch:
1892   case AtomicExpr::AO__atomic_sub_fetch:
1893     IsAddSub = true;
1894     // Fall through.
1895   case AtomicExpr::AO__c11_atomic_fetch_and:
1896   case AtomicExpr::AO__c11_atomic_fetch_or:
1897   case AtomicExpr::AO__c11_atomic_fetch_xor:
1898   case AtomicExpr::AO__atomic_fetch_and:
1899   case AtomicExpr::AO__atomic_fetch_or:
1900   case AtomicExpr::AO__atomic_fetch_xor:
1901   case AtomicExpr::AO__atomic_fetch_nand:
1902   case AtomicExpr::AO__atomic_and_fetch:
1903   case AtomicExpr::AO__atomic_or_fetch:
1904   case AtomicExpr::AO__atomic_xor_fetch:
1905   case AtomicExpr::AO__atomic_nand_fetch:
1906     Form = Arithmetic;
1907     break;
1908 
1909   case AtomicExpr::AO__c11_atomic_exchange:
1910   case AtomicExpr::AO__atomic_exchange_n:
1911     Form = Xchg;
1912     break;
1913 
1914   case AtomicExpr::AO__atomic_exchange:
1915     Form = GNUXchg;
1916     break;
1917 
1918   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1919   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1920     Form = C11CmpXchg;
1921     break;
1922 
1923   case AtomicExpr::AO__atomic_compare_exchange:
1924   case AtomicExpr::AO__atomic_compare_exchange_n:
1925     Form = GNUCmpXchg;
1926     break;
1927   }
1928 
1929   // Check we have the right number of arguments.
1930   if (TheCall->getNumArgs() < NumArgs[Form]) {
1931     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1932       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1933       << TheCall->getCallee()->getSourceRange();
1934     return ExprError();
1935   } else if (TheCall->getNumArgs() > NumArgs[Form]) {
1936     Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
1937          diag::err_typecheck_call_too_many_args)
1938       << 0 << NumArgs[Form] << TheCall->getNumArgs()
1939       << TheCall->getCallee()->getSourceRange();
1940     return ExprError();
1941   }
1942 
1943   // Inspect the first argument of the atomic operation.
1944   Expr *Ptr = TheCall->getArg(0);
1945   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1946   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1947   if (!pointerType) {
1948     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1949       << Ptr->getType() << Ptr->getSourceRange();
1950     return ExprError();
1951   }
1952 
1953   // For a __c11 builtin, this should be a pointer to an _Atomic type.
1954   QualType AtomTy = pointerType->getPointeeType(); // 'A'
1955   QualType ValType = AtomTy; // 'C'
1956   if (IsC11) {
1957     if (!AtomTy->isAtomicType()) {
1958       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1959         << Ptr->getType() << Ptr->getSourceRange();
1960       return ExprError();
1961     }
1962     if (AtomTy.isConstQualified()) {
1963       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1964         << Ptr->getType() << Ptr->getSourceRange();
1965       return ExprError();
1966     }
1967     ValType = AtomTy->getAs<AtomicType>()->getValueType();
1968   } else if (Form != Load && Form != LoadCopy) {
1969     if (ValType.isConstQualified()) {
1970       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1971         << Ptr->getType() << Ptr->getSourceRange();
1972       return ExprError();
1973     }
1974   }
1975 
1976   // For an arithmetic operation, the implied arithmetic must be well-formed.
1977   if (Form == Arithmetic) {
1978     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1979     if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1980       Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1981         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1982       return ExprError();
1983     }
1984     if (!IsAddSub && !ValType->isIntegerType()) {
1985       Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1986         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1987       return ExprError();
1988     }
1989     if (IsC11 && ValType->isPointerType() &&
1990         RequireCompleteType(Ptr->getLocStart(), ValType->getPointeeType(),
1991                             diag::err_incomplete_type)) {
1992       return ExprError();
1993     }
1994   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1995     // For __atomic_*_n operations, the value type must be a scalar integral or
1996     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1997     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1998       << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1999     return ExprError();
2000   }
2001 
2002   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
2003       !AtomTy->isScalarType()) {
2004     // For GNU atomics, require a trivially-copyable type. This is not part of
2005     // the GNU atomics specification, but we enforce it for sanity.
2006     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2007       << Ptr->getType() << Ptr->getSourceRange();
2008     return ExprError();
2009   }
2010 
2011   switch (ValType.getObjCLifetime()) {
2012   case Qualifiers::OCL_None:
2013   case Qualifiers::OCL_ExplicitNone:
2014     // okay
2015     break;
2016 
2017   case Qualifiers::OCL_Weak:
2018   case Qualifiers::OCL_Strong:
2019   case Qualifiers::OCL_Autoreleasing:
2020     // FIXME: Can this happen? By this point, ValType should be known
2021     // to be trivially copyable.
2022     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2023       << ValType << Ptr->getSourceRange();
2024     return ExprError();
2025   }
2026 
2027   // atomic_fetch_or takes a pointer to a volatile 'A'.  We shouldn't let the
2028   // volatile-ness of the pointee-type inject itself into the result or the
2029   // other operands. Similarly atomic_load can take a pointer to a const 'A'.
2030   ValType.removeLocalVolatile();
2031   ValType.removeLocalConst();
2032   QualType ResultType = ValType;
2033   if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2034     ResultType = Context.VoidTy;
2035   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2036     ResultType = Context.BoolTy;
2037 
2038   // The type of a parameter passed 'by value'. In the GNU atomics, such
2039   // arguments are actually passed as pointers.
2040   QualType ByValType = ValType; // 'CP'
2041   if (!IsC11 && !IsN)
2042     ByValType = Ptr->getType();
2043 
2044   // The first argument --- the pointer --- has a fixed type; we
2045   // deduce the types of the rest of the arguments accordingly.  Walk
2046   // the remaining arguments, converting them to the deduced value type.
2047   for (unsigned i = 1; i != NumArgs[Form]; ++i) {
2048     QualType Ty;
2049     if (i < NumVals[Form] + 1) {
2050       switch (i) {
2051       case 1:
2052         // The second argument is the non-atomic operand. For arithmetic, this
2053         // is always passed by value, and for a compare_exchange it is always
2054         // passed by address. For the rest, GNU uses by-address and C11 uses
2055         // by-value.
2056         assert(Form != Load);
2057         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
2058           Ty = ValType;
2059         else if (Form == Copy || Form == Xchg)
2060           Ty = ByValType;
2061         else if (Form == Arithmetic)
2062           Ty = Context.getPointerDiffType();
2063         else {
2064           Expr *ValArg = TheCall->getArg(i);
2065           unsigned AS = 0;
2066           // Keep address space of non-atomic pointer type.
2067           if (const PointerType *PtrTy =
2068                   ValArg->getType()->getAs<PointerType>()) {
2069             AS = PtrTy->getPointeeType().getAddressSpace();
2070           }
2071           Ty = Context.getPointerType(
2072               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
2073         }
2074         break;
2075       case 2:
2076         // The third argument to compare_exchange / GNU exchange is a
2077         // (pointer to a) desired value.
2078         Ty = ByValType;
2079         break;
2080       case 3:
2081         // The fourth argument to GNU compare_exchange is a 'weak' flag.
2082         Ty = Context.BoolTy;
2083         break;
2084       }
2085     } else {
2086       // The order(s) are always converted to int.
2087       Ty = Context.IntTy;
2088     }
2089 
2090     InitializedEntity Entity =
2091         InitializedEntity::InitializeParameter(Context, Ty, false);
2092     ExprResult Arg = TheCall->getArg(i);
2093     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2094     if (Arg.isInvalid())
2095       return true;
2096     TheCall->setArg(i, Arg.get());
2097   }
2098 
2099   // Permute the arguments into a 'consistent' order.
2100   SmallVector<Expr*, 5> SubExprs;
2101   SubExprs.push_back(Ptr);
2102   switch (Form) {
2103   case Init:
2104     // Note, AtomicExpr::getVal1() has a special case for this atomic.
2105     SubExprs.push_back(TheCall->getArg(1)); // Val1
2106     break;
2107   case Load:
2108     SubExprs.push_back(TheCall->getArg(1)); // Order
2109     break;
2110   case LoadCopy:
2111   case Copy:
2112   case Arithmetic:
2113   case Xchg:
2114     SubExprs.push_back(TheCall->getArg(2)); // Order
2115     SubExprs.push_back(TheCall->getArg(1)); // Val1
2116     break;
2117   case GNUXchg:
2118     // Note, AtomicExpr::getVal2() has a special case for this atomic.
2119     SubExprs.push_back(TheCall->getArg(3)); // Order
2120     SubExprs.push_back(TheCall->getArg(1)); // Val1
2121     SubExprs.push_back(TheCall->getArg(2)); // Val2
2122     break;
2123   case C11CmpXchg:
2124     SubExprs.push_back(TheCall->getArg(3)); // Order
2125     SubExprs.push_back(TheCall->getArg(1)); // Val1
2126     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
2127     SubExprs.push_back(TheCall->getArg(2)); // Val2
2128     break;
2129   case GNUCmpXchg:
2130     SubExprs.push_back(TheCall->getArg(4)); // Order
2131     SubExprs.push_back(TheCall->getArg(1)); // Val1
2132     SubExprs.push_back(TheCall->getArg(5)); // OrderFail
2133     SubExprs.push_back(TheCall->getArg(2)); // Val2
2134     SubExprs.push_back(TheCall->getArg(3)); // Weak
2135     break;
2136   }
2137 
2138   if (SubExprs.size() >= 2 && Form != Init) {
2139     llvm::APSInt Result(32);
2140     if (SubExprs[1]->isIntegerConstantExpr(Result, Context) &&
2141         !isValidOrderingForOp(Result.getSExtValue(), Op))
2142       Diag(SubExprs[1]->getLocStart(),
2143            diag::warn_atomic_op_has_invalid_memory_order)
2144           << SubExprs[1]->getSourceRange();
2145   }
2146 
2147   AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
2148                                             SubExprs, ResultType, Op,
2149                                             TheCall->getRParenLoc());
2150 
2151   if ((Op == AtomicExpr::AO__c11_atomic_load ||
2152        (Op == AtomicExpr::AO__c11_atomic_store)) &&
2153       Context.AtomicUsesUnsupportedLibcall(AE))
2154     Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
2155     ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
2156 
2157   return AE;
2158 }
2159 
2160 /// checkBuiltinArgument - Given a call to a builtin function, perform
2161 /// normal type-checking on the given argument, updating the call in
2162 /// place.  This is useful when a builtin function requires custom
2163 /// type-checking for some of its arguments but not necessarily all of
2164 /// them.
2165 ///
2166 /// Returns true on error.
2167 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
2168   FunctionDecl *Fn = E->getDirectCallee();
2169   assert(Fn && "builtin call without direct callee!");
2170 
2171   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
2172   InitializedEntity Entity =
2173     InitializedEntity::InitializeParameter(S.Context, Param);
2174 
2175   ExprResult Arg = E->getArg(0);
2176   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
2177   if (Arg.isInvalid())
2178     return true;
2179 
2180   E->setArg(ArgIndex, Arg.get());
2181   return false;
2182 }
2183 
2184 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
2185 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
2186 /// type of its first argument.  The main ActOnCallExpr routines have already
2187 /// promoted the types of arguments because all of these calls are prototyped as
2188 /// void(...).
2189 ///
2190 /// This function goes through and does final semantic checking for these
2191 /// builtins,
2192 ExprResult
2193 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
2194   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2195   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2196   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2197 
2198   // Ensure that we have at least one argument to do type inference from.
2199   if (TheCall->getNumArgs() < 1) {
2200     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2201       << 0 << 1 << TheCall->getNumArgs()
2202       << TheCall->getCallee()->getSourceRange();
2203     return ExprError();
2204   }
2205 
2206   // Inspect the first argument of the atomic builtin.  This should always be
2207   // a pointer type, whose element is an integral scalar or pointer type.
2208   // Because it is a pointer type, we don't have to worry about any implicit
2209   // casts here.
2210   // FIXME: We don't allow floating point scalars as input.
2211   Expr *FirstArg = TheCall->getArg(0);
2212   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
2213   if (FirstArgResult.isInvalid())
2214     return ExprError();
2215   FirstArg = FirstArgResult.get();
2216   TheCall->setArg(0, FirstArg);
2217 
2218   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
2219   if (!pointerType) {
2220     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2221       << FirstArg->getType() << FirstArg->getSourceRange();
2222     return ExprError();
2223   }
2224 
2225   QualType ValType = pointerType->getPointeeType();
2226   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2227       !ValType->isBlockPointerType()) {
2228     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
2229       << FirstArg->getType() << FirstArg->getSourceRange();
2230     return ExprError();
2231   }
2232 
2233   switch (ValType.getObjCLifetime()) {
2234   case Qualifiers::OCL_None:
2235   case Qualifiers::OCL_ExplicitNone:
2236     // okay
2237     break;
2238 
2239   case Qualifiers::OCL_Weak:
2240   case Qualifiers::OCL_Strong:
2241   case Qualifiers::OCL_Autoreleasing:
2242     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2243       << ValType << FirstArg->getSourceRange();
2244     return ExprError();
2245   }
2246 
2247   // Strip any qualifiers off ValType.
2248   ValType = ValType.getUnqualifiedType();
2249 
2250   // The majority of builtins return a value, but a few have special return
2251   // types, so allow them to override appropriately below.
2252   QualType ResultType = ValType;
2253 
2254   // We need to figure out which concrete builtin this maps onto.  For example,
2255   // __sync_fetch_and_add with a 2 byte object turns into
2256   // __sync_fetch_and_add_2.
2257 #define BUILTIN_ROW(x) \
2258   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2259     Builtin::BI##x##_8, Builtin::BI##x##_16 }
2260 
2261   static const unsigned BuiltinIndices[][5] = {
2262     BUILTIN_ROW(__sync_fetch_and_add),
2263     BUILTIN_ROW(__sync_fetch_and_sub),
2264     BUILTIN_ROW(__sync_fetch_and_or),
2265     BUILTIN_ROW(__sync_fetch_and_and),
2266     BUILTIN_ROW(__sync_fetch_and_xor),
2267     BUILTIN_ROW(__sync_fetch_and_nand),
2268 
2269     BUILTIN_ROW(__sync_add_and_fetch),
2270     BUILTIN_ROW(__sync_sub_and_fetch),
2271     BUILTIN_ROW(__sync_and_and_fetch),
2272     BUILTIN_ROW(__sync_or_and_fetch),
2273     BUILTIN_ROW(__sync_xor_and_fetch),
2274     BUILTIN_ROW(__sync_nand_and_fetch),
2275 
2276     BUILTIN_ROW(__sync_val_compare_and_swap),
2277     BUILTIN_ROW(__sync_bool_compare_and_swap),
2278     BUILTIN_ROW(__sync_lock_test_and_set),
2279     BUILTIN_ROW(__sync_lock_release),
2280     BUILTIN_ROW(__sync_swap)
2281   };
2282 #undef BUILTIN_ROW
2283 
2284   // Determine the index of the size.
2285   unsigned SizeIndex;
2286   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
2287   case 1: SizeIndex = 0; break;
2288   case 2: SizeIndex = 1; break;
2289   case 4: SizeIndex = 2; break;
2290   case 8: SizeIndex = 3; break;
2291   case 16: SizeIndex = 4; break;
2292   default:
2293     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
2294       << FirstArg->getType() << FirstArg->getSourceRange();
2295     return ExprError();
2296   }
2297 
2298   // Each of these builtins has one pointer argument, followed by some number of
2299   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
2300   // that we ignore.  Find out which row of BuiltinIndices to read from as well
2301   // as the number of fixed args.
2302   unsigned BuiltinID = FDecl->getBuiltinID();
2303   unsigned BuiltinIndex, NumFixed = 1;
2304   bool WarnAboutSemanticsChange = false;
2305   switch (BuiltinID) {
2306   default: llvm_unreachable("Unknown overloaded atomic builtin!");
2307   case Builtin::BI__sync_fetch_and_add:
2308   case Builtin::BI__sync_fetch_and_add_1:
2309   case Builtin::BI__sync_fetch_and_add_2:
2310   case Builtin::BI__sync_fetch_and_add_4:
2311   case Builtin::BI__sync_fetch_and_add_8:
2312   case Builtin::BI__sync_fetch_and_add_16:
2313     BuiltinIndex = 0;
2314     break;
2315 
2316   case Builtin::BI__sync_fetch_and_sub:
2317   case Builtin::BI__sync_fetch_and_sub_1:
2318   case Builtin::BI__sync_fetch_and_sub_2:
2319   case Builtin::BI__sync_fetch_and_sub_4:
2320   case Builtin::BI__sync_fetch_and_sub_8:
2321   case Builtin::BI__sync_fetch_and_sub_16:
2322     BuiltinIndex = 1;
2323     break;
2324 
2325   case Builtin::BI__sync_fetch_and_or:
2326   case Builtin::BI__sync_fetch_and_or_1:
2327   case Builtin::BI__sync_fetch_and_or_2:
2328   case Builtin::BI__sync_fetch_and_or_4:
2329   case Builtin::BI__sync_fetch_and_or_8:
2330   case Builtin::BI__sync_fetch_and_or_16:
2331     BuiltinIndex = 2;
2332     break;
2333 
2334   case Builtin::BI__sync_fetch_and_and:
2335   case Builtin::BI__sync_fetch_and_and_1:
2336   case Builtin::BI__sync_fetch_and_and_2:
2337   case Builtin::BI__sync_fetch_and_and_4:
2338   case Builtin::BI__sync_fetch_and_and_8:
2339   case Builtin::BI__sync_fetch_and_and_16:
2340     BuiltinIndex = 3;
2341     break;
2342 
2343   case Builtin::BI__sync_fetch_and_xor:
2344   case Builtin::BI__sync_fetch_and_xor_1:
2345   case Builtin::BI__sync_fetch_and_xor_2:
2346   case Builtin::BI__sync_fetch_and_xor_4:
2347   case Builtin::BI__sync_fetch_and_xor_8:
2348   case Builtin::BI__sync_fetch_and_xor_16:
2349     BuiltinIndex = 4;
2350     break;
2351 
2352   case Builtin::BI__sync_fetch_and_nand:
2353   case Builtin::BI__sync_fetch_and_nand_1:
2354   case Builtin::BI__sync_fetch_and_nand_2:
2355   case Builtin::BI__sync_fetch_and_nand_4:
2356   case Builtin::BI__sync_fetch_and_nand_8:
2357   case Builtin::BI__sync_fetch_and_nand_16:
2358     BuiltinIndex = 5;
2359     WarnAboutSemanticsChange = true;
2360     break;
2361 
2362   case Builtin::BI__sync_add_and_fetch:
2363   case Builtin::BI__sync_add_and_fetch_1:
2364   case Builtin::BI__sync_add_and_fetch_2:
2365   case Builtin::BI__sync_add_and_fetch_4:
2366   case Builtin::BI__sync_add_and_fetch_8:
2367   case Builtin::BI__sync_add_and_fetch_16:
2368     BuiltinIndex = 6;
2369     break;
2370 
2371   case Builtin::BI__sync_sub_and_fetch:
2372   case Builtin::BI__sync_sub_and_fetch_1:
2373   case Builtin::BI__sync_sub_and_fetch_2:
2374   case Builtin::BI__sync_sub_and_fetch_4:
2375   case Builtin::BI__sync_sub_and_fetch_8:
2376   case Builtin::BI__sync_sub_and_fetch_16:
2377     BuiltinIndex = 7;
2378     break;
2379 
2380   case Builtin::BI__sync_and_and_fetch:
2381   case Builtin::BI__sync_and_and_fetch_1:
2382   case Builtin::BI__sync_and_and_fetch_2:
2383   case Builtin::BI__sync_and_and_fetch_4:
2384   case Builtin::BI__sync_and_and_fetch_8:
2385   case Builtin::BI__sync_and_and_fetch_16:
2386     BuiltinIndex = 8;
2387     break;
2388 
2389   case Builtin::BI__sync_or_and_fetch:
2390   case Builtin::BI__sync_or_and_fetch_1:
2391   case Builtin::BI__sync_or_and_fetch_2:
2392   case Builtin::BI__sync_or_and_fetch_4:
2393   case Builtin::BI__sync_or_and_fetch_8:
2394   case Builtin::BI__sync_or_and_fetch_16:
2395     BuiltinIndex = 9;
2396     break;
2397 
2398   case Builtin::BI__sync_xor_and_fetch:
2399   case Builtin::BI__sync_xor_and_fetch_1:
2400   case Builtin::BI__sync_xor_and_fetch_2:
2401   case Builtin::BI__sync_xor_and_fetch_4:
2402   case Builtin::BI__sync_xor_and_fetch_8:
2403   case Builtin::BI__sync_xor_and_fetch_16:
2404     BuiltinIndex = 10;
2405     break;
2406 
2407   case Builtin::BI__sync_nand_and_fetch:
2408   case Builtin::BI__sync_nand_and_fetch_1:
2409   case Builtin::BI__sync_nand_and_fetch_2:
2410   case Builtin::BI__sync_nand_and_fetch_4:
2411   case Builtin::BI__sync_nand_and_fetch_8:
2412   case Builtin::BI__sync_nand_and_fetch_16:
2413     BuiltinIndex = 11;
2414     WarnAboutSemanticsChange = true;
2415     break;
2416 
2417   case Builtin::BI__sync_val_compare_and_swap:
2418   case Builtin::BI__sync_val_compare_and_swap_1:
2419   case Builtin::BI__sync_val_compare_and_swap_2:
2420   case Builtin::BI__sync_val_compare_and_swap_4:
2421   case Builtin::BI__sync_val_compare_and_swap_8:
2422   case Builtin::BI__sync_val_compare_and_swap_16:
2423     BuiltinIndex = 12;
2424     NumFixed = 2;
2425     break;
2426 
2427   case Builtin::BI__sync_bool_compare_and_swap:
2428   case Builtin::BI__sync_bool_compare_and_swap_1:
2429   case Builtin::BI__sync_bool_compare_and_swap_2:
2430   case Builtin::BI__sync_bool_compare_and_swap_4:
2431   case Builtin::BI__sync_bool_compare_and_swap_8:
2432   case Builtin::BI__sync_bool_compare_and_swap_16:
2433     BuiltinIndex = 13;
2434     NumFixed = 2;
2435     ResultType = Context.BoolTy;
2436     break;
2437 
2438   case Builtin::BI__sync_lock_test_and_set:
2439   case Builtin::BI__sync_lock_test_and_set_1:
2440   case Builtin::BI__sync_lock_test_and_set_2:
2441   case Builtin::BI__sync_lock_test_and_set_4:
2442   case Builtin::BI__sync_lock_test_and_set_8:
2443   case Builtin::BI__sync_lock_test_and_set_16:
2444     BuiltinIndex = 14;
2445     break;
2446 
2447   case Builtin::BI__sync_lock_release:
2448   case Builtin::BI__sync_lock_release_1:
2449   case Builtin::BI__sync_lock_release_2:
2450   case Builtin::BI__sync_lock_release_4:
2451   case Builtin::BI__sync_lock_release_8:
2452   case Builtin::BI__sync_lock_release_16:
2453     BuiltinIndex = 15;
2454     NumFixed = 0;
2455     ResultType = Context.VoidTy;
2456     break;
2457 
2458   case Builtin::BI__sync_swap:
2459   case Builtin::BI__sync_swap_1:
2460   case Builtin::BI__sync_swap_2:
2461   case Builtin::BI__sync_swap_4:
2462   case Builtin::BI__sync_swap_8:
2463   case Builtin::BI__sync_swap_16:
2464     BuiltinIndex = 16;
2465     break;
2466   }
2467 
2468   // Now that we know how many fixed arguments we expect, first check that we
2469   // have at least that many.
2470   if (TheCall->getNumArgs() < 1+NumFixed) {
2471     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2472       << 0 << 1+NumFixed << TheCall->getNumArgs()
2473       << TheCall->getCallee()->getSourceRange();
2474     return ExprError();
2475   }
2476 
2477   if (WarnAboutSemanticsChange) {
2478     Diag(TheCall->getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2479       << TheCall->getCallee()->getSourceRange();
2480   }
2481 
2482   // Get the decl for the concrete builtin from this, we can tell what the
2483   // concrete integer type we should convert to is.
2484   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2485   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
2486   FunctionDecl *NewBuiltinDecl;
2487   if (NewBuiltinID == BuiltinID)
2488     NewBuiltinDecl = FDecl;
2489   else {
2490     // Perform builtin lookup to avoid redeclaring it.
2491     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
2492     LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
2493     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
2494     assert(Res.getFoundDecl());
2495     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
2496     if (!NewBuiltinDecl)
2497       return ExprError();
2498   }
2499 
2500   // The first argument --- the pointer --- has a fixed type; we
2501   // deduce the types of the rest of the arguments accordingly.  Walk
2502   // the remaining arguments, converting them to the deduced value type.
2503   for (unsigned i = 0; i != NumFixed; ++i) {
2504     ExprResult Arg = TheCall->getArg(i+1);
2505 
2506     // GCC does an implicit conversion to the pointer or integer ValType.  This
2507     // can fail in some cases (1i -> int**), check for this error case now.
2508     // Initialize the argument.
2509     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
2510                                                    ValType, /*consume*/ false);
2511     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
2512     if (Arg.isInvalid())
2513       return ExprError();
2514 
2515     // Okay, we have something that *can* be converted to the right type.  Check
2516     // to see if there is a potentially weird extension going on here.  This can
2517     // happen when you do an atomic operation on something like an char* and
2518     // pass in 42.  The 42 gets converted to char.  This is even more strange
2519     // for things like 45.123 -> char, etc.
2520     // FIXME: Do this check.
2521     TheCall->setArg(i+1, Arg.get());
2522   }
2523 
2524   ASTContext& Context = this->getASTContext();
2525 
2526   // Create a new DeclRefExpr to refer to the new decl.
2527   DeclRefExpr* NewDRE = DeclRefExpr::Create(
2528       Context,
2529       DRE->getQualifierLoc(),
2530       SourceLocation(),
2531       NewBuiltinDecl,
2532       /*enclosing*/ false,
2533       DRE->getLocation(),
2534       Context.BuiltinFnTy,
2535       DRE->getValueKind());
2536 
2537   // Set the callee in the CallExpr.
2538   // FIXME: This loses syntactic information.
2539   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
2540   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2541                                               CK_BuiltinFnToFnPtr);
2542   TheCall->setCallee(PromotedCall.get());
2543 
2544   // Change the result type of the call to match the original value type. This
2545   // is arbitrary, but the codegen for these builtins ins design to handle it
2546   // gracefully.
2547   TheCall->setType(ResultType);
2548 
2549   return TheCallResult;
2550 }
2551 
2552 /// SemaBuiltinNontemporalOverloaded - We have a call to
2553 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
2554 /// overloaded function based on the pointer type of its last argument.
2555 ///
2556 /// This function goes through and does final semantic checking for these
2557 /// builtins.
2558 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
2559   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
2560   DeclRefExpr *DRE =
2561       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2562   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
2563   unsigned BuiltinID = FDecl->getBuiltinID();
2564   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2565           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2566          "Unexpected nontemporal load/store builtin!");
2567   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2568   unsigned numArgs = isStore ? 2 : 1;
2569 
2570   // Ensure that we have the proper number of arguments.
2571   if (checkArgCount(*this, TheCall, numArgs))
2572     return ExprError();
2573 
2574   // Inspect the last argument of the nontemporal builtin.  This should always
2575   // be a pointer type, from which we imply the type of the memory access.
2576   // Because it is a pointer type, we don't have to worry about any implicit
2577   // casts here.
2578   Expr *PointerArg = TheCall->getArg(numArgs - 1);
2579   ExprResult PointerArgResult =
2580       DefaultFunctionArrayLvalueConversion(PointerArg);
2581 
2582   if (PointerArgResult.isInvalid())
2583     return ExprError();
2584   PointerArg = PointerArgResult.get();
2585   TheCall->setArg(numArgs - 1, PointerArg);
2586 
2587   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2588   if (!pointerType) {
2589     Diag(DRE->getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2590         << PointerArg->getType() << PointerArg->getSourceRange();
2591     return ExprError();
2592   }
2593 
2594   QualType ValType = pointerType->getPointeeType();
2595 
2596   // Strip any qualifiers off ValType.
2597   ValType = ValType.getUnqualifiedType();
2598   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2599       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
2600       !ValType->isVectorType()) {
2601     Diag(DRE->getLocStart(),
2602          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2603         << PointerArg->getType() << PointerArg->getSourceRange();
2604     return ExprError();
2605   }
2606 
2607   if (!isStore) {
2608     TheCall->setType(ValType);
2609     return TheCallResult;
2610   }
2611 
2612   ExprResult ValArg = TheCall->getArg(0);
2613   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2614       Context, ValType, /*consume*/ false);
2615   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2616   if (ValArg.isInvalid())
2617     return ExprError();
2618 
2619   TheCall->setArg(0, ValArg.get());
2620   TheCall->setType(Context.VoidTy);
2621   return TheCallResult;
2622 }
2623 
2624 /// CheckObjCString - Checks that the argument to the builtin
2625 /// CFString constructor is correct
2626 /// Note: It might also make sense to do the UTF-16 conversion here (would
2627 /// simplify the backend).
2628 bool Sema::CheckObjCString(Expr *Arg) {
2629   Arg = Arg->IgnoreParenCasts();
2630   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
2631 
2632   if (!Literal || !Literal->isAscii()) {
2633     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2634       << Arg->getSourceRange();
2635     return true;
2636   }
2637 
2638   if (Literal->containsNonAsciiOrNull()) {
2639     StringRef String = Literal->getString();
2640     unsigned NumBytes = String.size();
2641     SmallVector<UTF16, 128> ToBuf(NumBytes);
2642     const UTF8 *FromPtr = (const UTF8 *)String.data();
2643     UTF16 *ToPtr = &ToBuf[0];
2644 
2645     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2646                                                  &ToPtr, ToPtr + NumBytes,
2647                                                  strictConversion);
2648     // Check for conversion failure.
2649     if (Result != conversionOK)
2650       Diag(Arg->getLocStart(),
2651            diag::warn_cfstring_truncated) << Arg->getSourceRange();
2652   }
2653   return false;
2654 }
2655 
2656 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
2657 /// for validity.  Emit an error and return true on failure; return false
2658 /// on success.
2659 bool Sema::SemaBuiltinVAStartImpl(CallExpr *TheCall) {
2660   Expr *Fn = TheCall->getCallee();
2661   if (TheCall->getNumArgs() > 2) {
2662     Diag(TheCall->getArg(2)->getLocStart(),
2663          diag::err_typecheck_call_too_many_args)
2664       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2665       << Fn->getSourceRange()
2666       << SourceRange(TheCall->getArg(2)->getLocStart(),
2667                      (*(TheCall->arg_end()-1))->getLocEnd());
2668     return true;
2669   }
2670 
2671   if (TheCall->getNumArgs() < 2) {
2672     return Diag(TheCall->getLocEnd(),
2673       diag::err_typecheck_call_too_few_args_at_least)
2674       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
2675   }
2676 
2677   // Type-check the first argument normally.
2678   if (checkBuiltinArgument(*this, TheCall, 0))
2679     return true;
2680 
2681   // Determine whether the current function is variadic or not.
2682   BlockScopeInfo *CurBlock = getCurBlock();
2683   bool isVariadic;
2684   if (CurBlock)
2685     isVariadic = CurBlock->TheDecl->isVariadic();
2686   else if (FunctionDecl *FD = getCurFunctionDecl())
2687     isVariadic = FD->isVariadic();
2688   else
2689     isVariadic = getCurMethodDecl()->isVariadic();
2690 
2691   if (!isVariadic) {
2692     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2693     return true;
2694   }
2695 
2696   // Verify that the second argument to the builtin is the last argument of the
2697   // current function or method.
2698   bool SecondArgIsLastNamedArgument = false;
2699   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
2700 
2701   // These are valid if SecondArgIsLastNamedArgument is false after the next
2702   // block.
2703   QualType Type;
2704   SourceLocation ParamLoc;
2705   bool IsCRegister = false;
2706 
2707   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2708     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2709       // FIXME: This isn't correct for methods (results in bogus warning).
2710       // Get the last formal in the current function.
2711       const ParmVarDecl *LastArg;
2712       if (CurBlock)
2713         LastArg = *(CurBlock->TheDecl->param_end()-1);
2714       else if (FunctionDecl *FD = getCurFunctionDecl())
2715         LastArg = *(FD->param_end()-1);
2716       else
2717         LastArg = *(getCurMethodDecl()->param_end()-1);
2718       SecondArgIsLastNamedArgument = PV == LastArg;
2719 
2720       Type = PV->getType();
2721       ParamLoc = PV->getLocation();
2722       IsCRegister =
2723           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
2724     }
2725   }
2726 
2727   if (!SecondArgIsLastNamedArgument)
2728     Diag(TheCall->getArg(1)->getLocStart(),
2729          diag::warn_second_arg_of_va_start_not_last_named_param);
2730   else if (IsCRegister || Type->isReferenceType() ||
2731            Type->isPromotableIntegerType() ||
2732            Type->isSpecificBuiltinType(BuiltinType::Float)) {
2733     unsigned Reason = 0;
2734     if (Type->isReferenceType())  Reason = 1;
2735     else if (IsCRegister)         Reason = 2;
2736     Diag(Arg->getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
2737     Diag(ParamLoc, diag::note_parameter_type) << Type;
2738   }
2739 
2740   TheCall->setType(Context.VoidTy);
2741   return false;
2742 }
2743 
2744 /// Check the arguments to '__builtin_va_start' for validity, and that
2745 /// it was called from a function of the native ABI.
2746 /// Emit an error and return true on failure; return false on success.
2747 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
2748   // On x86-64 Unix, don't allow this in Win64 ABI functions.
2749   // On x64 Windows, don't allow this in System V ABI functions.
2750   // (Yes, that means there's no corresponding way to support variadic
2751   // System V ABI functions on Windows.)
2752   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64) {
2753     unsigned OS = Context.getTargetInfo().getTriple().getOS();
2754     clang::CallingConv CC = CC_C;
2755     if (const FunctionDecl *FD = getCurFunctionDecl())
2756       CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2757     if ((OS == llvm::Triple::Win32 && CC == CC_X86_64SysV) ||
2758         (OS != llvm::Triple::Win32 && CC == CC_X86_64Win64))
2759       return Diag(TheCall->getCallee()->getLocStart(),
2760                   diag::err_va_start_used_in_wrong_abi_function)
2761              << (OS != llvm::Triple::Win32);
2762   }
2763   return SemaBuiltinVAStartImpl(TheCall);
2764 }
2765 
2766 /// Check the arguments to '__builtin_ms_va_start' for validity, and that
2767 /// it was called from a Win64 ABI function.
2768 /// Emit an error and return true on failure; return false on success.
2769 bool Sema::SemaBuiltinMSVAStart(CallExpr *TheCall) {
2770   // This only makes sense for x86-64.
2771   const llvm::Triple &TT = Context.getTargetInfo().getTriple();
2772   Expr *Callee = TheCall->getCallee();
2773   if (TT.getArch() != llvm::Triple::x86_64)
2774     return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2775   // Don't allow this in System V ABI functions.
2776   clang::CallingConv CC = CC_C;
2777   if (const FunctionDecl *FD = getCurFunctionDecl())
2778     CC = FD->getType()->getAs<FunctionType>()->getCallConv();
2779   if (CC == CC_X86_64SysV ||
2780       (TT.getOS() != llvm::Triple::Win32 && CC != CC_X86_64Win64))
2781     return Diag(Callee->getLocStart(),
2782                 diag::err_ms_va_start_used_in_sysv_function);
2783   return SemaBuiltinVAStartImpl(TheCall);
2784 }
2785 
2786 bool Sema::SemaBuiltinVAStartARM(CallExpr *Call) {
2787   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
2788   //                 const char *named_addr);
2789 
2790   Expr *Func = Call->getCallee();
2791 
2792   if (Call->getNumArgs() < 3)
2793     return Diag(Call->getLocEnd(),
2794                 diag::err_typecheck_call_too_few_args_at_least)
2795            << 0 /*function call*/ << 3 << Call->getNumArgs();
2796 
2797   // Determine whether the current function is variadic or not.
2798   bool IsVariadic;
2799   if (BlockScopeInfo *CurBlock = getCurBlock())
2800     IsVariadic = CurBlock->TheDecl->isVariadic();
2801   else if (FunctionDecl *FD = getCurFunctionDecl())
2802     IsVariadic = FD->isVariadic();
2803   else if (ObjCMethodDecl *MD = getCurMethodDecl())
2804     IsVariadic = MD->isVariadic();
2805   else
2806     llvm_unreachable("unexpected statement type");
2807 
2808   if (!IsVariadic) {
2809     Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2810     return true;
2811   }
2812 
2813   // Type-check the first argument normally.
2814   if (checkBuiltinArgument(*this, Call, 0))
2815     return true;
2816 
2817   const struct {
2818     unsigned ArgNo;
2819     QualType Type;
2820   } ArgumentTypes[] = {
2821     { 1, Context.getPointerType(Context.CharTy.withConst()) },
2822     { 2, Context.getSizeType() },
2823   };
2824 
2825   for (const auto &AT : ArgumentTypes) {
2826     const Expr *Arg = Call->getArg(AT.ArgNo)->IgnoreParens();
2827     if (Arg->getType().getCanonicalType() == AT.Type.getCanonicalType())
2828       continue;
2829     Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2830       << Arg->getType() << AT.Type << 1 /* different class */
2831       << 0 /* qualifier difference */ << 3 /* parameter mismatch */
2832       << AT.ArgNo + 1 << Arg->getType() << AT.Type;
2833   }
2834 
2835   return false;
2836 }
2837 
2838 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
2839 /// friends.  This is declared to take (...), so we have to check everything.
2840 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
2841   if (TheCall->getNumArgs() < 2)
2842     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2843       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
2844   if (TheCall->getNumArgs() > 2)
2845     return Diag(TheCall->getArg(2)->getLocStart(),
2846                 diag::err_typecheck_call_too_many_args)
2847       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2848       << SourceRange(TheCall->getArg(2)->getLocStart(),
2849                      (*(TheCall->arg_end()-1))->getLocEnd());
2850 
2851   ExprResult OrigArg0 = TheCall->getArg(0);
2852   ExprResult OrigArg1 = TheCall->getArg(1);
2853 
2854   // Do standard promotions between the two arguments, returning their common
2855   // type.
2856   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
2857   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
2858     return true;
2859 
2860   // Make sure any conversions are pushed back into the call; this is
2861   // type safe since unordered compare builtins are declared as "_Bool
2862   // foo(...)".
2863   TheCall->setArg(0, OrigArg0.get());
2864   TheCall->setArg(1, OrigArg1.get());
2865 
2866   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
2867     return false;
2868 
2869   // If the common type isn't a real floating type, then the arguments were
2870   // invalid for this operation.
2871   if (Res.isNull() || !Res->isRealFloatingType())
2872     return Diag(OrigArg0.get()->getLocStart(),
2873                 diag::err_typecheck_call_invalid_ordered_compare)
2874       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
2875       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
2876 
2877   return false;
2878 }
2879 
2880 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
2881 /// __builtin_isnan and friends.  This is declared to take (...), so we have
2882 /// to check everything. We expect the last argument to be a floating point
2883 /// value.
2884 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
2885   if (TheCall->getNumArgs() < NumArgs)
2886     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
2887       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
2888   if (TheCall->getNumArgs() > NumArgs)
2889     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
2890                 diag::err_typecheck_call_too_many_args)
2891       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
2892       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
2893                      (*(TheCall->arg_end()-1))->getLocEnd());
2894 
2895   Expr *OrigArg = TheCall->getArg(NumArgs-1);
2896 
2897   if (OrigArg->isTypeDependent())
2898     return false;
2899 
2900   // This operation requires a non-_Complex floating-point number.
2901   if (!OrigArg->getType()->isRealFloatingType())
2902     return Diag(OrigArg->getLocStart(),
2903                 diag::err_typecheck_call_invalid_unary_fp)
2904       << OrigArg->getType() << OrigArg->getSourceRange();
2905 
2906   // If this is an implicit conversion from float -> double, remove it.
2907   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
2908     Expr *CastArg = Cast->getSubExpr();
2909     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
2910       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2911              "promotion from float to double is the only expected cast here");
2912       Cast->setSubExpr(nullptr);
2913       TheCall->setArg(NumArgs-1, CastArg);
2914     }
2915   }
2916 
2917   return false;
2918 }
2919 
2920 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
2921 // This is declared to take (...), so we have to check everything.
2922 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
2923   if (TheCall->getNumArgs() < 2)
2924     return ExprError(Diag(TheCall->getLocEnd(),
2925                           diag::err_typecheck_call_too_few_args_at_least)
2926                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
2927                      << TheCall->getSourceRange());
2928 
2929   // Determine which of the following types of shufflevector we're checking:
2930   // 1) unary, vector mask: (lhs, mask)
2931   // 2) binary, vector mask: (lhs, rhs, mask)
2932   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
2933   QualType resType = TheCall->getArg(0)->getType();
2934   unsigned numElements = 0;
2935 
2936   if (!TheCall->getArg(0)->isTypeDependent() &&
2937       !TheCall->getArg(1)->isTypeDependent()) {
2938     QualType LHSType = TheCall->getArg(0)->getType();
2939     QualType RHSType = TheCall->getArg(1)->getType();
2940 
2941     if (!LHSType->isVectorType() || !RHSType->isVectorType())
2942       return ExprError(Diag(TheCall->getLocStart(),
2943                             diag::err_shufflevector_non_vector)
2944                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2945                                       TheCall->getArg(1)->getLocEnd()));
2946 
2947     numElements = LHSType->getAs<VectorType>()->getNumElements();
2948     unsigned numResElements = TheCall->getNumArgs() - 2;
2949 
2950     // Check to see if we have a call with 2 vector arguments, the unary shuffle
2951     // with mask.  If so, verify that RHS is an integer vector type with the
2952     // same number of elts as lhs.
2953     if (TheCall->getNumArgs() == 2) {
2954       if (!RHSType->hasIntegerRepresentation() ||
2955           RHSType->getAs<VectorType>()->getNumElements() != numElements)
2956         return ExprError(Diag(TheCall->getLocStart(),
2957                               diag::err_shufflevector_incompatible_vector)
2958                          << SourceRange(TheCall->getArg(1)->getLocStart(),
2959                                         TheCall->getArg(1)->getLocEnd()));
2960     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
2961       return ExprError(Diag(TheCall->getLocStart(),
2962                             diag::err_shufflevector_incompatible_vector)
2963                        << SourceRange(TheCall->getArg(0)->getLocStart(),
2964                                       TheCall->getArg(1)->getLocEnd()));
2965     } else if (numElements != numResElements) {
2966       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
2967       resType = Context.getVectorType(eltType, numResElements,
2968                                       VectorType::GenericVector);
2969     }
2970   }
2971 
2972   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
2973     if (TheCall->getArg(i)->isTypeDependent() ||
2974         TheCall->getArg(i)->isValueDependent())
2975       continue;
2976 
2977     llvm::APSInt Result(32);
2978     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
2979       return ExprError(Diag(TheCall->getLocStart(),
2980                             diag::err_shufflevector_nonconstant_argument)
2981                        << TheCall->getArg(i)->getSourceRange());
2982 
2983     // Allow -1 which will be translated to undef in the IR.
2984     if (Result.isSigned() && Result.isAllOnesValue())
2985       continue;
2986 
2987     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2988       return ExprError(Diag(TheCall->getLocStart(),
2989                             diag::err_shufflevector_argument_too_large)
2990                        << TheCall->getArg(i)->getSourceRange());
2991   }
2992 
2993   SmallVector<Expr*, 32> exprs;
2994 
2995   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
2996     exprs.push_back(TheCall->getArg(i));
2997     TheCall->setArg(i, nullptr);
2998   }
2999 
3000   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
3001                                          TheCall->getCallee()->getLocStart(),
3002                                          TheCall->getRParenLoc());
3003 }
3004 
3005 /// SemaConvertVectorExpr - Handle __builtin_convertvector
3006 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
3007                                        SourceLocation BuiltinLoc,
3008                                        SourceLocation RParenLoc) {
3009   ExprValueKind VK = VK_RValue;
3010   ExprObjectKind OK = OK_Ordinary;
3011   QualType DstTy = TInfo->getType();
3012   QualType SrcTy = E->getType();
3013 
3014   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
3015     return ExprError(Diag(BuiltinLoc,
3016                           diag::err_convertvector_non_vector)
3017                      << E->getSourceRange());
3018   if (!DstTy->isVectorType() && !DstTy->isDependentType())
3019     return ExprError(Diag(BuiltinLoc,
3020                           diag::err_convertvector_non_vector_type));
3021 
3022   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
3023     unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
3024     unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
3025     if (SrcElts != DstElts)
3026       return ExprError(Diag(BuiltinLoc,
3027                             diag::err_convertvector_incompatible_vector)
3028                        << E->getSourceRange());
3029   }
3030 
3031   return new (Context)
3032       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
3033 }
3034 
3035 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
3036 // This is declared to take (const void*, ...) and can take two
3037 // optional constant int args.
3038 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
3039   unsigned NumArgs = TheCall->getNumArgs();
3040 
3041   if (NumArgs > 3)
3042     return Diag(TheCall->getLocEnd(),
3043              diag::err_typecheck_call_too_many_args_at_most)
3044              << 0 /*function call*/ << 3 << NumArgs
3045              << TheCall->getSourceRange();
3046 
3047   // Argument 0 is checked for us and the remaining arguments must be
3048   // constant integers.
3049   for (unsigned i = 1; i != NumArgs; ++i)
3050     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
3051       return true;
3052 
3053   return false;
3054 }
3055 
3056 /// SemaBuiltinAssume - Handle __assume (MS Extension).
3057 // __assume does not evaluate its arguments, and should warn if its argument
3058 // has side effects.
3059 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
3060   Expr *Arg = TheCall->getArg(0);
3061   if (Arg->isInstantiationDependent()) return false;
3062 
3063   if (Arg->HasSideEffects(Context))
3064     Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
3065       << Arg->getSourceRange()
3066       << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
3067 
3068   return false;
3069 }
3070 
3071 /// Handle __builtin_assume_aligned. This is declared
3072 /// as (const void*, size_t, ...) and can take one optional constant int arg.
3073 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
3074   unsigned NumArgs = TheCall->getNumArgs();
3075 
3076   if (NumArgs > 3)
3077     return Diag(TheCall->getLocEnd(),
3078              diag::err_typecheck_call_too_many_args_at_most)
3079              << 0 /*function call*/ << 3 << NumArgs
3080              << TheCall->getSourceRange();
3081 
3082   // The alignment must be a constant integer.
3083   Expr *Arg = TheCall->getArg(1);
3084 
3085   // We can't check the value of a dependent argument.
3086   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
3087     llvm::APSInt Result;
3088     if (SemaBuiltinConstantArg(TheCall, 1, Result))
3089       return true;
3090 
3091     if (!Result.isPowerOf2())
3092       return Diag(TheCall->getLocStart(),
3093                   diag::err_alignment_not_power_of_two)
3094            << Arg->getSourceRange();
3095   }
3096 
3097   if (NumArgs > 2) {
3098     ExprResult Arg(TheCall->getArg(2));
3099     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
3100       Context.getSizeType(), false);
3101     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
3102     if (Arg.isInvalid()) return true;
3103     TheCall->setArg(2, Arg.get());
3104   }
3105 
3106   return false;
3107 }
3108 
3109 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
3110 /// TheCall is a constant expression.
3111 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
3112                                   llvm::APSInt &Result) {
3113   Expr *Arg = TheCall->getArg(ArgNum);
3114   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
3115   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
3116 
3117   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
3118 
3119   if (!Arg->isIntegerConstantExpr(Result, Context))
3120     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
3121                 << FDecl->getDeclName() <<  Arg->getSourceRange();
3122 
3123   return false;
3124 }
3125 
3126 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
3127 /// TheCall is a constant expression in the range [Low, High].
3128 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
3129                                        int Low, int High) {
3130   llvm::APSInt Result;
3131 
3132   // We can't check the value of a dependent argument.
3133   Expr *Arg = TheCall->getArg(ArgNum);
3134   if (Arg->isTypeDependent() || Arg->isValueDependent())
3135     return false;
3136 
3137   // Check constant-ness first.
3138   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3139     return true;
3140 
3141   if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
3142     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
3143       << Low << High << Arg->getSourceRange();
3144 
3145   return false;
3146 }
3147 
3148 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
3149 /// TheCall is an ARM/AArch64 special register string literal.
3150 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
3151                                     int ArgNum, unsigned ExpectedFieldNum,
3152                                     bool AllowName) {
3153   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
3154                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
3155                       BuiltinID == ARM::BI__builtin_arm_rsr ||
3156                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
3157                       BuiltinID == ARM::BI__builtin_arm_wsr ||
3158                       BuiltinID == ARM::BI__builtin_arm_wsrp;
3159   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
3160                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
3161                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
3162                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
3163                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
3164                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
3165   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
3166 
3167   // We can't check the value of a dependent argument.
3168   Expr *Arg = TheCall->getArg(ArgNum);
3169   if (Arg->isTypeDependent() || Arg->isValueDependent())
3170     return false;
3171 
3172   // Check if the argument is a string literal.
3173   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3174     return Diag(TheCall->getLocStart(), diag::err_expr_not_string_literal)
3175            << Arg->getSourceRange();
3176 
3177   // Check the type of special register given.
3178   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3179   SmallVector<StringRef, 6> Fields;
3180   Reg.split(Fields, ":");
3181 
3182   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
3183     return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3184            << Arg->getSourceRange();
3185 
3186   // If the string is the name of a register then we cannot check that it is
3187   // valid here but if the string is of one the forms described in ACLE then we
3188   // can check that the supplied fields are integers and within the valid
3189   // ranges.
3190   if (Fields.size() > 1) {
3191     bool FiveFields = Fields.size() == 5;
3192 
3193     bool ValidString = true;
3194     if (IsARMBuiltin) {
3195       ValidString &= Fields[0].startswith_lower("cp") ||
3196                      Fields[0].startswith_lower("p");
3197       if (ValidString)
3198         Fields[0] =
3199           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
3200 
3201       ValidString &= Fields[2].startswith_lower("c");
3202       if (ValidString)
3203         Fields[2] = Fields[2].drop_front(1);
3204 
3205       if (FiveFields) {
3206         ValidString &= Fields[3].startswith_lower("c");
3207         if (ValidString)
3208           Fields[3] = Fields[3].drop_front(1);
3209       }
3210     }
3211 
3212     SmallVector<int, 5> Ranges;
3213     if (FiveFields)
3214       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
3215     else
3216       Ranges.append({15, 7, 15});
3217 
3218     for (unsigned i=0; i<Fields.size(); ++i) {
3219       int IntField;
3220       ValidString &= !Fields[i].getAsInteger(10, IntField);
3221       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
3222     }
3223 
3224     if (!ValidString)
3225       return Diag(TheCall->getLocStart(), diag::err_arm_invalid_specialreg)
3226              << Arg->getSourceRange();
3227 
3228   } else if (IsAArch64Builtin && Fields.size() == 1) {
3229     // If the register name is one of those that appear in the condition below
3230     // and the special register builtin being used is one of the write builtins,
3231     // then we require that the argument provided for writing to the register
3232     // is an integer constant expression. This is because it will be lowered to
3233     // an MSR (immediate) instruction, so we need to know the immediate at
3234     // compile time.
3235     if (TheCall->getNumArgs() != 2)
3236       return false;
3237 
3238     std::string RegLower = Reg.lower();
3239     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
3240         RegLower != "pan" && RegLower != "uao")
3241       return false;
3242 
3243     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3244   }
3245 
3246   return false;
3247 }
3248 
3249 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
3250 /// This checks that the target supports __builtin_longjmp and
3251 /// that val is a constant 1.
3252 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
3253   if (!Context.getTargetInfo().hasSjLjLowering())
3254     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_unsupported)
3255              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3256 
3257   Expr *Arg = TheCall->getArg(1);
3258   llvm::APSInt Result;
3259 
3260   // TODO: This is less than ideal. Overload this to take a value.
3261   if (SemaBuiltinConstantArg(TheCall, 1, Result))
3262     return true;
3263 
3264   if (Result != 1)
3265     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
3266              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3267 
3268   return false;
3269 }
3270 
3271 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
3272 /// This checks that the target supports __builtin_setjmp.
3273 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
3274   if (!Context.getTargetInfo().hasSjLjLowering())
3275     return Diag(TheCall->getLocStart(), diag::err_builtin_setjmp_unsupported)
3276              << SourceRange(TheCall->getLocStart(), TheCall->getLocEnd());
3277   return false;
3278 }
3279 
3280 namespace {
3281 class UncoveredArgHandler {
3282   enum { Unknown = -1, AllCovered = -2 };
3283   signed FirstUncoveredArg;
3284   SmallVector<const Expr *, 4> DiagnosticExprs;
3285 
3286 public:
3287   UncoveredArgHandler() : FirstUncoveredArg(Unknown) { }
3288 
3289   bool hasUncoveredArg() const {
3290     return (FirstUncoveredArg >= 0);
3291   }
3292 
3293   unsigned getUncoveredArg() const {
3294     assert(hasUncoveredArg() && "no uncovered argument");
3295     return FirstUncoveredArg;
3296   }
3297 
3298   void setAllCovered() {
3299     // A string has been found with all arguments covered, so clear out
3300     // the diagnostics.
3301     DiagnosticExprs.clear();
3302     FirstUncoveredArg = AllCovered;
3303   }
3304 
3305   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
3306     assert(NewFirstUncoveredArg >= 0 && "Outside range");
3307 
3308     // Don't update if a previous string covers all arguments.
3309     if (FirstUncoveredArg == AllCovered)
3310       return;
3311 
3312     // UncoveredArgHandler tracks the highest uncovered argument index
3313     // and with it all the strings that match this index.
3314     if (NewFirstUncoveredArg == FirstUncoveredArg)
3315       DiagnosticExprs.push_back(StrExpr);
3316     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
3317       DiagnosticExprs.clear();
3318       DiagnosticExprs.push_back(StrExpr);
3319       FirstUncoveredArg = NewFirstUncoveredArg;
3320     }
3321   }
3322 
3323   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
3324 };
3325 
3326 enum StringLiteralCheckType {
3327   SLCT_NotALiteral,
3328   SLCT_UncheckedLiteral,
3329   SLCT_CheckedLiteral
3330 };
3331 } // end anonymous namespace
3332 
3333 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
3334                               const Expr *OrigFormatExpr,
3335                               ArrayRef<const Expr *> Args,
3336                               bool HasVAListArg, unsigned format_idx,
3337                               unsigned firstDataArg,
3338                               Sema::FormatStringType Type,
3339                               bool inFunctionCall,
3340                               Sema::VariadicCallType CallType,
3341                               llvm::SmallBitVector &CheckedVarArgs,
3342                               UncoveredArgHandler &UncoveredArg);
3343 
3344 // Determine if an expression is a string literal or constant string.
3345 // If this function returns false on the arguments to a function expecting a
3346 // format string, we will usually need to emit a warning.
3347 // True string literals are then checked by CheckFormatString.
3348 static StringLiteralCheckType
3349 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
3350                       bool HasVAListArg, unsigned format_idx,
3351                       unsigned firstDataArg, Sema::FormatStringType Type,
3352                       Sema::VariadicCallType CallType, bool InFunctionCall,
3353                       llvm::SmallBitVector &CheckedVarArgs,
3354                       UncoveredArgHandler &UncoveredArg) {
3355  tryAgain:
3356   if (E->isTypeDependent() || E->isValueDependent())
3357     return SLCT_NotALiteral;
3358 
3359   E = E->IgnoreParenCasts();
3360 
3361   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
3362     // Technically -Wformat-nonliteral does not warn about this case.
3363     // The behavior of printf and friends in this case is implementation
3364     // dependent.  Ideally if the format string cannot be null then
3365     // it should have a 'nonnull' attribute in the function prototype.
3366     return SLCT_UncheckedLiteral;
3367 
3368   switch (E->getStmtClass()) {
3369   case Stmt::BinaryConditionalOperatorClass:
3370   case Stmt::ConditionalOperatorClass: {
3371     // The expression is a literal if both sub-expressions were, and it was
3372     // completely checked only if both sub-expressions were checked.
3373     const AbstractConditionalOperator *C =
3374         cast<AbstractConditionalOperator>(E);
3375 
3376     // Determine whether it is necessary to check both sub-expressions, for
3377     // example, because the condition expression is a constant that can be
3378     // evaluated at compile time.
3379     bool CheckLeft = true, CheckRight = true;
3380 
3381     bool Cond;
3382     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext())) {
3383       if (Cond)
3384         CheckRight = false;
3385       else
3386         CheckLeft = false;
3387     }
3388 
3389     StringLiteralCheckType Left;
3390     if (!CheckLeft)
3391       Left = SLCT_UncheckedLiteral;
3392     else {
3393       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
3394                                    HasVAListArg, format_idx, firstDataArg,
3395                                    Type, CallType, InFunctionCall,
3396                                    CheckedVarArgs, UncoveredArg);
3397       if (Left == SLCT_NotALiteral || !CheckRight)
3398         return Left;
3399     }
3400 
3401     StringLiteralCheckType Right =
3402         checkFormatStringExpr(S, C->getFalseExpr(), Args,
3403                               HasVAListArg, format_idx, firstDataArg,
3404                               Type, CallType, InFunctionCall, CheckedVarArgs,
3405                               UncoveredArg);
3406 
3407     return (CheckLeft && Left < Right) ? Left : Right;
3408   }
3409 
3410   case Stmt::ImplicitCastExprClass: {
3411     E = cast<ImplicitCastExpr>(E)->getSubExpr();
3412     goto tryAgain;
3413   }
3414 
3415   case Stmt::OpaqueValueExprClass:
3416     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3417       E = src;
3418       goto tryAgain;
3419     }
3420     return SLCT_NotALiteral;
3421 
3422   case Stmt::PredefinedExprClass:
3423     // While __func__, etc., are technically not string literals, they
3424     // cannot contain format specifiers and thus are not a security
3425     // liability.
3426     return SLCT_UncheckedLiteral;
3427 
3428   case Stmt::DeclRefExprClass: {
3429     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
3430 
3431     // As an exception, do not flag errors for variables binding to
3432     // const string literals.
3433     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
3434       bool isConstant = false;
3435       QualType T = DR->getType();
3436 
3437       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
3438         isConstant = AT->getElementType().isConstant(S.Context);
3439       } else if (const PointerType *PT = T->getAs<PointerType>()) {
3440         isConstant = T.isConstant(S.Context) &&
3441                      PT->getPointeeType().isConstant(S.Context);
3442       } else if (T->isObjCObjectPointerType()) {
3443         // In ObjC, there is usually no "const ObjectPointer" type,
3444         // so don't check if the pointee type is constant.
3445         isConstant = T.isConstant(S.Context);
3446       }
3447 
3448       if (isConstant) {
3449         if (const Expr *Init = VD->getAnyInitializer()) {
3450           // Look through initializers like const char c[] = { "foo" }
3451           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3452             if (InitList->isStringLiteralInit())
3453               Init = InitList->getInit(0)->IgnoreParenImpCasts();
3454           }
3455           return checkFormatStringExpr(S, Init, Args,
3456                                        HasVAListArg, format_idx,
3457                                        firstDataArg, Type, CallType,
3458                                        /*InFunctionCall*/false, CheckedVarArgs,
3459                                        UncoveredArg);
3460         }
3461       }
3462 
3463       // For vprintf* functions (i.e., HasVAListArg==true), we add a
3464       // special check to see if the format string is a function parameter
3465       // of the function calling the printf function.  If the function
3466       // has an attribute indicating it is a printf-like function, then we
3467       // should suppress warnings concerning non-literals being used in a call
3468       // to a vprintf function.  For example:
3469       //
3470       // void
3471       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
3472       //      va_list ap;
3473       //      va_start(ap, fmt);
3474       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
3475       //      ...
3476       // }
3477       if (HasVAListArg) {
3478         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3479           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3480             int PVIndex = PV->getFunctionScopeIndex() + 1;
3481             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3482               // adjust for implicit parameter
3483               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3484                 if (MD->isInstance())
3485                   ++PVIndex;
3486               // We also check if the formats are compatible.
3487               // We can't pass a 'scanf' string to a 'printf' function.
3488               if (PVIndex == PVFormat->getFormatIdx() &&
3489                   Type == S.GetFormatStringType(PVFormat))
3490                 return SLCT_UncheckedLiteral;
3491             }
3492           }
3493         }
3494       }
3495     }
3496 
3497     return SLCT_NotALiteral;
3498   }
3499 
3500   case Stmt::CallExprClass:
3501   case Stmt::CXXMemberCallExprClass: {
3502     const CallExpr *CE = cast<CallExpr>(E);
3503     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
3504       if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3505         unsigned ArgIndex = FA->getFormatIdx();
3506         if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
3507           if (MD->isInstance())
3508             --ArgIndex;
3509         const Expr *Arg = CE->getArg(ArgIndex - 1);
3510 
3511         return checkFormatStringExpr(S, Arg, Args,
3512                                      HasVAListArg, format_idx, firstDataArg,
3513                                      Type, CallType, InFunctionCall,
3514                                      CheckedVarArgs, UncoveredArg);
3515       } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3516         unsigned BuiltinID = FD->getBuiltinID();
3517         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3518             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3519           const Expr *Arg = CE->getArg(0);
3520           return checkFormatStringExpr(S, Arg, Args,
3521                                        HasVAListArg, format_idx,
3522                                        firstDataArg, Type, CallType,
3523                                        InFunctionCall, CheckedVarArgs,
3524                                        UncoveredArg);
3525         }
3526       }
3527     }
3528 
3529     return SLCT_NotALiteral;
3530   }
3531   case Stmt::ObjCStringLiteralClass:
3532   case Stmt::StringLiteralClass: {
3533     const StringLiteral *StrE = nullptr;
3534 
3535     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
3536       StrE = ObjCFExpr->getString();
3537     else
3538       StrE = cast<StringLiteral>(E);
3539 
3540     if (StrE) {
3541       CheckFormatString(S, StrE, E, Args, HasVAListArg, format_idx,
3542                         firstDataArg, Type, InFunctionCall, CallType,
3543                         CheckedVarArgs, UncoveredArg);
3544       return SLCT_CheckedLiteral;
3545     }
3546 
3547     return SLCT_NotALiteral;
3548   }
3549 
3550   default:
3551     return SLCT_NotALiteral;
3552   }
3553 }
3554 
3555 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
3556   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3557   .Case("scanf", FST_Scanf)
3558   .Cases("printf", "printf0", FST_Printf)
3559   .Cases("NSString", "CFString", FST_NSString)
3560   .Case("strftime", FST_Strftime)
3561   .Case("strfmon", FST_Strfmon)
3562   .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
3563   .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
3564   .Case("os_trace", FST_OSTrace)
3565   .Default(FST_Unknown);
3566 }
3567 
3568 /// CheckFormatArguments - Check calls to printf and scanf (and similar
3569 /// functions) for correct use of format strings.
3570 /// Returns true if a format string has been fully checked.
3571 bool Sema::CheckFormatArguments(const FormatAttr *Format,
3572                                 ArrayRef<const Expr *> Args,
3573                                 bool IsCXXMember,
3574                                 VariadicCallType CallType,
3575                                 SourceLocation Loc, SourceRange Range,
3576                                 llvm::SmallBitVector &CheckedVarArgs) {
3577   FormatStringInfo FSI;
3578   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3579     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3580                                 FSI.FirstDataArg, GetFormatStringType(Format),
3581                                 CallType, Loc, Range, CheckedVarArgs);
3582   return false;
3583 }
3584 
3585 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
3586                                 bool HasVAListArg, unsigned format_idx,
3587                                 unsigned firstDataArg, FormatStringType Type,
3588                                 VariadicCallType CallType,
3589                                 SourceLocation Loc, SourceRange Range,
3590                                 llvm::SmallBitVector &CheckedVarArgs) {
3591   // CHECK: printf/scanf-like function is called with no format string.
3592   if (format_idx >= Args.size()) {
3593     Diag(Loc, diag::warn_missing_format_string) << Range;
3594     return false;
3595   }
3596 
3597   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3598 
3599   // CHECK: format string is not a string literal.
3600   //
3601   // Dynamically generated format strings are difficult to
3602   // automatically vet at compile time.  Requiring that format strings
3603   // are string literals: (1) permits the checking of format strings by
3604   // the compiler and thereby (2) can practically remove the source of
3605   // many format string exploits.
3606 
3607   // Format string can be either ObjC string (e.g. @"%d") or
3608   // C string (e.g. "%d")
3609   // ObjC string uses the same format specifiers as C string, so we can use
3610   // the same format string checking logic for both ObjC and C strings.
3611   UncoveredArgHandler UncoveredArg;
3612   StringLiteralCheckType CT =
3613       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
3614                             format_idx, firstDataArg, Type, CallType,
3615                             /*IsFunctionCall*/true, CheckedVarArgs,
3616                             UncoveredArg);
3617 
3618   // Generate a diagnostic where an uncovered argument is detected.
3619   if (UncoveredArg.hasUncoveredArg()) {
3620     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
3621     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
3622     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
3623   }
3624 
3625   if (CT != SLCT_NotALiteral)
3626     // Literal format string found, check done!
3627     return CT == SLCT_CheckedLiteral;
3628 
3629   // Strftime is particular as it always uses a single 'time' argument,
3630   // so it is safe to pass a non-literal string.
3631   if (Type == FST_Strftime)
3632     return false;
3633 
3634   // Do not emit diag when the string param is a macro expansion and the
3635   // format is either NSString or CFString. This is a hack to prevent
3636   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
3637   // which are usually used in place of NS and CF string literals.
3638   SourceLocation FormatLoc = Args[format_idx]->getLocStart();
3639   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
3640     return false;
3641 
3642   // If there are no arguments specified, warn with -Wformat-security, otherwise
3643   // warn only with -Wformat-nonliteral.
3644   if (Args.size() == firstDataArg) {
3645     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
3646       << OrigFormatExpr->getSourceRange();
3647     switch (Type) {
3648     default:
3649       break;
3650     case FST_Kprintf:
3651     case FST_FreeBSDKPrintf:
3652     case FST_Printf:
3653       Diag(FormatLoc, diag::note_format_security_fixit)
3654         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
3655       break;
3656     case FST_NSString:
3657       Diag(FormatLoc, diag::note_format_security_fixit)
3658         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
3659       break;
3660     }
3661   } else {
3662     Diag(FormatLoc, diag::warn_format_nonliteral)
3663       << OrigFormatExpr->getSourceRange();
3664   }
3665   return false;
3666 }
3667 
3668 namespace {
3669 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
3670 protected:
3671   Sema &S;
3672   const StringLiteral *FExpr;
3673   const Expr *OrigFormatExpr;
3674   const unsigned FirstDataArg;
3675   const unsigned NumDataArgs;
3676   const char *Beg; // Start of format string.
3677   const bool HasVAListArg;
3678   ArrayRef<const Expr *> Args;
3679   unsigned FormatIdx;
3680   llvm::SmallBitVector CoveredArgs;
3681   bool usesPositionalArgs;
3682   bool atFirstArg;
3683   bool inFunctionCall;
3684   Sema::VariadicCallType CallType;
3685   llvm::SmallBitVector &CheckedVarArgs;
3686   UncoveredArgHandler &UncoveredArg;
3687 
3688 public:
3689   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
3690                      const Expr *origFormatExpr, unsigned firstDataArg,
3691                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
3692                      ArrayRef<const Expr *> Args,
3693                      unsigned formatIdx, bool inFunctionCall,
3694                      Sema::VariadicCallType callType,
3695                      llvm::SmallBitVector &CheckedVarArgs,
3696                      UncoveredArgHandler &UncoveredArg)
3697     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3698       FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3699       Beg(beg), HasVAListArg(hasVAListArg),
3700       Args(Args), FormatIdx(formatIdx),
3701       usesPositionalArgs(false), atFirstArg(true),
3702       inFunctionCall(inFunctionCall), CallType(callType),
3703       CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
3704     CoveredArgs.resize(numDataArgs);
3705     CoveredArgs.reset();
3706   }
3707 
3708   void DoneProcessing();
3709 
3710   void HandleIncompleteSpecifier(const char *startSpecifier,
3711                                  unsigned specifierLen) override;
3712 
3713   void HandleInvalidLengthModifier(
3714                            const analyze_format_string::FormatSpecifier &FS,
3715                            const analyze_format_string::ConversionSpecifier &CS,
3716                            const char *startSpecifier, unsigned specifierLen,
3717                            unsigned DiagID);
3718 
3719   void HandleNonStandardLengthModifier(
3720                     const analyze_format_string::FormatSpecifier &FS,
3721                     const char *startSpecifier, unsigned specifierLen);
3722 
3723   void HandleNonStandardConversionSpecifier(
3724                     const analyze_format_string::ConversionSpecifier &CS,
3725                     const char *startSpecifier, unsigned specifierLen);
3726 
3727   void HandlePosition(const char *startPos, unsigned posLen) override;
3728 
3729   void HandleInvalidPosition(const char *startSpecifier,
3730                              unsigned specifierLen,
3731                              analyze_format_string::PositionContext p) override;
3732 
3733   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
3734 
3735   void HandleNullChar(const char *nullCharacter) override;
3736 
3737   template <typename Range>
3738   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
3739                                    const Expr *ArgumentExpr,
3740                                    PartialDiagnostic PDiag,
3741                                    SourceLocation StringLoc,
3742                                    bool IsStringLocation, Range StringRange,
3743                                    ArrayRef<FixItHint> Fixit = None);
3744 
3745 protected:
3746   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
3747                                         const char *startSpec,
3748                                         unsigned specifierLen,
3749                                         const char *csStart, unsigned csLen);
3750 
3751   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
3752                                          const char *startSpec,
3753                                          unsigned specifierLen);
3754 
3755   SourceRange getFormatStringRange();
3756   CharSourceRange getSpecifierRange(const char *startSpecifier,
3757                                     unsigned specifierLen);
3758   SourceLocation getLocationOfByte(const char *x);
3759 
3760   const Expr *getDataArg(unsigned i) const;
3761 
3762   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
3763                     const analyze_format_string::ConversionSpecifier &CS,
3764                     const char *startSpecifier, unsigned specifierLen,
3765                     unsigned argIndex);
3766 
3767   template <typename Range>
3768   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
3769                             bool IsStringLocation, Range StringRange,
3770                             ArrayRef<FixItHint> Fixit = None);
3771 };
3772 } // end anonymous namespace
3773 
3774 SourceRange CheckFormatHandler::getFormatStringRange() {
3775   return OrigFormatExpr->getSourceRange();
3776 }
3777 
3778 CharSourceRange CheckFormatHandler::
3779 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
3780   SourceLocation Start = getLocationOfByte(startSpecifier);
3781   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
3782 
3783   // Advance the end SourceLocation by one due to half-open ranges.
3784   End = End.getLocWithOffset(1);
3785 
3786   return CharSourceRange::getCharRange(Start, End);
3787 }
3788 
3789 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
3790   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
3791 }
3792 
3793 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
3794                                                    unsigned specifierLen){
3795   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
3796                        getLocationOfByte(startSpecifier),
3797                        /*IsStringLocation*/true,
3798                        getSpecifierRange(startSpecifier, specifierLen));
3799 }
3800 
3801 void CheckFormatHandler::HandleInvalidLengthModifier(
3802     const analyze_format_string::FormatSpecifier &FS,
3803     const analyze_format_string::ConversionSpecifier &CS,
3804     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
3805   using namespace analyze_format_string;
3806 
3807   const LengthModifier &LM = FS.getLengthModifier();
3808   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3809 
3810   // See if we know how to fix this length modifier.
3811   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3812   if (FixedLM) {
3813     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3814                          getLocationOfByte(LM.getStart()),
3815                          /*IsStringLocation*/true,
3816                          getSpecifierRange(startSpecifier, specifierLen));
3817 
3818     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3819       << FixedLM->toString()
3820       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3821 
3822   } else {
3823     FixItHint Hint;
3824     if (DiagID == diag::warn_format_nonsensical_length)
3825       Hint = FixItHint::CreateRemoval(LMRange);
3826 
3827     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
3828                          getLocationOfByte(LM.getStart()),
3829                          /*IsStringLocation*/true,
3830                          getSpecifierRange(startSpecifier, specifierLen),
3831                          Hint);
3832   }
3833 }
3834 
3835 void CheckFormatHandler::HandleNonStandardLengthModifier(
3836     const analyze_format_string::FormatSpecifier &FS,
3837     const char *startSpecifier, unsigned specifierLen) {
3838   using namespace analyze_format_string;
3839 
3840   const LengthModifier &LM = FS.getLengthModifier();
3841   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3842 
3843   // See if we know how to fix this length modifier.
3844   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
3845   if (FixedLM) {
3846     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3847                            << LM.toString() << 0,
3848                          getLocationOfByte(LM.getStart()),
3849                          /*IsStringLocation*/true,
3850                          getSpecifierRange(startSpecifier, specifierLen));
3851 
3852     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3853       << FixedLM->toString()
3854       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
3855 
3856   } else {
3857     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3858                            << LM.toString() << 0,
3859                          getLocationOfByte(LM.getStart()),
3860                          /*IsStringLocation*/true,
3861                          getSpecifierRange(startSpecifier, specifierLen));
3862   }
3863 }
3864 
3865 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3866     const analyze_format_string::ConversionSpecifier &CS,
3867     const char *startSpecifier, unsigned specifierLen) {
3868   using namespace analyze_format_string;
3869 
3870   // See if we know how to fix this conversion specifier.
3871   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
3872   if (FixedCS) {
3873     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3874                           << CS.toString() << /*conversion specifier*/1,
3875                          getLocationOfByte(CS.getStart()),
3876                          /*IsStringLocation*/true,
3877                          getSpecifierRange(startSpecifier, specifierLen));
3878 
3879     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
3880     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
3881       << FixedCS->toString()
3882       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
3883   } else {
3884     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
3885                           << CS.toString() << /*conversion specifier*/1,
3886                          getLocationOfByte(CS.getStart()),
3887                          /*IsStringLocation*/true,
3888                          getSpecifierRange(startSpecifier, specifierLen));
3889   }
3890 }
3891 
3892 void CheckFormatHandler::HandlePosition(const char *startPos,
3893                                         unsigned posLen) {
3894   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
3895                                getLocationOfByte(startPos),
3896                                /*IsStringLocation*/true,
3897                                getSpecifierRange(startPos, posLen));
3898 }
3899 
3900 void
3901 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
3902                                      analyze_format_string::PositionContext p) {
3903   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
3904                          << (unsigned) p,
3905                        getLocationOfByte(startPos), /*IsStringLocation*/true,
3906                        getSpecifierRange(startPos, posLen));
3907 }
3908 
3909 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
3910                                             unsigned posLen) {
3911   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
3912                                getLocationOfByte(startPos),
3913                                /*IsStringLocation*/true,
3914                                getSpecifierRange(startPos, posLen));
3915 }
3916 
3917 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
3918   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3919     // The presence of a null character is likely an error.
3920     EmitFormatDiagnostic(
3921       S.PDiag(diag::warn_printf_format_string_contains_null_char),
3922       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
3923       getFormatStringRange());
3924   }
3925 }
3926 
3927 // Note that this may return NULL if there was an error parsing or building
3928 // one of the argument expressions.
3929 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
3930   return Args[FirstDataArg + i];
3931 }
3932 
3933 void CheckFormatHandler::DoneProcessing() {
3934   // Does the number of data arguments exceed the number of
3935   // format conversions in the format string?
3936   if (!HasVAListArg) {
3937       // Find any arguments that weren't covered.
3938     CoveredArgs.flip();
3939     signed notCoveredArg = CoveredArgs.find_first();
3940     if (notCoveredArg >= 0) {
3941       assert((unsigned)notCoveredArg < NumDataArgs);
3942       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
3943     } else {
3944       UncoveredArg.setAllCovered();
3945     }
3946   }
3947 }
3948 
3949 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
3950                                    const Expr *ArgExpr) {
3951   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
3952          "Invalid state");
3953 
3954   if (!ArgExpr)
3955     return;
3956 
3957   SourceLocation Loc = ArgExpr->getLocStart();
3958 
3959   if (S.getSourceManager().isInSystemMacro(Loc))
3960     return;
3961 
3962   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
3963   for (auto E : DiagnosticExprs)
3964     PDiag << E->getSourceRange();
3965 
3966   CheckFormatHandler::EmitFormatDiagnostic(
3967                                   S, IsFunctionCall, DiagnosticExprs[0],
3968                                   PDiag, Loc, /*IsStringLocation*/false,
3969                                   DiagnosticExprs[0]->getSourceRange());
3970 }
3971 
3972 bool
3973 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
3974                                                      SourceLocation Loc,
3975                                                      const char *startSpec,
3976                                                      unsigned specifierLen,
3977                                                      const char *csStart,
3978                                                      unsigned csLen) {
3979   bool keepGoing = true;
3980   if (argIndex < NumDataArgs) {
3981     // Consider the argument coverered, even though the specifier doesn't
3982     // make sense.
3983     CoveredArgs.set(argIndex);
3984   }
3985   else {
3986     // If argIndex exceeds the number of data arguments we
3987     // don't issue a warning because that is just a cascade of warnings (and
3988     // they may have intended '%%' anyway). We don't want to continue processing
3989     // the format string after this point, however, as we will like just get
3990     // gibberish when trying to match arguments.
3991     keepGoing = false;
3992   }
3993 
3994   StringRef Specifier(csStart, csLen);
3995 
3996   // If the specifier in non-printable, it could be the first byte of a UTF-8
3997   // sequence. In that case, print the UTF-8 code point. If not, print the byte
3998   // hex value.
3999   std::string CodePointStr;
4000   if (!llvm::sys::locale::isPrint(*csStart)) {
4001     UTF32 CodePoint;
4002     const UTF8 **B = reinterpret_cast<const UTF8 **>(&csStart);
4003     const UTF8 *E =
4004         reinterpret_cast<const UTF8 *>(csStart + csLen);
4005     ConversionResult Result =
4006         llvm::convertUTF8Sequence(B, E, &CodePoint, strictConversion);
4007 
4008     if (Result != conversionOK) {
4009       unsigned char FirstChar = *csStart;
4010       CodePoint = (UTF32)FirstChar;
4011     }
4012 
4013     llvm::raw_string_ostream OS(CodePointStr);
4014     if (CodePoint < 256)
4015       OS << "\\x" << llvm::format("%02x", CodePoint);
4016     else if (CodePoint <= 0xFFFF)
4017       OS << "\\u" << llvm::format("%04x", CodePoint);
4018     else
4019       OS << "\\U" << llvm::format("%08x", CodePoint);
4020     OS.flush();
4021     Specifier = CodePointStr;
4022   }
4023 
4024   EmitFormatDiagnostic(
4025       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
4026       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
4027 
4028   return keepGoing;
4029 }
4030 
4031 void
4032 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
4033                                                       const char *startSpec,
4034                                                       unsigned specifierLen) {
4035   EmitFormatDiagnostic(
4036     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
4037     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
4038 }
4039 
4040 bool
4041 CheckFormatHandler::CheckNumArgs(
4042   const analyze_format_string::FormatSpecifier &FS,
4043   const analyze_format_string::ConversionSpecifier &CS,
4044   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
4045 
4046   if (argIndex >= NumDataArgs) {
4047     PartialDiagnostic PDiag = FS.usesPositionalArg()
4048       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
4049            << (argIndex+1) << NumDataArgs)
4050       : S.PDiag(diag::warn_printf_insufficient_data_args);
4051     EmitFormatDiagnostic(
4052       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
4053       getSpecifierRange(startSpecifier, specifierLen));
4054 
4055     // Since more arguments than conversion tokens are given, by extension
4056     // all arguments are covered, so mark this as so.
4057     UncoveredArg.setAllCovered();
4058     return false;
4059   }
4060   return true;
4061 }
4062 
4063 template<typename Range>
4064 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
4065                                               SourceLocation Loc,
4066                                               bool IsStringLocation,
4067                                               Range StringRange,
4068                                               ArrayRef<FixItHint> FixIt) {
4069   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
4070                        Loc, IsStringLocation, StringRange, FixIt);
4071 }
4072 
4073 /// \brief If the format string is not within the funcion call, emit a note
4074 /// so that the function call and string are in diagnostic messages.
4075 ///
4076 /// \param InFunctionCall if true, the format string is within the function
4077 /// call and only one diagnostic message will be produced.  Otherwise, an
4078 /// extra note will be emitted pointing to location of the format string.
4079 ///
4080 /// \param ArgumentExpr the expression that is passed as the format string
4081 /// argument in the function call.  Used for getting locations when two
4082 /// diagnostics are emitted.
4083 ///
4084 /// \param PDiag the callee should already have provided any strings for the
4085 /// diagnostic message.  This function only adds locations and fixits
4086 /// to diagnostics.
4087 ///
4088 /// \param Loc primary location for diagnostic.  If two diagnostics are
4089 /// required, one will be at Loc and a new SourceLocation will be created for
4090 /// the other one.
4091 ///
4092 /// \param IsStringLocation if true, Loc points to the format string should be
4093 /// used for the note.  Otherwise, Loc points to the argument list and will
4094 /// be used with PDiag.
4095 ///
4096 /// \param StringRange some or all of the string to highlight.  This is
4097 /// templated so it can accept either a CharSourceRange or a SourceRange.
4098 ///
4099 /// \param FixIt optional fix it hint for the format string.
4100 template<typename Range>
4101 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
4102                                               const Expr *ArgumentExpr,
4103                                               PartialDiagnostic PDiag,
4104                                               SourceLocation Loc,
4105                                               bool IsStringLocation,
4106                                               Range StringRange,
4107                                               ArrayRef<FixItHint> FixIt) {
4108   if (InFunctionCall) {
4109     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
4110     D << StringRange;
4111     D << FixIt;
4112   } else {
4113     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
4114       << ArgumentExpr->getSourceRange();
4115 
4116     const Sema::SemaDiagnosticBuilder &Note =
4117       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
4118              diag::note_format_string_defined);
4119 
4120     Note << StringRange;
4121     Note << FixIt;
4122   }
4123 }
4124 
4125 //===--- CHECK: Printf format string checking ------------------------------===//
4126 
4127 namespace {
4128 class CheckPrintfHandler : public CheckFormatHandler {
4129   bool ObjCContext;
4130 
4131 public:
4132   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
4133                      const Expr *origFormatExpr, unsigned firstDataArg,
4134                      unsigned numDataArgs, bool isObjC,
4135                      const char *beg, bool hasVAListArg,
4136                      ArrayRef<const Expr *> Args,
4137                      unsigned formatIdx, bool inFunctionCall,
4138                      Sema::VariadicCallType CallType,
4139                      llvm::SmallBitVector &CheckedVarArgs,
4140                      UncoveredArgHandler &UncoveredArg)
4141     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4142                          numDataArgs, beg, hasVAListArg, Args,
4143                          formatIdx, inFunctionCall, CallType, CheckedVarArgs,
4144                          UncoveredArg),
4145       ObjCContext(isObjC)
4146   {}
4147 
4148   bool HandleInvalidPrintfConversionSpecifier(
4149                                       const analyze_printf::PrintfSpecifier &FS,
4150                                       const char *startSpecifier,
4151                                       unsigned specifierLen) override;
4152 
4153   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
4154                              const char *startSpecifier,
4155                              unsigned specifierLen) override;
4156   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4157                        const char *StartSpecifier,
4158                        unsigned SpecifierLen,
4159                        const Expr *E);
4160 
4161   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
4162                     const char *startSpecifier, unsigned specifierLen);
4163   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
4164                            const analyze_printf::OptionalAmount &Amt,
4165                            unsigned type,
4166                            const char *startSpecifier, unsigned specifierLen);
4167   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4168                   const analyze_printf::OptionalFlag &flag,
4169                   const char *startSpecifier, unsigned specifierLen);
4170   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
4171                          const analyze_printf::OptionalFlag &ignoredFlag,
4172                          const analyze_printf::OptionalFlag &flag,
4173                          const char *startSpecifier, unsigned specifierLen);
4174   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
4175                            const Expr *E);
4176 
4177   void HandleEmptyObjCModifierFlag(const char *startFlag,
4178                                    unsigned flagLen) override;
4179 
4180   void HandleInvalidObjCModifierFlag(const char *startFlag,
4181                                             unsigned flagLen) override;
4182 
4183   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
4184                                            const char *flagsEnd,
4185                                            const char *conversionPosition)
4186                                              override;
4187 };
4188 } // end anonymous namespace
4189 
4190 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
4191                                       const analyze_printf::PrintfSpecifier &FS,
4192                                       const char *startSpecifier,
4193                                       unsigned specifierLen) {
4194   const analyze_printf::PrintfConversionSpecifier &CS =
4195     FS.getConversionSpecifier();
4196 
4197   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4198                                           getLocationOfByte(CS.getStart()),
4199                                           startSpecifier, specifierLen,
4200                                           CS.getStart(), CS.getLength());
4201 }
4202 
4203 bool CheckPrintfHandler::HandleAmount(
4204                                const analyze_format_string::OptionalAmount &Amt,
4205                                unsigned k, const char *startSpecifier,
4206                                unsigned specifierLen) {
4207   if (Amt.hasDataArgument()) {
4208     if (!HasVAListArg) {
4209       unsigned argIndex = Amt.getArgIndex();
4210       if (argIndex >= NumDataArgs) {
4211         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
4212                                << k,
4213                              getLocationOfByte(Amt.getStart()),
4214                              /*IsStringLocation*/true,
4215                              getSpecifierRange(startSpecifier, specifierLen));
4216         // Don't do any more checking.  We will just emit
4217         // spurious errors.
4218         return false;
4219       }
4220 
4221       // Type check the data argument.  It should be an 'int'.
4222       // Although not in conformance with C99, we also allow the argument to be
4223       // an 'unsigned int' as that is a reasonably safe case.  GCC also
4224       // doesn't emit a warning for that case.
4225       CoveredArgs.set(argIndex);
4226       const Expr *Arg = getDataArg(argIndex);
4227       if (!Arg)
4228         return false;
4229 
4230       QualType T = Arg->getType();
4231 
4232       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
4233       assert(AT.isValid());
4234 
4235       if (!AT.matchesType(S.Context, T)) {
4236         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
4237                                << k << AT.getRepresentativeTypeName(S.Context)
4238                                << T << Arg->getSourceRange(),
4239                              getLocationOfByte(Amt.getStart()),
4240                              /*IsStringLocation*/true,
4241                              getSpecifierRange(startSpecifier, specifierLen));
4242         // Don't do any more checking.  We will just emit
4243         // spurious errors.
4244         return false;
4245       }
4246     }
4247   }
4248   return true;
4249 }
4250 
4251 void CheckPrintfHandler::HandleInvalidAmount(
4252                                       const analyze_printf::PrintfSpecifier &FS,
4253                                       const analyze_printf::OptionalAmount &Amt,
4254                                       unsigned type,
4255                                       const char *startSpecifier,
4256                                       unsigned specifierLen) {
4257   const analyze_printf::PrintfConversionSpecifier &CS =
4258     FS.getConversionSpecifier();
4259 
4260   FixItHint fixit =
4261     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
4262       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
4263                                  Amt.getConstantLength()))
4264       : FixItHint();
4265 
4266   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
4267                          << type << CS.toString(),
4268                        getLocationOfByte(Amt.getStart()),
4269                        /*IsStringLocation*/true,
4270                        getSpecifierRange(startSpecifier, specifierLen),
4271                        fixit);
4272 }
4273 
4274 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
4275                                     const analyze_printf::OptionalFlag &flag,
4276                                     const char *startSpecifier,
4277                                     unsigned specifierLen) {
4278   // Warn about pointless flag with a fixit removal.
4279   const analyze_printf::PrintfConversionSpecifier &CS =
4280     FS.getConversionSpecifier();
4281   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
4282                          << flag.toString() << CS.toString(),
4283                        getLocationOfByte(flag.getPosition()),
4284                        /*IsStringLocation*/true,
4285                        getSpecifierRange(startSpecifier, specifierLen),
4286                        FixItHint::CreateRemoval(
4287                          getSpecifierRange(flag.getPosition(), 1)));
4288 }
4289 
4290 void CheckPrintfHandler::HandleIgnoredFlag(
4291                                 const analyze_printf::PrintfSpecifier &FS,
4292                                 const analyze_printf::OptionalFlag &ignoredFlag,
4293                                 const analyze_printf::OptionalFlag &flag,
4294                                 const char *startSpecifier,
4295                                 unsigned specifierLen) {
4296   // Warn about ignored flag with a fixit removal.
4297   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
4298                          << ignoredFlag.toString() << flag.toString(),
4299                        getLocationOfByte(ignoredFlag.getPosition()),
4300                        /*IsStringLocation*/true,
4301                        getSpecifierRange(startSpecifier, specifierLen),
4302                        FixItHint::CreateRemoval(
4303                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
4304 }
4305 
4306 //  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
4307 //                            bool IsStringLocation, Range StringRange,
4308 //                            ArrayRef<FixItHint> Fixit = None);
4309 
4310 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
4311                                                      unsigned flagLen) {
4312   // Warn about an empty flag.
4313   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
4314                        getLocationOfByte(startFlag),
4315                        /*IsStringLocation*/true,
4316                        getSpecifierRange(startFlag, flagLen));
4317 }
4318 
4319 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
4320                                                        unsigned flagLen) {
4321   // Warn about an invalid flag.
4322   auto Range = getSpecifierRange(startFlag, flagLen);
4323   StringRef flag(startFlag, flagLen);
4324   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
4325                       getLocationOfByte(startFlag),
4326                       /*IsStringLocation*/true,
4327                       Range, FixItHint::CreateRemoval(Range));
4328 }
4329 
4330 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
4331     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
4332     // Warn about using '[...]' without a '@' conversion.
4333     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
4334     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
4335     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
4336                          getLocationOfByte(conversionPosition),
4337                          /*IsStringLocation*/true,
4338                          Range, FixItHint::CreateRemoval(Range));
4339 }
4340 
4341 // Determines if the specified is a C++ class or struct containing
4342 // a member with the specified name and kind (e.g. a CXXMethodDecl named
4343 // "c_str()").
4344 template<typename MemberKind>
4345 static llvm::SmallPtrSet<MemberKind*, 1>
4346 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
4347   const RecordType *RT = Ty->getAs<RecordType>();
4348   llvm::SmallPtrSet<MemberKind*, 1> Results;
4349 
4350   if (!RT)
4351     return Results;
4352   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
4353   if (!RD || !RD->getDefinition())
4354     return Results;
4355 
4356   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
4357                  Sema::LookupMemberName);
4358   R.suppressDiagnostics();
4359 
4360   // We just need to include all members of the right kind turned up by the
4361   // filter, at this point.
4362   if (S.LookupQualifiedName(R, RT->getDecl()))
4363     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4364       NamedDecl *decl = (*I)->getUnderlyingDecl();
4365       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
4366         Results.insert(FK);
4367     }
4368   return Results;
4369 }
4370 
4371 /// Check if we could call '.c_str()' on an object.
4372 ///
4373 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
4374 /// allow the call, or if it would be ambiguous).
4375 bool Sema::hasCStrMethod(const Expr *E) {
4376   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4377   MethodSet Results =
4378       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
4379   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4380        MI != ME; ++MI)
4381     if ((*MI)->getMinRequiredArguments() == 0)
4382       return true;
4383   return false;
4384 }
4385 
4386 // Check if a (w)string was passed when a (w)char* was needed, and offer a
4387 // better diagnostic if so. AT is assumed to be valid.
4388 // Returns true when a c_str() conversion method is found.
4389 bool CheckPrintfHandler::checkForCStrMembers(
4390     const analyze_printf::ArgType &AT, const Expr *E) {
4391   typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
4392 
4393   MethodSet Results =
4394       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
4395 
4396   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
4397        MI != ME; ++MI) {
4398     const CXXMethodDecl *Method = *MI;
4399     if (Method->getMinRequiredArguments() == 0 &&
4400         AT.matchesType(S.Context, Method->getReturnType())) {
4401       // FIXME: Suggest parens if the expression needs them.
4402       SourceLocation EndLoc = S.getLocForEndOfToken(E->getLocEnd());
4403       S.Diag(E->getLocStart(), diag::note_printf_c_str)
4404           << "c_str()"
4405           << FixItHint::CreateInsertion(EndLoc, ".c_str()");
4406       return true;
4407     }
4408   }
4409 
4410   return false;
4411 }
4412 
4413 bool
4414 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
4415                                             &FS,
4416                                           const char *startSpecifier,
4417                                           unsigned specifierLen) {
4418   using namespace analyze_format_string;
4419   using namespace analyze_printf;
4420   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
4421 
4422   if (FS.consumesDataArgument()) {
4423     if (atFirstArg) {
4424         atFirstArg = false;
4425         usesPositionalArgs = FS.usesPositionalArg();
4426     }
4427     else if (usesPositionalArgs != FS.usesPositionalArg()) {
4428       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4429                                         startSpecifier, specifierLen);
4430       return false;
4431     }
4432   }
4433 
4434   // First check if the field width, precision, and conversion specifier
4435   // have matching data arguments.
4436   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
4437                     startSpecifier, specifierLen)) {
4438     return false;
4439   }
4440 
4441   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
4442                     startSpecifier, specifierLen)) {
4443     return false;
4444   }
4445 
4446   if (!CS.consumesDataArgument()) {
4447     // FIXME: Technically specifying a precision or field width here
4448     // makes no sense.  Worth issuing a warning at some point.
4449     return true;
4450   }
4451 
4452   // Consume the argument.
4453   unsigned argIndex = FS.getArgIndex();
4454   if (argIndex < NumDataArgs) {
4455     // The check to see if the argIndex is valid will come later.
4456     // We set the bit here because we may exit early from this
4457     // function if we encounter some other error.
4458     CoveredArgs.set(argIndex);
4459   }
4460 
4461   // FreeBSD kernel extensions.
4462   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
4463       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
4464     // We need at least two arguments.
4465     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4466       return false;
4467 
4468     // Claim the second argument.
4469     CoveredArgs.set(argIndex + 1);
4470 
4471     // Type check the first argument (int for %b, pointer for %D)
4472     const Expr *Ex = getDataArg(argIndex);
4473     const analyze_printf::ArgType &AT =
4474       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
4475         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4476     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
4477       EmitFormatDiagnostic(
4478         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4479         << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
4480         << false << Ex->getSourceRange(),
4481         Ex->getLocStart(), /*IsStringLocation*/false,
4482         getSpecifierRange(startSpecifier, specifierLen));
4483 
4484     // Type check the second argument (char * for both %b and %D)
4485     Ex = getDataArg(argIndex + 1);
4486     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4487     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4488       EmitFormatDiagnostic(
4489         S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4490         << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4491         << false << Ex->getSourceRange(),
4492         Ex->getLocStart(), /*IsStringLocation*/false,
4493         getSpecifierRange(startSpecifier, specifierLen));
4494 
4495      return true;
4496   }
4497 
4498   // Check for using an Objective-C specific conversion specifier
4499   // in a non-ObjC literal.
4500   if (!ObjCContext && CS.isObjCArg()) {
4501     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4502                                                   specifierLen);
4503   }
4504 
4505   // Check for invalid use of field width
4506   if (!FS.hasValidFieldWidth()) {
4507     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
4508         startSpecifier, specifierLen);
4509   }
4510 
4511   // Check for invalid use of precision
4512   if (!FS.hasValidPrecision()) {
4513     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
4514         startSpecifier, specifierLen);
4515   }
4516 
4517   // Check each flag does not conflict with any other component.
4518   if (!FS.hasValidThousandsGroupingPrefix())
4519     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
4520   if (!FS.hasValidLeadingZeros())
4521     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
4522   if (!FS.hasValidPlusPrefix())
4523     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
4524   if (!FS.hasValidSpacePrefix())
4525     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
4526   if (!FS.hasValidAlternativeForm())
4527     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
4528   if (!FS.hasValidLeftJustified())
4529     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
4530 
4531   // Check that flags are not ignored by another flag
4532   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
4533     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
4534         startSpecifier, specifierLen);
4535   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
4536     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
4537             startSpecifier, specifierLen);
4538 
4539   // Check the length modifier is valid with the given conversion specifier.
4540   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
4541     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4542                                 diag::warn_format_nonsensical_length);
4543   else if (!FS.hasStandardLengthModifier())
4544     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4545   else if (!FS.hasStandardLengthConversionCombination())
4546     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4547                                 diag::warn_format_non_standard_conversion_spec);
4548 
4549   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
4550     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4551 
4552   // The remaining checks depend on the data arguments.
4553   if (HasVAListArg)
4554     return true;
4555 
4556   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4557     return false;
4558 
4559   const Expr *Arg = getDataArg(argIndex);
4560   if (!Arg)
4561     return true;
4562 
4563   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
4564 }
4565 
4566 static bool requiresParensToAddCast(const Expr *E) {
4567   // FIXME: We should have a general way to reason about operator
4568   // precedence and whether parens are actually needed here.
4569   // Take care of a few common cases where they aren't.
4570   const Expr *Inside = E->IgnoreImpCasts();
4571   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
4572     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
4573 
4574   switch (Inside->getStmtClass()) {
4575   case Stmt::ArraySubscriptExprClass:
4576   case Stmt::CallExprClass:
4577   case Stmt::CharacterLiteralClass:
4578   case Stmt::CXXBoolLiteralExprClass:
4579   case Stmt::DeclRefExprClass:
4580   case Stmt::FloatingLiteralClass:
4581   case Stmt::IntegerLiteralClass:
4582   case Stmt::MemberExprClass:
4583   case Stmt::ObjCArrayLiteralClass:
4584   case Stmt::ObjCBoolLiteralExprClass:
4585   case Stmt::ObjCBoxedExprClass:
4586   case Stmt::ObjCDictionaryLiteralClass:
4587   case Stmt::ObjCEncodeExprClass:
4588   case Stmt::ObjCIvarRefExprClass:
4589   case Stmt::ObjCMessageExprClass:
4590   case Stmt::ObjCPropertyRefExprClass:
4591   case Stmt::ObjCStringLiteralClass:
4592   case Stmt::ObjCSubscriptRefExprClass:
4593   case Stmt::ParenExprClass:
4594   case Stmt::StringLiteralClass:
4595   case Stmt::UnaryOperatorClass:
4596     return false;
4597   default:
4598     return true;
4599   }
4600 }
4601 
4602 static std::pair<QualType, StringRef>
4603 shouldNotPrintDirectly(const ASTContext &Context,
4604                        QualType IntendedTy,
4605                        const Expr *E) {
4606   // Use a 'while' to peel off layers of typedefs.
4607   QualType TyTy = IntendedTy;
4608   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
4609     StringRef Name = UserTy->getDecl()->getName();
4610     QualType CastTy = llvm::StringSwitch<QualType>(Name)
4611       .Case("NSInteger", Context.LongTy)
4612       .Case("NSUInteger", Context.UnsignedLongTy)
4613       .Case("SInt32", Context.IntTy)
4614       .Case("UInt32", Context.UnsignedIntTy)
4615       .Default(QualType());
4616 
4617     if (!CastTy.isNull())
4618       return std::make_pair(CastTy, Name);
4619 
4620     TyTy = UserTy->desugar();
4621   }
4622 
4623   // Strip parens if necessary.
4624   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4625     return shouldNotPrintDirectly(Context,
4626                                   PE->getSubExpr()->getType(),
4627                                   PE->getSubExpr());
4628 
4629   // If this is a conditional expression, then its result type is constructed
4630   // via usual arithmetic conversions and thus there might be no necessary
4631   // typedef sugar there.  Recurse to operands to check for NSInteger &
4632   // Co. usage condition.
4633   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4634     QualType TrueTy, FalseTy;
4635     StringRef TrueName, FalseName;
4636 
4637     std::tie(TrueTy, TrueName) =
4638       shouldNotPrintDirectly(Context,
4639                              CO->getTrueExpr()->getType(),
4640                              CO->getTrueExpr());
4641     std::tie(FalseTy, FalseName) =
4642       shouldNotPrintDirectly(Context,
4643                              CO->getFalseExpr()->getType(),
4644                              CO->getFalseExpr());
4645 
4646     if (TrueTy == FalseTy)
4647       return std::make_pair(TrueTy, TrueName);
4648     else if (TrueTy.isNull())
4649       return std::make_pair(FalseTy, FalseName);
4650     else if (FalseTy.isNull())
4651       return std::make_pair(TrueTy, TrueName);
4652   }
4653 
4654   return std::make_pair(QualType(), StringRef());
4655 }
4656 
4657 bool
4658 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
4659                                     const char *StartSpecifier,
4660                                     unsigned SpecifierLen,
4661                                     const Expr *E) {
4662   using namespace analyze_format_string;
4663   using namespace analyze_printf;
4664   // Now type check the data expression that matches the
4665   // format specifier.
4666   const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
4667                                                     ObjCContext);
4668   if (!AT.isValid())
4669     return true;
4670 
4671   QualType ExprTy = E->getType();
4672   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4673     ExprTy = TET->getUnderlyingExpr()->getType();
4674   }
4675 
4676   analyze_printf::ArgType::MatchKind match = AT.matchesType(S.Context, ExprTy);
4677 
4678   if (match == analyze_printf::ArgType::Match) {
4679     return true;
4680   }
4681 
4682   // Look through argument promotions for our error message's reported type.
4683   // This includes the integral and floating promotions, but excludes array
4684   // and function pointer decay; seeing that an argument intended to be a
4685   // string has type 'char [6]' is probably more confusing than 'char *'.
4686   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4687     if (ICE->getCastKind() == CK_IntegralCast ||
4688         ICE->getCastKind() == CK_FloatingCast) {
4689       E = ICE->getSubExpr();
4690       ExprTy = E->getType();
4691 
4692       // Check if we didn't match because of an implicit cast from a 'char'
4693       // or 'short' to an 'int'.  This is done because printf is a varargs
4694       // function.
4695       if (ICE->getType() == S.Context.IntTy ||
4696           ICE->getType() == S.Context.UnsignedIntTy) {
4697         // All further checking is done on the subexpression.
4698         if (AT.matchesType(S.Context, ExprTy))
4699           return true;
4700       }
4701     }
4702   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
4703     // Special case for 'a', which has type 'int' in C.
4704     // Note, however, that we do /not/ want to treat multibyte constants like
4705     // 'MooV' as characters! This form is deprecated but still exists.
4706     if (ExprTy == S.Context.IntTy)
4707       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4708         ExprTy = S.Context.CharTy;
4709   }
4710 
4711   // Look through enums to their underlying type.
4712   bool IsEnum = false;
4713   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
4714     ExprTy = EnumTy->getDecl()->getIntegerType();
4715     IsEnum = true;
4716   }
4717 
4718   // %C in an Objective-C context prints a unichar, not a wchar_t.
4719   // If the argument is an integer of some kind, believe the %C and suggest
4720   // a cast instead of changing the conversion specifier.
4721   QualType IntendedTy = ExprTy;
4722   if (ObjCContext &&
4723       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
4724     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4725         !ExprTy->isCharType()) {
4726       // 'unichar' is defined as a typedef of unsigned short, but we should
4727       // prefer using the typedef if it is visible.
4728       IntendedTy = S.Context.UnsignedShortTy;
4729 
4730       // While we are here, check if the value is an IntegerLiteral that happens
4731       // to be within the valid range.
4732       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
4733         const llvm::APInt &V = IL->getValue();
4734         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4735           return true;
4736       }
4737 
4738       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
4739                           Sema::LookupOrdinaryName);
4740       if (S.LookupName(Result, S.getCurScope())) {
4741         NamedDecl *ND = Result.getFoundDecl();
4742         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
4743           if (TD->getUnderlyingType() == IntendedTy)
4744             IntendedTy = S.Context.getTypedefType(TD);
4745       }
4746     }
4747   }
4748 
4749   // Special-case some of Darwin's platform-independence types by suggesting
4750   // casts to primitive types that are known to be large enough.
4751   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
4752   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
4753     QualType CastTy;
4754     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
4755     if (!CastTy.isNull()) {
4756       IntendedTy = CastTy;
4757       ShouldNotPrintDirectly = true;
4758     }
4759   }
4760 
4761   // We may be able to offer a FixItHint if it is a supported type.
4762   PrintfSpecifier fixedFS = FS;
4763   bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
4764                                  S.Context, ObjCContext);
4765 
4766   if (success) {
4767     // Get the fix string from the fixed format specifier
4768     SmallString<16> buf;
4769     llvm::raw_svector_ostream os(buf);
4770     fixedFS.toString(os);
4771 
4772     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4773 
4774     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
4775       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4776       if (match == analyze_format_string::ArgType::NoMatchPedantic) {
4777         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4778       }
4779       // In this case, the specifier is wrong and should be changed to match
4780       // the argument.
4781       EmitFormatDiagnostic(S.PDiag(diag)
4782                                << AT.getRepresentativeTypeName(S.Context)
4783                                << IntendedTy << IsEnum << E->getSourceRange(),
4784                            E->getLocStart(),
4785                            /*IsStringLocation*/ false, SpecRange,
4786                            FixItHint::CreateReplacement(SpecRange, os.str()));
4787     } else {
4788       // The canonical type for formatting this value is different from the
4789       // actual type of the expression. (This occurs, for example, with Darwin's
4790       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
4791       // should be printed as 'long' for 64-bit compatibility.)
4792       // Rather than emitting a normal format/argument mismatch, we want to
4793       // add a cast to the recommended type (and correct the format string
4794       // if necessary).
4795       SmallString<16> CastBuf;
4796       llvm::raw_svector_ostream CastFix(CastBuf);
4797       CastFix << "(";
4798       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4799       CastFix << ")";
4800 
4801       SmallVector<FixItHint,4> Hints;
4802       if (!AT.matchesType(S.Context, IntendedTy))
4803         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
4804 
4805       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
4806         // If there's already a cast present, just replace it.
4807         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4808         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
4809 
4810       } else if (!requiresParensToAddCast(E)) {
4811         // If the expression has high enough precedence,
4812         // just write the C-style cast.
4813         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4814                                                    CastFix.str()));
4815       } else {
4816         // Otherwise, add parens around the expression as well as the cast.
4817         CastFix << "(";
4818         Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
4819                                                    CastFix.str()));
4820 
4821         SourceLocation After = S.getLocForEndOfToken(E->getLocEnd());
4822         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
4823       }
4824 
4825       if (ShouldNotPrintDirectly) {
4826         // The expression has a type that should not be printed directly.
4827         // We extract the name from the typedef because we don't want to show
4828         // the underlying type in the diagnostic.
4829         StringRef Name;
4830         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4831           Name = TypedefTy->getDecl()->getName();
4832         else
4833           Name = CastTyName;
4834         EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
4835                                << Name << IntendedTy << IsEnum
4836                                << E->getSourceRange(),
4837                              E->getLocStart(), /*IsStringLocation=*/false,
4838                              SpecRange, Hints);
4839       } else {
4840         // In this case, the expression could be printed using a different
4841         // specifier, but we've decided that the specifier is probably correct
4842         // and we should cast instead. Just use the normal warning message.
4843         EmitFormatDiagnostic(
4844           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4845             << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
4846             << E->getSourceRange(),
4847           E->getLocStart(), /*IsStringLocation*/false,
4848           SpecRange, Hints);
4849       }
4850     }
4851   } else {
4852     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
4853                                                    SpecifierLen);
4854     // Since the warning for passing non-POD types to variadic functions
4855     // was deferred until now, we emit a warning for non-POD
4856     // arguments here.
4857     switch (S.isValidVarArgType(ExprTy)) {
4858     case Sema::VAK_Valid:
4859     case Sema::VAK_ValidInCXX11: {
4860       unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4861       if (match == analyze_printf::ArgType::NoMatchPedantic) {
4862         diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4863       }
4864 
4865       EmitFormatDiagnostic(
4866           S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4867                         << IsEnum << CSR << E->getSourceRange(),
4868           E->getLocStart(), /*IsStringLocation*/ false, CSR);
4869       break;
4870     }
4871     case Sema::VAK_Undefined:
4872     case Sema::VAK_MSVCUndefined:
4873       EmitFormatDiagnostic(
4874         S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4875           << S.getLangOpts().CPlusPlus11
4876           << ExprTy
4877           << CallType
4878           << AT.getRepresentativeTypeName(S.Context)
4879           << CSR
4880           << E->getSourceRange(),
4881         E->getLocStart(), /*IsStringLocation*/false, CSR);
4882       checkForCStrMembers(AT, E);
4883       break;
4884 
4885     case Sema::VAK_Invalid:
4886       if (ExprTy->isObjCObjectType())
4887         EmitFormatDiagnostic(
4888           S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4889             << S.getLangOpts().CPlusPlus11
4890             << ExprTy
4891             << CallType
4892             << AT.getRepresentativeTypeName(S.Context)
4893             << CSR
4894             << E->getSourceRange(),
4895           E->getLocStart(), /*IsStringLocation*/false, CSR);
4896       else
4897         // FIXME: If this is an initializer list, suggest removing the braces
4898         // or inserting a cast to the target type.
4899         S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4900           << isa<InitListExpr>(E) << ExprTy << CallType
4901           << AT.getRepresentativeTypeName(S.Context)
4902           << E->getSourceRange();
4903       break;
4904     }
4905 
4906     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
4907            "format string specifier index out of range");
4908     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
4909   }
4910 
4911   return true;
4912 }
4913 
4914 //===--- CHECK: Scanf format string checking ------------------------------===//
4915 
4916 namespace {
4917 class CheckScanfHandler : public CheckFormatHandler {
4918 public:
4919   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
4920                     const Expr *origFormatExpr, unsigned firstDataArg,
4921                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
4922                     ArrayRef<const Expr *> Args,
4923                     unsigned formatIdx, bool inFunctionCall,
4924                     Sema::VariadicCallType CallType,
4925                     llvm::SmallBitVector &CheckedVarArgs,
4926                     UncoveredArgHandler &UncoveredArg)
4927     : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4928                          numDataArgs, beg, hasVAListArg,
4929                          Args, formatIdx, inFunctionCall, CallType,
4930                          CheckedVarArgs, UncoveredArg)
4931   {}
4932 
4933   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
4934                             const char *startSpecifier,
4935                             unsigned specifierLen) override;
4936 
4937   bool HandleInvalidScanfConversionSpecifier(
4938           const analyze_scanf::ScanfSpecifier &FS,
4939           const char *startSpecifier,
4940           unsigned specifierLen) override;
4941 
4942   void HandleIncompleteScanList(const char *start, const char *end) override;
4943 };
4944 } // end anonymous namespace
4945 
4946 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
4947                                                  const char *end) {
4948   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4949                        getLocationOfByte(end), /*IsStringLocation*/true,
4950                        getSpecifierRange(start, end - start));
4951 }
4952 
4953 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4954                                         const analyze_scanf::ScanfSpecifier &FS,
4955                                         const char *startSpecifier,
4956                                         unsigned specifierLen) {
4957 
4958   const analyze_scanf::ScanfConversionSpecifier &CS =
4959     FS.getConversionSpecifier();
4960 
4961   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
4962                                           getLocationOfByte(CS.getStart()),
4963                                           startSpecifier, specifierLen,
4964                                           CS.getStart(), CS.getLength());
4965 }
4966 
4967 bool CheckScanfHandler::HandleScanfSpecifier(
4968                                        const analyze_scanf::ScanfSpecifier &FS,
4969                                        const char *startSpecifier,
4970                                        unsigned specifierLen) {
4971   using namespace analyze_scanf;
4972   using namespace analyze_format_string;
4973 
4974   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
4975 
4976   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
4977   // be used to decide if we are using positional arguments consistently.
4978   if (FS.consumesDataArgument()) {
4979     if (atFirstArg) {
4980       atFirstArg = false;
4981       usesPositionalArgs = FS.usesPositionalArg();
4982     }
4983     else if (usesPositionalArgs != FS.usesPositionalArg()) {
4984       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
4985                                         startSpecifier, specifierLen);
4986       return false;
4987     }
4988   }
4989 
4990   // Check if the field with is non-zero.
4991   const OptionalAmount &Amt = FS.getFieldWidth();
4992   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4993     if (Amt.getConstantAmount() == 0) {
4994       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
4995                                                    Amt.getConstantLength());
4996       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4997                            getLocationOfByte(Amt.getStart()),
4998                            /*IsStringLocation*/true, R,
4999                            FixItHint::CreateRemoval(R));
5000     }
5001   }
5002 
5003   if (!FS.consumesDataArgument()) {
5004     // FIXME: Technically specifying a precision or field width here
5005     // makes no sense.  Worth issuing a warning at some point.
5006     return true;
5007   }
5008 
5009   // Consume the argument.
5010   unsigned argIndex = FS.getArgIndex();
5011   if (argIndex < NumDataArgs) {
5012       // The check to see if the argIndex is valid will come later.
5013       // We set the bit here because we may exit early from this
5014       // function if we encounter some other error.
5015     CoveredArgs.set(argIndex);
5016   }
5017 
5018   // Check the length modifier is valid with the given conversion specifier.
5019   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
5020     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5021                                 diag::warn_format_nonsensical_length);
5022   else if (!FS.hasStandardLengthModifier())
5023     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5024   else if (!FS.hasStandardLengthConversionCombination())
5025     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5026                                 diag::warn_format_non_standard_conversion_spec);
5027 
5028   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
5029     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5030 
5031   // The remaining checks depend on the data arguments.
5032   if (HasVAListArg)
5033     return true;
5034 
5035   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5036     return false;
5037 
5038   // Check that the argument type matches the format specifier.
5039   const Expr *Ex = getDataArg(argIndex);
5040   if (!Ex)
5041     return true;
5042 
5043   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
5044 
5045   if (!AT.isValid()) {
5046     return true;
5047   }
5048 
5049   analyze_format_string::ArgType::MatchKind match =
5050       AT.matchesType(S.Context, Ex->getType());
5051   if (match == analyze_format_string::ArgType::Match) {
5052     return true;
5053   }
5054 
5055   ScanfSpecifier fixedFS = FS;
5056   bool success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
5057                                  S.getLangOpts(), S.Context);
5058 
5059   unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
5060   if (match == analyze_format_string::ArgType::NoMatchPedantic) {
5061     diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
5062   }
5063 
5064   if (success) {
5065     // Get the fix string from the fixed format specifier.
5066     SmallString<128> buf;
5067     llvm::raw_svector_ostream os(buf);
5068     fixedFS.toString(os);
5069 
5070     EmitFormatDiagnostic(
5071         S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
5072                       << Ex->getType() << false << Ex->getSourceRange(),
5073         Ex->getLocStart(),
5074         /*IsStringLocation*/ false,
5075         getSpecifierRange(startSpecifier, specifierLen),
5076         FixItHint::CreateReplacement(
5077             getSpecifierRange(startSpecifier, specifierLen), os.str()));
5078   } else {
5079     EmitFormatDiagnostic(S.PDiag(diag)
5080                              << AT.getRepresentativeTypeName(S.Context)
5081                              << Ex->getType() << false << Ex->getSourceRange(),
5082                          Ex->getLocStart(),
5083                          /*IsStringLocation*/ false,
5084                          getSpecifierRange(startSpecifier, specifierLen));
5085   }
5086 
5087   return true;
5088 }
5089 
5090 static void CheckFormatString(Sema &S, const StringLiteral *FExpr,
5091                               const Expr *OrigFormatExpr,
5092                               ArrayRef<const Expr *> Args,
5093                               bool HasVAListArg, unsigned format_idx,
5094                               unsigned firstDataArg,
5095                               Sema::FormatStringType Type,
5096                               bool inFunctionCall,
5097                               Sema::VariadicCallType CallType,
5098                               llvm::SmallBitVector &CheckedVarArgs,
5099                               UncoveredArgHandler &UncoveredArg) {
5100   // CHECK: is the format string a wide literal?
5101   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
5102     CheckFormatHandler::EmitFormatDiagnostic(
5103       S, inFunctionCall, Args[format_idx],
5104       S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
5105       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5106     return;
5107   }
5108 
5109   // Str - The format string.  NOTE: this is NOT null-terminated!
5110   StringRef StrRef = FExpr->getString();
5111   const char *Str = StrRef.data();
5112   // Account for cases where the string literal is truncated in a declaration.
5113   const ConstantArrayType *T =
5114     S.Context.getAsConstantArrayType(FExpr->getType());
5115   assert(T && "String literal not of constant array type!");
5116   size_t TypeSize = T->getSize().getZExtValue();
5117   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5118   const unsigned numDataArgs = Args.size() - firstDataArg;
5119 
5120   // Emit a warning if the string literal is truncated and does not contain an
5121   // embedded null character.
5122   if (TypeSize <= StrRef.size() &&
5123       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
5124     CheckFormatHandler::EmitFormatDiagnostic(
5125         S, inFunctionCall, Args[format_idx],
5126         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
5127         FExpr->getLocStart(),
5128         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
5129     return;
5130   }
5131 
5132   // CHECK: empty format string?
5133   if (StrLen == 0 && numDataArgs > 0) {
5134     CheckFormatHandler::EmitFormatDiagnostic(
5135       S, inFunctionCall, Args[format_idx],
5136       S.PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
5137       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
5138     return;
5139   }
5140 
5141   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
5142       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSTrace) {
5143     CheckPrintfHandler H(S, FExpr, OrigFormatExpr, firstDataArg,
5144                          numDataArgs, (Type == Sema::FST_NSString ||
5145                                        Type == Sema::FST_OSTrace),
5146                          Str, HasVAListArg, Args, format_idx,
5147                          inFunctionCall, CallType, CheckedVarArgs,
5148                          UncoveredArg);
5149 
5150     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
5151                                                   S.getLangOpts(),
5152                                                   S.Context.getTargetInfo(),
5153                                             Type == Sema::FST_FreeBSDKPrintf))
5154       H.DoneProcessing();
5155   } else if (Type == Sema::FST_Scanf) {
5156     CheckScanfHandler H(S, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
5157                         Str, HasVAListArg, Args, format_idx,
5158                         inFunctionCall, CallType, CheckedVarArgs,
5159                         UncoveredArg);
5160 
5161     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
5162                                                  S.getLangOpts(),
5163                                                  S.Context.getTargetInfo()))
5164       H.DoneProcessing();
5165   } // TODO: handle other formats
5166 }
5167 
5168 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
5169   // Str - The format string.  NOTE: this is NOT null-terminated!
5170   StringRef StrRef = FExpr->getString();
5171   const char *Str = StrRef.data();
5172   // Account for cases where the string literal is truncated in a declaration.
5173   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
5174   assert(T && "String literal not of constant array type!");
5175   size_t TypeSize = T->getSize().getZExtValue();
5176   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
5177   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
5178                                                          getLangOpts(),
5179                                                          Context.getTargetInfo());
5180 }
5181 
5182 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
5183 
5184 // Returns the related absolute value function that is larger, of 0 if one
5185 // does not exist.
5186 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
5187   switch (AbsFunction) {
5188   default:
5189     return 0;
5190 
5191   case Builtin::BI__builtin_abs:
5192     return Builtin::BI__builtin_labs;
5193   case Builtin::BI__builtin_labs:
5194     return Builtin::BI__builtin_llabs;
5195   case Builtin::BI__builtin_llabs:
5196     return 0;
5197 
5198   case Builtin::BI__builtin_fabsf:
5199     return Builtin::BI__builtin_fabs;
5200   case Builtin::BI__builtin_fabs:
5201     return Builtin::BI__builtin_fabsl;
5202   case Builtin::BI__builtin_fabsl:
5203     return 0;
5204 
5205   case Builtin::BI__builtin_cabsf:
5206     return Builtin::BI__builtin_cabs;
5207   case Builtin::BI__builtin_cabs:
5208     return Builtin::BI__builtin_cabsl;
5209   case Builtin::BI__builtin_cabsl:
5210     return 0;
5211 
5212   case Builtin::BIabs:
5213     return Builtin::BIlabs;
5214   case Builtin::BIlabs:
5215     return Builtin::BIllabs;
5216   case Builtin::BIllabs:
5217     return 0;
5218 
5219   case Builtin::BIfabsf:
5220     return Builtin::BIfabs;
5221   case Builtin::BIfabs:
5222     return Builtin::BIfabsl;
5223   case Builtin::BIfabsl:
5224     return 0;
5225 
5226   case Builtin::BIcabsf:
5227    return Builtin::BIcabs;
5228   case Builtin::BIcabs:
5229     return Builtin::BIcabsl;
5230   case Builtin::BIcabsl:
5231     return 0;
5232   }
5233 }
5234 
5235 // Returns the argument type of the absolute value function.
5236 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
5237                                              unsigned AbsType) {
5238   if (AbsType == 0)
5239     return QualType();
5240 
5241   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
5242   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
5243   if (Error != ASTContext::GE_None)
5244     return QualType();
5245 
5246   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
5247   if (!FT)
5248     return QualType();
5249 
5250   if (FT->getNumParams() != 1)
5251     return QualType();
5252 
5253   return FT->getParamType(0);
5254 }
5255 
5256 // Returns the best absolute value function, or zero, based on type and
5257 // current absolute value function.
5258 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
5259                                    unsigned AbsFunctionKind) {
5260   unsigned BestKind = 0;
5261   uint64_t ArgSize = Context.getTypeSize(ArgType);
5262   for (unsigned Kind = AbsFunctionKind; Kind != 0;
5263        Kind = getLargerAbsoluteValueFunction(Kind)) {
5264     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
5265     if (Context.getTypeSize(ParamType) >= ArgSize) {
5266       if (BestKind == 0)
5267         BestKind = Kind;
5268       else if (Context.hasSameType(ParamType, ArgType)) {
5269         BestKind = Kind;
5270         break;
5271       }
5272     }
5273   }
5274   return BestKind;
5275 }
5276 
5277 enum AbsoluteValueKind {
5278   AVK_Integer,
5279   AVK_Floating,
5280   AVK_Complex
5281 };
5282 
5283 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
5284   if (T->isIntegralOrEnumerationType())
5285     return AVK_Integer;
5286   if (T->isRealFloatingType())
5287     return AVK_Floating;
5288   if (T->isAnyComplexType())
5289     return AVK_Complex;
5290 
5291   llvm_unreachable("Type not integer, floating, or complex");
5292 }
5293 
5294 // Changes the absolute value function to a different type.  Preserves whether
5295 // the function is a builtin.
5296 static unsigned changeAbsFunction(unsigned AbsKind,
5297                                   AbsoluteValueKind ValueKind) {
5298   switch (ValueKind) {
5299   case AVK_Integer:
5300     switch (AbsKind) {
5301     default:
5302       return 0;
5303     case Builtin::BI__builtin_fabsf:
5304     case Builtin::BI__builtin_fabs:
5305     case Builtin::BI__builtin_fabsl:
5306     case Builtin::BI__builtin_cabsf:
5307     case Builtin::BI__builtin_cabs:
5308     case Builtin::BI__builtin_cabsl:
5309       return Builtin::BI__builtin_abs;
5310     case Builtin::BIfabsf:
5311     case Builtin::BIfabs:
5312     case Builtin::BIfabsl:
5313     case Builtin::BIcabsf:
5314     case Builtin::BIcabs:
5315     case Builtin::BIcabsl:
5316       return Builtin::BIabs;
5317     }
5318   case AVK_Floating:
5319     switch (AbsKind) {
5320     default:
5321       return 0;
5322     case Builtin::BI__builtin_abs:
5323     case Builtin::BI__builtin_labs:
5324     case Builtin::BI__builtin_llabs:
5325     case Builtin::BI__builtin_cabsf:
5326     case Builtin::BI__builtin_cabs:
5327     case Builtin::BI__builtin_cabsl:
5328       return Builtin::BI__builtin_fabsf;
5329     case Builtin::BIabs:
5330     case Builtin::BIlabs:
5331     case Builtin::BIllabs:
5332     case Builtin::BIcabsf:
5333     case Builtin::BIcabs:
5334     case Builtin::BIcabsl:
5335       return Builtin::BIfabsf;
5336     }
5337   case AVK_Complex:
5338     switch (AbsKind) {
5339     default:
5340       return 0;
5341     case Builtin::BI__builtin_abs:
5342     case Builtin::BI__builtin_labs:
5343     case Builtin::BI__builtin_llabs:
5344     case Builtin::BI__builtin_fabsf:
5345     case Builtin::BI__builtin_fabs:
5346     case Builtin::BI__builtin_fabsl:
5347       return Builtin::BI__builtin_cabsf;
5348     case Builtin::BIabs:
5349     case Builtin::BIlabs:
5350     case Builtin::BIllabs:
5351     case Builtin::BIfabsf:
5352     case Builtin::BIfabs:
5353     case Builtin::BIfabsl:
5354       return Builtin::BIcabsf;
5355     }
5356   }
5357   llvm_unreachable("Unable to convert function");
5358 }
5359 
5360 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
5361   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
5362   if (!FnInfo)
5363     return 0;
5364 
5365   switch (FDecl->getBuiltinID()) {
5366   default:
5367     return 0;
5368   case Builtin::BI__builtin_abs:
5369   case Builtin::BI__builtin_fabs:
5370   case Builtin::BI__builtin_fabsf:
5371   case Builtin::BI__builtin_fabsl:
5372   case Builtin::BI__builtin_labs:
5373   case Builtin::BI__builtin_llabs:
5374   case Builtin::BI__builtin_cabs:
5375   case Builtin::BI__builtin_cabsf:
5376   case Builtin::BI__builtin_cabsl:
5377   case Builtin::BIabs:
5378   case Builtin::BIlabs:
5379   case Builtin::BIllabs:
5380   case Builtin::BIfabs:
5381   case Builtin::BIfabsf:
5382   case Builtin::BIfabsl:
5383   case Builtin::BIcabs:
5384   case Builtin::BIcabsf:
5385   case Builtin::BIcabsl:
5386     return FDecl->getBuiltinID();
5387   }
5388   llvm_unreachable("Unknown Builtin type");
5389 }
5390 
5391 // If the replacement is valid, emit a note with replacement function.
5392 // Additionally, suggest including the proper header if not already included.
5393 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
5394                             unsigned AbsKind, QualType ArgType) {
5395   bool EmitHeaderHint = true;
5396   const char *HeaderName = nullptr;
5397   const char *FunctionName = nullptr;
5398   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
5399     FunctionName = "std::abs";
5400     if (ArgType->isIntegralOrEnumerationType()) {
5401       HeaderName = "cstdlib";
5402     } else if (ArgType->isRealFloatingType()) {
5403       HeaderName = "cmath";
5404     } else {
5405       llvm_unreachable("Invalid Type");
5406     }
5407 
5408     // Lookup all std::abs
5409     if (NamespaceDecl *Std = S.getStdNamespace()) {
5410       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
5411       R.suppressDiagnostics();
5412       S.LookupQualifiedName(R, Std);
5413 
5414       for (const auto *I : R) {
5415         const FunctionDecl *FDecl = nullptr;
5416         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
5417           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
5418         } else {
5419           FDecl = dyn_cast<FunctionDecl>(I);
5420         }
5421         if (!FDecl)
5422           continue;
5423 
5424         // Found std::abs(), check that they are the right ones.
5425         if (FDecl->getNumParams() != 1)
5426           continue;
5427 
5428         // Check that the parameter type can handle the argument.
5429         QualType ParamType = FDecl->getParamDecl(0)->getType();
5430         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
5431             S.Context.getTypeSize(ArgType) <=
5432                 S.Context.getTypeSize(ParamType)) {
5433           // Found a function, don't need the header hint.
5434           EmitHeaderHint = false;
5435           break;
5436         }
5437       }
5438     }
5439   } else {
5440     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
5441     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
5442 
5443     if (HeaderName) {
5444       DeclarationName DN(&S.Context.Idents.get(FunctionName));
5445       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
5446       R.suppressDiagnostics();
5447       S.LookupName(R, S.getCurScope());
5448 
5449       if (R.isSingleResult()) {
5450         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
5451         if (FD && FD->getBuiltinID() == AbsKind) {
5452           EmitHeaderHint = false;
5453         } else {
5454           return;
5455         }
5456       } else if (!R.empty()) {
5457         return;
5458       }
5459     }
5460   }
5461 
5462   S.Diag(Loc, diag::note_replace_abs_function)
5463       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
5464 
5465   if (!HeaderName)
5466     return;
5467 
5468   if (!EmitHeaderHint)
5469     return;
5470 
5471   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5472                                                     << FunctionName;
5473 }
5474 
5475 static bool IsFunctionStdAbs(const FunctionDecl *FDecl) {
5476   if (!FDecl)
5477     return false;
5478 
5479   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr("abs"))
5480     return false;
5481 
5482   const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(FDecl->getDeclContext());
5483 
5484   while (ND && ND->isInlineNamespace()) {
5485     ND = dyn_cast<NamespaceDecl>(ND->getDeclContext());
5486   }
5487 
5488   if (!ND || !ND->getIdentifier() || !ND->getIdentifier()->isStr("std"))
5489     return false;
5490 
5491   if (!isa<TranslationUnitDecl>(ND->getDeclContext()))
5492     return false;
5493 
5494   return true;
5495 }
5496 
5497 // Warn when using the wrong abs() function.
5498 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
5499                                       const FunctionDecl *FDecl,
5500                                       IdentifierInfo *FnInfo) {
5501   if (Call->getNumArgs() != 1)
5502     return;
5503 
5504   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
5505   bool IsStdAbs = IsFunctionStdAbs(FDecl);
5506   if (AbsKind == 0 && !IsStdAbs)
5507     return;
5508 
5509   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
5510   QualType ParamType = Call->getArg(0)->getType();
5511 
5512   // Unsigned types cannot be negative.  Suggest removing the absolute value
5513   // function call.
5514   if (ArgType->isUnsignedIntegerType()) {
5515     const char *FunctionName =
5516         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
5517     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5518     Diag(Call->getExprLoc(), diag::note_remove_abs)
5519         << FunctionName
5520         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
5521     return;
5522   }
5523 
5524   // Taking the absolute value of a pointer is very suspicious, they probably
5525   // wanted to index into an array, dereference a pointer, call a function, etc.
5526   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
5527     unsigned DiagType = 0;
5528     if (ArgType->isFunctionType())
5529       DiagType = 1;
5530     else if (ArgType->isArrayType())
5531       DiagType = 2;
5532 
5533     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5534     return;
5535   }
5536 
5537   // std::abs has overloads which prevent most of the absolute value problems
5538   // from occurring.
5539   if (IsStdAbs)
5540     return;
5541 
5542   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
5543   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
5544 
5545   // The argument and parameter are the same kind.  Check if they are the right
5546   // size.
5547   if (ArgValueKind == ParamValueKind) {
5548     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
5549       return;
5550 
5551     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
5552     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
5553         << FDecl << ArgType << ParamType;
5554 
5555     if (NewAbsKind == 0)
5556       return;
5557 
5558     emitReplacement(*this, Call->getExprLoc(),
5559                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5560     return;
5561   }
5562 
5563   // ArgValueKind != ParamValueKind
5564   // The wrong type of absolute value function was used.  Attempt to find the
5565   // proper one.
5566   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
5567   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
5568   if (NewAbsKind == 0)
5569     return;
5570 
5571   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
5572       << FDecl << ParamValueKind << ArgValueKind;
5573 
5574   emitReplacement(*this, Call->getExprLoc(),
5575                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
5576 }
5577 
5578 //===--- CHECK: Standard memory functions ---------------------------------===//
5579 
5580 /// \brief Takes the expression passed to the size_t parameter of functions
5581 /// such as memcmp, strncat, etc and warns if it's a comparison.
5582 ///
5583 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
5584 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
5585                                            IdentifierInfo *FnName,
5586                                            SourceLocation FnLoc,
5587                                            SourceLocation RParenLoc) {
5588   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
5589   if (!Size)
5590     return false;
5591 
5592   // if E is binop and op is >, <, >=, <=, ==, &&, ||:
5593   if (!Size->isComparisonOp() && !Size->isEqualityOp() && !Size->isLogicalOp())
5594     return false;
5595 
5596   SourceRange SizeRange = Size->getSourceRange();
5597   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
5598       << SizeRange << FnName;
5599   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
5600       << FnName << FixItHint::CreateInsertion(
5601                        S.getLocForEndOfToken(Size->getLHS()->getLocEnd()), ")")
5602       << FixItHint::CreateRemoval(RParenLoc);
5603   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
5604       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
5605       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
5606                                     ")");
5607 
5608   return true;
5609 }
5610 
5611 /// \brief Determine whether the given type is or contains a dynamic class type
5612 /// (e.g., whether it has a vtable).
5613 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
5614                                                      bool &IsContained) {
5615   // Look through array types while ignoring qualifiers.
5616   const Type *Ty = T->getBaseElementTypeUnsafe();
5617   IsContained = false;
5618 
5619   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
5620   RD = RD ? RD->getDefinition() : nullptr;
5621   if (!RD || RD->isInvalidDecl())
5622     return nullptr;
5623 
5624   if (RD->isDynamicClass())
5625     return RD;
5626 
5627   // Check all the fields.  If any bases were dynamic, the class is dynamic.
5628   // It's impossible for a class to transitively contain itself by value, so
5629   // infinite recursion is impossible.
5630   for (auto *FD : RD->fields()) {
5631     bool SubContained;
5632     if (const CXXRecordDecl *ContainedRD =
5633             getContainedDynamicClass(FD->getType(), SubContained)) {
5634       IsContained = true;
5635       return ContainedRD;
5636     }
5637   }
5638 
5639   return nullptr;
5640 }
5641 
5642 /// \brief If E is a sizeof expression, returns its argument expression,
5643 /// otherwise returns NULL.
5644 static const Expr *getSizeOfExprArg(const Expr *E) {
5645   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5646       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5647     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
5648       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
5649 
5650   return nullptr;
5651 }
5652 
5653 /// \brief If E is a sizeof expression, returns its argument type.
5654 static QualType getSizeOfArgType(const Expr *E) {
5655   if (const UnaryExprOrTypeTraitExpr *SizeOf =
5656       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5657     if (SizeOf->getKind() == clang::UETT_SizeOf)
5658       return SizeOf->getTypeOfArgument();
5659 
5660   return QualType();
5661 }
5662 
5663 /// \brief Check for dangerous or invalid arguments to memset().
5664 ///
5665 /// This issues warnings on known problematic, dangerous or unspecified
5666 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
5667 /// function calls.
5668 ///
5669 /// \param Call The call expression to diagnose.
5670 void Sema::CheckMemaccessArguments(const CallExpr *Call,
5671                                    unsigned BId,
5672                                    IdentifierInfo *FnName) {
5673   assert(BId != 0);
5674 
5675   // It is possible to have a non-standard definition of memset.  Validate
5676   // we have enough arguments, and if not, abort further checking.
5677   unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5678   if (Call->getNumArgs() < ExpectedNumArgs)
5679     return;
5680 
5681   unsigned LastArg = (BId == Builtin::BImemset ||
5682                       BId == Builtin::BIstrndup ? 1 : 2);
5683   unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5684   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
5685 
5686   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
5687                                      Call->getLocStart(), Call->getRParenLoc()))
5688     return;
5689 
5690   // We have special checking when the length is a sizeof expression.
5691   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
5692   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
5693   llvm::FoldingSetNodeID SizeOfArgID;
5694 
5695   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5696     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
5697     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
5698 
5699     QualType DestTy = Dest->getType();
5700     QualType PointeeTy;
5701     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
5702       PointeeTy = DestPtrTy->getPointeeType();
5703 
5704       // Never warn about void type pointers. This can be used to suppress
5705       // false positives.
5706       if (PointeeTy->isVoidType())
5707         continue;
5708 
5709       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
5710       // actually comparing the expressions for equality. Because computing the
5711       // expression IDs can be expensive, we only do this if the diagnostic is
5712       // enabled.
5713       if (SizeOfArg &&
5714           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5715                            SizeOfArg->getExprLoc())) {
5716         // We only compute IDs for expressions if the warning is enabled, and
5717         // cache the sizeof arg's ID.
5718         if (SizeOfArgID == llvm::FoldingSetNodeID())
5719           SizeOfArg->Profile(SizeOfArgID, Context, true);
5720         llvm::FoldingSetNodeID DestID;
5721         Dest->Profile(DestID, Context, true);
5722         if (DestID == SizeOfArgID) {
5723           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
5724           //       over sizeof(src) as well.
5725           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
5726           StringRef ReadableName = FnName->getName();
5727 
5728           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5729             if (UnaryOp->getOpcode() == UO_AddrOf)
5730               ActionIdx = 1; // If its an address-of operator, just remove it.
5731           if (!PointeeTy->isIncompleteType() &&
5732               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
5733             ActionIdx = 2; // If the pointee's size is sizeof(char),
5734                            // suggest an explicit length.
5735 
5736           // If the function is defined as a builtin macro, do not show macro
5737           // expansion.
5738           SourceLocation SL = SizeOfArg->getExprLoc();
5739           SourceRange DSR = Dest->getSourceRange();
5740           SourceRange SSR = SizeOfArg->getSourceRange();
5741           SourceManager &SM = getSourceManager();
5742 
5743           if (SM.isMacroArgExpansion(SL)) {
5744             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
5745             SL = SM.getSpellingLoc(SL);
5746             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
5747                              SM.getSpellingLoc(DSR.getEnd()));
5748             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
5749                              SM.getSpellingLoc(SSR.getEnd()));
5750           }
5751 
5752           DiagRuntimeBehavior(SL, SizeOfArg,
5753                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5754                                 << ReadableName
5755                                 << PointeeTy
5756                                 << DestTy
5757                                 << DSR
5758                                 << SSR);
5759           DiagRuntimeBehavior(SL, SizeOfArg,
5760                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5761                                 << ActionIdx
5762                                 << SSR);
5763 
5764           break;
5765         }
5766       }
5767 
5768       // Also check for cases where the sizeof argument is the exact same
5769       // type as the memory argument, and where it points to a user-defined
5770       // record type.
5771       if (SizeOfArgTy != QualType()) {
5772         if (PointeeTy->isRecordType() &&
5773             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
5774           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
5775                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
5776                                 << FnName << SizeOfArgTy << ArgIdx
5777                                 << PointeeTy << Dest->getSourceRange()
5778                                 << LenExpr->getSourceRange());
5779           break;
5780         }
5781       }
5782     } else if (DestTy->isArrayType()) {
5783       PointeeTy = DestTy;
5784     }
5785 
5786     if (PointeeTy == QualType())
5787       continue;
5788 
5789     // Always complain about dynamic classes.
5790     bool IsContained;
5791     if (const CXXRecordDecl *ContainedRD =
5792             getContainedDynamicClass(PointeeTy, IsContained)) {
5793 
5794       unsigned OperationType = 0;
5795       // "overwritten" if we're warning about the destination for any call
5796       // but memcmp; otherwise a verb appropriate to the call.
5797       if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5798         if (BId == Builtin::BImemcpy)
5799           OperationType = 1;
5800         else if(BId == Builtin::BImemmove)
5801           OperationType = 2;
5802         else if (BId == Builtin::BImemcmp)
5803           OperationType = 3;
5804       }
5805 
5806       DiagRuntimeBehavior(
5807         Dest->getExprLoc(), Dest,
5808         PDiag(diag::warn_dyn_class_memaccess)
5809           << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5810           << FnName << IsContained << ContainedRD << OperationType
5811           << Call->getCallee()->getSourceRange());
5812     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
5813              BId != Builtin::BImemset)
5814       DiagRuntimeBehavior(
5815         Dest->getExprLoc(), Dest,
5816         PDiag(diag::warn_arc_object_memaccess)
5817           << ArgIdx << FnName << PointeeTy
5818           << Call->getCallee()->getSourceRange());
5819     else
5820       continue;
5821 
5822     DiagRuntimeBehavior(
5823       Dest->getExprLoc(), Dest,
5824       PDiag(diag::note_bad_memaccess_silence)
5825         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
5826     break;
5827   }
5828 }
5829 
5830 // A little helper routine: ignore addition and subtraction of integer literals.
5831 // This intentionally does not ignore all integer constant expressions because
5832 // we don't want to remove sizeof().
5833 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
5834   Ex = Ex->IgnoreParenCasts();
5835 
5836   for (;;) {
5837     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
5838     if (!BO || !BO->isAdditiveOp())
5839       break;
5840 
5841     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
5842     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
5843 
5844     if (isa<IntegerLiteral>(RHS))
5845       Ex = LHS;
5846     else if (isa<IntegerLiteral>(LHS))
5847       Ex = RHS;
5848     else
5849       break;
5850   }
5851 
5852   return Ex;
5853 }
5854 
5855 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
5856                                                       ASTContext &Context) {
5857   // Only handle constant-sized or VLAs, but not flexible members.
5858   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
5859     // Only issue the FIXIT for arrays of size > 1.
5860     if (CAT->getSize().getSExtValue() <= 1)
5861       return false;
5862   } else if (!Ty->isVariableArrayType()) {
5863     return false;
5864   }
5865   return true;
5866 }
5867 
5868 // Warn if the user has made the 'size' argument to strlcpy or strlcat
5869 // be the size of the source, instead of the destination.
5870 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
5871                                     IdentifierInfo *FnName) {
5872 
5873   // Don't crash if the user has the wrong number of arguments
5874   unsigned NumArgs = Call->getNumArgs();
5875   if ((NumArgs != 3) && (NumArgs != 4))
5876     return;
5877 
5878   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
5879   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
5880   const Expr *CompareWithSrc = nullptr;
5881 
5882   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
5883                                      Call->getLocStart(), Call->getRParenLoc()))
5884     return;
5885 
5886   // Look for 'strlcpy(dst, x, sizeof(x))'
5887   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
5888     CompareWithSrc = Ex;
5889   else {
5890     // Look for 'strlcpy(dst, x, strlen(x))'
5891     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5892       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5893           SizeCall->getNumArgs() == 1)
5894         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
5895     }
5896   }
5897 
5898   if (!CompareWithSrc)
5899     return;
5900 
5901   // Determine if the argument to sizeof/strlen is equal to the source
5902   // argument.  In principle there's all kinds of things you could do
5903   // here, for instance creating an == expression and evaluating it with
5904   // EvaluateAsBooleanCondition, but this uses a more direct technique:
5905   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
5906   if (!SrcArgDRE)
5907     return;
5908 
5909   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
5910   if (!CompareWithSrcDRE ||
5911       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
5912     return;
5913 
5914   const Expr *OriginalSizeArg = Call->getArg(2);
5915   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
5916     << OriginalSizeArg->getSourceRange() << FnName;
5917 
5918   // Output a FIXIT hint if the destination is an array (rather than a
5919   // pointer to an array).  This could be enhanced to handle some
5920   // pointers if we know the actual size, like if DstArg is 'array+2'
5921   // we could say 'sizeof(array)-2'.
5922   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
5923   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
5924     return;
5925 
5926   SmallString<128> sizeString;
5927   llvm::raw_svector_ostream OS(sizeString);
5928   OS << "sizeof(";
5929   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
5930   OS << ")";
5931 
5932   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5933     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
5934                                     OS.str());
5935 }
5936 
5937 /// Check if two expressions refer to the same declaration.
5938 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
5939   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5940     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5941       return D1->getDecl() == D2->getDecl();
5942   return false;
5943 }
5944 
5945 static const Expr *getStrlenExprArg(const Expr *E) {
5946   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5947     const FunctionDecl *FD = CE->getDirectCallee();
5948     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
5949       return nullptr;
5950     return CE->getArg(0)->IgnoreParenCasts();
5951   }
5952   return nullptr;
5953 }
5954 
5955 // Warn on anti-patterns as the 'size' argument to strncat.
5956 // The correct size argument should look like following:
5957 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
5958 void Sema::CheckStrncatArguments(const CallExpr *CE,
5959                                  IdentifierInfo *FnName) {
5960   // Don't crash if the user has the wrong number of arguments.
5961   if (CE->getNumArgs() < 3)
5962     return;
5963   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
5964   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
5965   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
5966 
5967   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getLocStart(),
5968                                      CE->getRParenLoc()))
5969     return;
5970 
5971   // Identify common expressions, which are wrongly used as the size argument
5972   // to strncat and may lead to buffer overflows.
5973   unsigned PatternType = 0;
5974   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
5975     // - sizeof(dst)
5976     if (referToTheSameDecl(SizeOfArg, DstArg))
5977       PatternType = 1;
5978     // - sizeof(src)
5979     else if (referToTheSameDecl(SizeOfArg, SrcArg))
5980       PatternType = 2;
5981   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5982     if (BE->getOpcode() == BO_Sub) {
5983       const Expr *L = BE->getLHS()->IgnoreParenCasts();
5984       const Expr *R = BE->getRHS()->IgnoreParenCasts();
5985       // - sizeof(dst) - strlen(dst)
5986       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
5987           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
5988         PatternType = 1;
5989       // - sizeof(src) - (anything)
5990       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
5991         PatternType = 2;
5992     }
5993   }
5994 
5995   if (PatternType == 0)
5996     return;
5997 
5998   // Generate the diagnostic.
5999   SourceLocation SL = LenArg->getLocStart();
6000   SourceRange SR = LenArg->getSourceRange();
6001   SourceManager &SM = getSourceManager();
6002 
6003   // If the function is defined as a builtin macro, do not show macro expansion.
6004   if (SM.isMacroArgExpansion(SL)) {
6005     SL = SM.getSpellingLoc(SL);
6006     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
6007                      SM.getSpellingLoc(SR.getEnd()));
6008   }
6009 
6010   // Check if the destination is an array (rather than a pointer to an array).
6011   QualType DstTy = DstArg->getType();
6012   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
6013                                                                     Context);
6014   if (!isKnownSizeArray) {
6015     if (PatternType == 1)
6016       Diag(SL, diag::warn_strncat_wrong_size) << SR;
6017     else
6018       Diag(SL, diag::warn_strncat_src_size) << SR;
6019     return;
6020   }
6021 
6022   if (PatternType == 1)
6023     Diag(SL, diag::warn_strncat_large_size) << SR;
6024   else
6025     Diag(SL, diag::warn_strncat_src_size) << SR;
6026 
6027   SmallString<128> sizeString;
6028   llvm::raw_svector_ostream OS(sizeString);
6029   OS << "sizeof(";
6030   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6031   OS << ") - ";
6032   OS << "strlen(";
6033   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
6034   OS << ") - 1";
6035 
6036   Diag(SL, diag::note_strncat_wrong_size)
6037     << FixItHint::CreateReplacement(SR, OS.str());
6038 }
6039 
6040 //===--- CHECK: Return Address of Stack Variable --------------------------===//
6041 
6042 static const Expr *EvalVal(const Expr *E,
6043                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6044                            const Decl *ParentDecl);
6045 static const Expr *EvalAddr(const Expr *E,
6046                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6047                             const Decl *ParentDecl);
6048 
6049 /// CheckReturnStackAddr - Check if a return statement returns the address
6050 ///   of a stack variable.
6051 static void
6052 CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType,
6053                      SourceLocation ReturnLoc) {
6054 
6055   const Expr *stackE = nullptr;
6056   SmallVector<const DeclRefExpr *, 8> refVars;
6057 
6058   // Perform checking for returned stack addresses, local blocks,
6059   // label addresses or references to temporaries.
6060   if (lhsType->isPointerType() ||
6061       (!S.getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
6062     stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/nullptr);
6063   } else if (lhsType->isReferenceType()) {
6064     stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/nullptr);
6065   }
6066 
6067   if (!stackE)
6068     return; // Nothing suspicious was found.
6069 
6070   SourceLocation diagLoc;
6071   SourceRange diagRange;
6072   if (refVars.empty()) {
6073     diagLoc = stackE->getLocStart();
6074     diagRange = stackE->getSourceRange();
6075   } else {
6076     // We followed through a reference variable. 'stackE' contains the
6077     // problematic expression but we will warn at the return statement pointing
6078     // at the reference variable. We will later display the "trail" of
6079     // reference variables using notes.
6080     diagLoc = refVars[0]->getLocStart();
6081     diagRange = refVars[0]->getSourceRange();
6082   }
6083 
6084   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
6085     // address of local var
6086     S.Diag(diagLoc, diag::warn_ret_stack_addr_ref) << lhsType->isReferenceType()
6087      << DR->getDecl()->getDeclName() << diagRange;
6088   } else if (isa<BlockExpr>(stackE)) { // local block.
6089     S.Diag(diagLoc, diag::err_ret_local_block) << diagRange;
6090   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
6091     S.Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
6092   } else { // local temporary.
6093     S.Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
6094      << lhsType->isReferenceType() << diagRange;
6095   }
6096 
6097   // Display the "trail" of reference variables that we followed until we
6098   // found the problematic expression using notes.
6099   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
6100     const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
6101     // If this var binds to another reference var, show the range of the next
6102     // var, otherwise the var binds to the problematic expression, in which case
6103     // show the range of the expression.
6104     SourceRange range = (i < e - 1) ? refVars[i + 1]->getSourceRange()
6105                                     : stackE->getSourceRange();
6106     S.Diag(VD->getLocation(), diag::note_ref_var_local_bind)
6107         << VD->getDeclName() << range;
6108   }
6109 }
6110 
6111 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
6112 ///  check if the expression in a return statement evaluates to an address
6113 ///  to a location on the stack, a local block, an address of a label, or a
6114 ///  reference to local temporary. The recursion is used to traverse the
6115 ///  AST of the return expression, with recursion backtracking when we
6116 ///  encounter a subexpression that (1) clearly does not lead to one of the
6117 ///  above problematic expressions (2) is something we cannot determine leads to
6118 ///  a problematic expression based on such local checking.
6119 ///
6120 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
6121 ///  the expression that they point to. Such variables are added to the
6122 ///  'refVars' vector so that we know what the reference variable "trail" was.
6123 ///
6124 ///  EvalAddr processes expressions that are pointers that are used as
6125 ///  references (and not L-values).  EvalVal handles all other values.
6126 ///  At the base case of the recursion is a check for the above problematic
6127 ///  expressions.
6128 ///
6129 ///  This implementation handles:
6130 ///
6131 ///   * pointer-to-pointer casts
6132 ///   * implicit conversions from array references to pointers
6133 ///   * taking the address of fields
6134 ///   * arbitrary interplay between "&" and "*" operators
6135 ///   * pointer arithmetic from an address of a stack variable
6136 ///   * taking the address of an array element where the array is on the stack
6137 static const Expr *EvalAddr(const Expr *E,
6138                             SmallVectorImpl<const DeclRefExpr *> &refVars,
6139                             const Decl *ParentDecl) {
6140   if (E->isTypeDependent())
6141     return nullptr;
6142 
6143   // We should only be called for evaluating pointer expressions.
6144   assert((E->getType()->isAnyPointerType() ||
6145           E->getType()->isBlockPointerType() ||
6146           E->getType()->isObjCQualifiedIdType()) &&
6147          "EvalAddr only works on pointers");
6148 
6149   E = E->IgnoreParens();
6150 
6151   // Our "symbolic interpreter" is just a dispatch off the currently
6152   // viewed AST node.  We then recursively traverse the AST by calling
6153   // EvalAddr and EvalVal appropriately.
6154   switch (E->getStmtClass()) {
6155   case Stmt::DeclRefExprClass: {
6156     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6157 
6158     // If we leave the immediate function, the lifetime isn't about to end.
6159     if (DR->refersToEnclosingVariableOrCapture())
6160       return nullptr;
6161 
6162     if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
6163       // If this is a reference variable, follow through to the expression that
6164       // it points to.
6165       if (V->hasLocalStorage() &&
6166           V->getType()->isReferenceType() && V->hasInit()) {
6167         // Add the reference variable to the "trail".
6168         refVars.push_back(DR);
6169         return EvalAddr(V->getInit(), refVars, ParentDecl);
6170       }
6171 
6172     return nullptr;
6173   }
6174 
6175   case Stmt::UnaryOperatorClass: {
6176     // The only unary operator that make sense to handle here
6177     // is AddrOf.  All others don't make sense as pointers.
6178     const UnaryOperator *U = cast<UnaryOperator>(E);
6179 
6180     if (U->getOpcode() == UO_AddrOf)
6181       return EvalVal(U->getSubExpr(), refVars, ParentDecl);
6182     return nullptr;
6183   }
6184 
6185   case Stmt::BinaryOperatorClass: {
6186     // Handle pointer arithmetic.  All other binary operators are not valid
6187     // in this context.
6188     const BinaryOperator *B = cast<BinaryOperator>(E);
6189     BinaryOperatorKind op = B->getOpcode();
6190 
6191     if (op != BO_Add && op != BO_Sub)
6192       return nullptr;
6193 
6194     const Expr *Base = B->getLHS();
6195 
6196     // Determine which argument is the real pointer base.  It could be
6197     // the RHS argument instead of the LHS.
6198     if (!Base->getType()->isPointerType())
6199       Base = B->getRHS();
6200 
6201     assert(Base->getType()->isPointerType());
6202     return EvalAddr(Base, refVars, ParentDecl);
6203   }
6204 
6205   // For conditional operators we need to see if either the LHS or RHS are
6206   // valid DeclRefExpr*s.  If one of them is valid, we return it.
6207   case Stmt::ConditionalOperatorClass: {
6208     const ConditionalOperator *C = cast<ConditionalOperator>(E);
6209 
6210     // Handle the GNU extension for missing LHS.
6211     // FIXME: That isn't a ConditionalOperator, so doesn't get here.
6212     if (const Expr *LHSExpr = C->getLHS()) {
6213       // In C++, we can have a throw-expression, which has 'void' type.
6214       if (!LHSExpr->getType()->isVoidType())
6215         if (const Expr *LHS = EvalAddr(LHSExpr, refVars, ParentDecl))
6216           return LHS;
6217     }
6218 
6219     // In C++, we can have a throw-expression, which has 'void' type.
6220     if (C->getRHS()->getType()->isVoidType())
6221       return nullptr;
6222 
6223     return EvalAddr(C->getRHS(), refVars, ParentDecl);
6224   }
6225 
6226   case Stmt::BlockExprClass:
6227     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
6228       return E; // local block.
6229     return nullptr;
6230 
6231   case Stmt::AddrLabelExprClass:
6232     return E; // address of label.
6233 
6234   case Stmt::ExprWithCleanupsClass:
6235     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6236                     ParentDecl);
6237 
6238   // For casts, we need to handle conversions from arrays to
6239   // pointer values, and pointer-to-pointer conversions.
6240   case Stmt::ImplicitCastExprClass:
6241   case Stmt::CStyleCastExprClass:
6242   case Stmt::CXXFunctionalCastExprClass:
6243   case Stmt::ObjCBridgedCastExprClass:
6244   case Stmt::CXXStaticCastExprClass:
6245   case Stmt::CXXDynamicCastExprClass:
6246   case Stmt::CXXConstCastExprClass:
6247   case Stmt::CXXReinterpretCastExprClass: {
6248     const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
6249     switch (cast<CastExpr>(E)->getCastKind()) {
6250     case CK_LValueToRValue:
6251     case CK_NoOp:
6252     case CK_BaseToDerived:
6253     case CK_DerivedToBase:
6254     case CK_UncheckedDerivedToBase:
6255     case CK_Dynamic:
6256     case CK_CPointerToObjCPointerCast:
6257     case CK_BlockPointerToObjCPointerCast:
6258     case CK_AnyPointerToBlockPointerCast:
6259       return EvalAddr(SubExpr, refVars, ParentDecl);
6260 
6261     case CK_ArrayToPointerDecay:
6262       return EvalVal(SubExpr, refVars, ParentDecl);
6263 
6264     case CK_BitCast:
6265       if (SubExpr->getType()->isAnyPointerType() ||
6266           SubExpr->getType()->isBlockPointerType() ||
6267           SubExpr->getType()->isObjCQualifiedIdType())
6268         return EvalAddr(SubExpr, refVars, ParentDecl);
6269       else
6270         return nullptr;
6271 
6272     default:
6273       return nullptr;
6274     }
6275   }
6276 
6277   case Stmt::MaterializeTemporaryExprClass:
6278     if (const Expr *Result =
6279             EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6280                      refVars, ParentDecl))
6281       return Result;
6282     return E;
6283 
6284   // Everything else: we simply don't reason about them.
6285   default:
6286     return nullptr;
6287   }
6288 }
6289 
6290 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
6291 ///   See the comments for EvalAddr for more details.
6292 static const Expr *EvalVal(const Expr *E,
6293                            SmallVectorImpl<const DeclRefExpr *> &refVars,
6294                            const Decl *ParentDecl) {
6295   do {
6296     // We should only be called for evaluating non-pointer expressions, or
6297     // expressions with a pointer type that are not used as references but
6298     // instead
6299     // are l-values (e.g., DeclRefExpr with a pointer type).
6300 
6301     // Our "symbolic interpreter" is just a dispatch off the currently
6302     // viewed AST node.  We then recursively traverse the AST by calling
6303     // EvalAddr and EvalVal appropriately.
6304 
6305     E = E->IgnoreParens();
6306     switch (E->getStmtClass()) {
6307     case Stmt::ImplicitCastExprClass: {
6308       const ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
6309       if (IE->getValueKind() == VK_LValue) {
6310         E = IE->getSubExpr();
6311         continue;
6312       }
6313       return nullptr;
6314     }
6315 
6316     case Stmt::ExprWithCleanupsClass:
6317       return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
6318                      ParentDecl);
6319 
6320     case Stmt::DeclRefExprClass: {
6321       // When we hit a DeclRefExpr we are looking at code that refers to a
6322       // variable's name. If it's not a reference variable we check if it has
6323       // local storage within the function, and if so, return the expression.
6324       const DeclRefExpr *DR = cast<DeclRefExpr>(E);
6325 
6326       // If we leave the immediate function, the lifetime isn't about to end.
6327       if (DR->refersToEnclosingVariableOrCapture())
6328         return nullptr;
6329 
6330       if (const VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
6331         // Check if it refers to itself, e.g. "int& i = i;".
6332         if (V == ParentDecl)
6333           return DR;
6334 
6335         if (V->hasLocalStorage()) {
6336           if (!V->getType()->isReferenceType())
6337             return DR;
6338 
6339           // Reference variable, follow through to the expression that
6340           // it points to.
6341           if (V->hasInit()) {
6342             // Add the reference variable to the "trail".
6343             refVars.push_back(DR);
6344             return EvalVal(V->getInit(), refVars, V);
6345           }
6346         }
6347       }
6348 
6349       return nullptr;
6350     }
6351 
6352     case Stmt::UnaryOperatorClass: {
6353       // The only unary operator that make sense to handle here
6354       // is Deref.  All others don't resolve to a "name."  This includes
6355       // handling all sorts of rvalues passed to a unary operator.
6356       const UnaryOperator *U = cast<UnaryOperator>(E);
6357 
6358       if (U->getOpcode() == UO_Deref)
6359         return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
6360 
6361       return nullptr;
6362     }
6363 
6364     case Stmt::ArraySubscriptExprClass: {
6365       // Array subscripts are potential references to data on the stack.  We
6366       // retrieve the DeclRefExpr* for the array variable if it indeed
6367       // has local storage.
6368       const auto *ASE = cast<ArraySubscriptExpr>(E);
6369       if (ASE->isTypeDependent())
6370         return nullptr;
6371       return EvalAddr(ASE->getBase(), refVars, ParentDecl);
6372     }
6373 
6374     case Stmt::OMPArraySectionExprClass: {
6375       return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
6376                       ParentDecl);
6377     }
6378 
6379     case Stmt::ConditionalOperatorClass: {
6380       // For conditional operators we need to see if either the LHS or RHS are
6381       // non-NULL Expr's.  If one is non-NULL, we return it.
6382       const ConditionalOperator *C = cast<ConditionalOperator>(E);
6383 
6384       // Handle the GNU extension for missing LHS.
6385       if (const Expr *LHSExpr = C->getLHS()) {
6386         // In C++, we can have a throw-expression, which has 'void' type.
6387         if (!LHSExpr->getType()->isVoidType())
6388           if (const Expr *LHS = EvalVal(LHSExpr, refVars, ParentDecl))
6389             return LHS;
6390       }
6391 
6392       // In C++, we can have a throw-expression, which has 'void' type.
6393       if (C->getRHS()->getType()->isVoidType())
6394         return nullptr;
6395 
6396       return EvalVal(C->getRHS(), refVars, ParentDecl);
6397     }
6398 
6399     // Accesses to members are potential references to data on the stack.
6400     case Stmt::MemberExprClass: {
6401       const MemberExpr *M = cast<MemberExpr>(E);
6402 
6403       // Check for indirect access.  We only want direct field accesses.
6404       if (M->isArrow())
6405         return nullptr;
6406 
6407       // Check whether the member type is itself a reference, in which case
6408       // we're not going to refer to the member, but to what the member refers
6409       // to.
6410       if (M->getMemberDecl()->getType()->isReferenceType())
6411         return nullptr;
6412 
6413       return EvalVal(M->getBase(), refVars, ParentDecl);
6414     }
6415 
6416     case Stmt::MaterializeTemporaryExprClass:
6417       if (const Expr *Result =
6418               EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
6419                       refVars, ParentDecl))
6420         return Result;
6421       return E;
6422 
6423     default:
6424       // Check that we don't return or take the address of a reference to a
6425       // temporary. This is only useful in C++.
6426       if (!E->isTypeDependent() && E->isRValue())
6427         return E;
6428 
6429       // Everything else: we simply don't reason about them.
6430       return nullptr;
6431     }
6432   } while (true);
6433 }
6434 
6435 void
6436 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
6437                          SourceLocation ReturnLoc,
6438                          bool isObjCMethod,
6439                          const AttrVec *Attrs,
6440                          const FunctionDecl *FD) {
6441   CheckReturnStackAddr(*this, RetValExp, lhsType, ReturnLoc);
6442 
6443   // Check if the return value is null but should not be.
6444   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6445        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
6446       CheckNonNullExpr(*this, RetValExp))
6447     Diag(ReturnLoc, diag::warn_null_ret)
6448       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6449 
6450   // C++11 [basic.stc.dynamic.allocation]p4:
6451   //   If an allocation function declared with a non-throwing
6452   //   exception-specification fails to allocate storage, it shall return
6453   //   a null pointer. Any other allocation function that fails to allocate
6454   //   storage shall indicate failure only by throwing an exception [...]
6455   if (FD) {
6456     OverloadedOperatorKind Op = FD->getOverloadedOperator();
6457     if (Op == OO_New || Op == OO_Array_New) {
6458       const FunctionProtoType *Proto
6459         = FD->getType()->castAs<FunctionProtoType>();
6460       if (!Proto->isNothrow(Context, /*ResultIfDependent*/true) &&
6461           CheckNonNullExpr(*this, RetValExp))
6462         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6463           << FD << getLangOpts().CPlusPlus11;
6464     }
6465   }
6466 }
6467 
6468 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
6469 
6470 /// Check for comparisons of floating point operands using != and ==.
6471 /// Issue a warning if these are no self-comparisons, as they are not likely
6472 /// to do what the programmer intended.
6473 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
6474   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
6475   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
6476 
6477   // Special case: check for x == x (which is OK).
6478   // Do not emit warnings for such cases.
6479   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6480     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6481       if (DRL->getDecl() == DRR->getDecl())
6482         return;
6483 
6484   // Special case: check for comparisons against literals that can be exactly
6485   //  represented by APFloat.  In such cases, do not emit a warning.  This
6486   //  is a heuristic: often comparison against such literals are used to
6487   //  detect if a value in a variable has not changed.  This clearly can
6488   //  lead to false negatives.
6489   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6490     if (FLL->isExact())
6491       return;
6492   } else
6493     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6494       if (FLR->isExact())
6495         return;
6496 
6497   // Check for comparisons with builtin types.
6498   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6499     if (CL->getBuiltinCallee())
6500       return;
6501 
6502   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6503     if (CR->getBuiltinCallee())
6504       return;
6505 
6506   // Emit the diagnostic.
6507   Diag(Loc, diag::warn_floatingpoint_eq)
6508     << LHS->getSourceRange() << RHS->getSourceRange();
6509 }
6510 
6511 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
6512 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
6513 
6514 namespace {
6515 
6516 /// Structure recording the 'active' range of an integer-valued
6517 /// expression.
6518 struct IntRange {
6519   /// The number of bits active in the int.
6520   unsigned Width;
6521 
6522   /// True if the int is known not to have negative values.
6523   bool NonNegative;
6524 
6525   IntRange(unsigned Width, bool NonNegative)
6526     : Width(Width), NonNegative(NonNegative)
6527   {}
6528 
6529   /// Returns the range of the bool type.
6530   static IntRange forBoolType() {
6531     return IntRange(1, true);
6532   }
6533 
6534   /// Returns the range of an opaque value of the given integral type.
6535   static IntRange forValueOfType(ASTContext &C, QualType T) {
6536     return forValueOfCanonicalType(C,
6537                           T->getCanonicalTypeInternal().getTypePtr());
6538   }
6539 
6540   /// Returns the range of an opaque value of a canonical integral type.
6541   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
6542     assert(T->isCanonicalUnqualified());
6543 
6544     if (const VectorType *VT = dyn_cast<VectorType>(T))
6545       T = VT->getElementType().getTypePtr();
6546     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6547       T = CT->getElementType().getTypePtr();
6548     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6549       T = AT->getValueType().getTypePtr();
6550 
6551     // For enum types, use the known bit width of the enumerators.
6552     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
6553       EnumDecl *Enum = ET->getDecl();
6554       if (!Enum->isCompleteDefinition())
6555         return IntRange(C.getIntWidth(QualType(T, 0)), false);
6556 
6557       unsigned NumPositive = Enum->getNumPositiveBits();
6558       unsigned NumNegative = Enum->getNumNegativeBits();
6559 
6560       if (NumNegative == 0)
6561         return IntRange(NumPositive, true/*NonNegative*/);
6562       else
6563         return IntRange(std::max(NumPositive + 1, NumNegative),
6564                         false/*NonNegative*/);
6565     }
6566 
6567     const BuiltinType *BT = cast<BuiltinType>(T);
6568     assert(BT->isInteger());
6569 
6570     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6571   }
6572 
6573   /// Returns the "target" range of a canonical integral type, i.e.
6574   /// the range of values expressible in the type.
6575   ///
6576   /// This matches forValueOfCanonicalType except that enums have the
6577   /// full range of their type, not the range of their enumerators.
6578   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
6579     assert(T->isCanonicalUnqualified());
6580 
6581     if (const VectorType *VT = dyn_cast<VectorType>(T))
6582       T = VT->getElementType().getTypePtr();
6583     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
6584       T = CT->getElementType().getTypePtr();
6585     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
6586       T = AT->getValueType().getTypePtr();
6587     if (const EnumType *ET = dyn_cast<EnumType>(T))
6588       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
6589 
6590     const BuiltinType *BT = cast<BuiltinType>(T);
6591     assert(BT->isInteger());
6592 
6593     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
6594   }
6595 
6596   /// Returns the supremum of two ranges: i.e. their conservative merge.
6597   static IntRange join(IntRange L, IntRange R) {
6598     return IntRange(std::max(L.Width, R.Width),
6599                     L.NonNegative && R.NonNegative);
6600   }
6601 
6602   /// Returns the infinum of two ranges: i.e. their aggressive merge.
6603   static IntRange meet(IntRange L, IntRange R) {
6604     return IntRange(std::min(L.Width, R.Width),
6605                     L.NonNegative || R.NonNegative);
6606   }
6607 };
6608 
6609 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
6610   if (value.isSigned() && value.isNegative())
6611     return IntRange(value.getMinSignedBits(), false);
6612 
6613   if (value.getBitWidth() > MaxWidth)
6614     value = value.trunc(MaxWidth);
6615 
6616   // isNonNegative() just checks the sign bit without considering
6617   // signedness.
6618   return IntRange(value.getActiveBits(), true);
6619 }
6620 
6621 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
6622                        unsigned MaxWidth) {
6623   if (result.isInt())
6624     return GetValueRange(C, result.getInt(), MaxWidth);
6625 
6626   if (result.isVector()) {
6627     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
6628     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
6629       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
6630       R = IntRange::join(R, El);
6631     }
6632     return R;
6633   }
6634 
6635   if (result.isComplexInt()) {
6636     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
6637     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
6638     return IntRange::join(R, I);
6639   }
6640 
6641   // This can happen with lossless casts to intptr_t of "based" lvalues.
6642   // Assume it might use arbitrary bits.
6643   // FIXME: The only reason we need to pass the type in here is to get
6644   // the sign right on this one case.  It would be nice if APValue
6645   // preserved this.
6646   assert(result.isLValue() || result.isAddrLabelDiff());
6647   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
6648 }
6649 
6650 QualType GetExprType(const Expr *E) {
6651   QualType Ty = E->getType();
6652   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
6653     Ty = AtomicRHS->getValueType();
6654   return Ty;
6655 }
6656 
6657 /// Pseudo-evaluate the given integer expression, estimating the
6658 /// range of values it might take.
6659 ///
6660 /// \param MaxWidth - the width to which the value will be truncated
6661 IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth) {
6662   E = E->IgnoreParens();
6663 
6664   // Try a full evaluation first.
6665   Expr::EvalResult result;
6666   if (E->EvaluateAsRValue(result, C))
6667     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
6668 
6669   // I think we only want to look through implicit casts here; if the
6670   // user has an explicit widening cast, we should treat the value as
6671   // being of the new, wider type.
6672   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
6673     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
6674       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6675 
6676     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6677 
6678     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
6679                          CE->getCastKind() == CK_BooleanToSignedIntegral;
6680 
6681     // Assume that non-integer casts can span the full range of the type.
6682     if (!isIntegerCast)
6683       return OutputTypeRange;
6684 
6685     IntRange SubRange
6686       = GetExprRange(C, CE->getSubExpr(),
6687                      std::min(MaxWidth, OutputTypeRange.Width));
6688 
6689     // Bail out if the subexpr's range is as wide as the cast type.
6690     if (SubRange.Width >= OutputTypeRange.Width)
6691       return OutputTypeRange;
6692 
6693     // Otherwise, we take the smaller width, and we're non-negative if
6694     // either the output type or the subexpr is.
6695     return IntRange(SubRange.Width,
6696                     SubRange.NonNegative || OutputTypeRange.NonNegative);
6697   }
6698 
6699   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
6700     // If we can fold the condition, just take that operand.
6701     bool CondResult;
6702     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6703       return GetExprRange(C, CondResult ? CO->getTrueExpr()
6704                                         : CO->getFalseExpr(),
6705                           MaxWidth);
6706 
6707     // Otherwise, conservatively merge.
6708     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6709     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6710     return IntRange::join(L, R);
6711   }
6712 
6713   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
6714     switch (BO->getOpcode()) {
6715 
6716     // Boolean-valued operations are single-bit and positive.
6717     case BO_LAnd:
6718     case BO_LOr:
6719     case BO_LT:
6720     case BO_GT:
6721     case BO_LE:
6722     case BO_GE:
6723     case BO_EQ:
6724     case BO_NE:
6725       return IntRange::forBoolType();
6726 
6727     // The type of the assignments is the type of the LHS, so the RHS
6728     // is not necessarily the same type.
6729     case BO_MulAssign:
6730     case BO_DivAssign:
6731     case BO_RemAssign:
6732     case BO_AddAssign:
6733     case BO_SubAssign:
6734     case BO_XorAssign:
6735     case BO_OrAssign:
6736       // TODO: bitfields?
6737       return IntRange::forValueOfType(C, GetExprType(E));
6738 
6739     // Simple assignments just pass through the RHS, which will have
6740     // been coerced to the LHS type.
6741     case BO_Assign:
6742       // TODO: bitfields?
6743       return GetExprRange(C, BO->getRHS(), MaxWidth);
6744 
6745     // Operations with opaque sources are black-listed.
6746     case BO_PtrMemD:
6747     case BO_PtrMemI:
6748       return IntRange::forValueOfType(C, GetExprType(E));
6749 
6750     // Bitwise-and uses the *infinum* of the two source ranges.
6751     case BO_And:
6752     case BO_AndAssign:
6753       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6754                             GetExprRange(C, BO->getRHS(), MaxWidth));
6755 
6756     // Left shift gets black-listed based on a judgement call.
6757     case BO_Shl:
6758       // ...except that we want to treat '1 << (blah)' as logically
6759       // positive.  It's an important idiom.
6760       if (IntegerLiteral *I
6761             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6762         if (I->getValue() == 1) {
6763           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6764           return IntRange(R.Width, /*NonNegative*/ true);
6765         }
6766       }
6767       // fallthrough
6768 
6769     case BO_ShlAssign:
6770       return IntRange::forValueOfType(C, GetExprType(E));
6771 
6772     // Right shift by a constant can narrow its left argument.
6773     case BO_Shr:
6774     case BO_ShrAssign: {
6775       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6776 
6777       // If the shift amount is a positive constant, drop the width by
6778       // that much.
6779       llvm::APSInt shift;
6780       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6781           shift.isNonNegative()) {
6782         unsigned zext = shift.getZExtValue();
6783         if (zext >= L.Width)
6784           L.Width = (L.NonNegative ? 0 : 1);
6785         else
6786           L.Width -= zext;
6787       }
6788 
6789       return L;
6790     }
6791 
6792     // Comma acts as its right operand.
6793     case BO_Comma:
6794       return GetExprRange(C, BO->getRHS(), MaxWidth);
6795 
6796     // Black-list pointer subtractions.
6797     case BO_Sub:
6798       if (BO->getLHS()->getType()->isPointerType())
6799         return IntRange::forValueOfType(C, GetExprType(E));
6800       break;
6801 
6802     // The width of a division result is mostly determined by the size
6803     // of the LHS.
6804     case BO_Div: {
6805       // Don't 'pre-truncate' the operands.
6806       unsigned opWidth = C.getIntWidth(GetExprType(E));
6807       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6808 
6809       // If the divisor is constant, use that.
6810       llvm::APSInt divisor;
6811       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6812         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
6813         if (log2 >= L.Width)
6814           L.Width = (L.NonNegative ? 0 : 1);
6815         else
6816           L.Width = std::min(L.Width - log2, MaxWidth);
6817         return L;
6818       }
6819 
6820       // Otherwise, just use the LHS's width.
6821       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6822       return IntRange(L.Width, L.NonNegative && R.NonNegative);
6823     }
6824 
6825     // The result of a remainder can't be larger than the result of
6826     // either side.
6827     case BO_Rem: {
6828       // Don't 'pre-truncate' the operands.
6829       unsigned opWidth = C.getIntWidth(GetExprType(E));
6830       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6831       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6832 
6833       IntRange meet = IntRange::meet(L, R);
6834       meet.Width = std::min(meet.Width, MaxWidth);
6835       return meet;
6836     }
6837 
6838     // The default behavior is okay for these.
6839     case BO_Mul:
6840     case BO_Add:
6841     case BO_Xor:
6842     case BO_Or:
6843       break;
6844     }
6845 
6846     // The default case is to treat the operation as if it were closed
6847     // on the narrowest type that encompasses both operands.
6848     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6849     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6850     return IntRange::join(L, R);
6851   }
6852 
6853   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
6854     switch (UO->getOpcode()) {
6855     // Boolean-valued operations are white-listed.
6856     case UO_LNot:
6857       return IntRange::forBoolType();
6858 
6859     // Operations with opaque sources are black-listed.
6860     case UO_Deref:
6861     case UO_AddrOf: // should be impossible
6862       return IntRange::forValueOfType(C, GetExprType(E));
6863 
6864     default:
6865       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6866     }
6867   }
6868 
6869   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
6870     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6871 
6872   if (const auto *BitField = E->getSourceBitField())
6873     return IntRange(BitField->getBitWidthValue(C),
6874                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
6875 
6876   return IntRange::forValueOfType(C, GetExprType(E));
6877 }
6878 
6879 IntRange GetExprRange(ASTContext &C, const Expr *E) {
6880   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
6881 }
6882 
6883 /// Checks whether the given value, which currently has the given
6884 /// source semantics, has the same value when coerced through the
6885 /// target semantics.
6886 bool IsSameFloatAfterCast(const llvm::APFloat &value,
6887                           const llvm::fltSemantics &Src,
6888                           const llvm::fltSemantics &Tgt) {
6889   llvm::APFloat truncated = value;
6890 
6891   bool ignored;
6892   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6893   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6894 
6895   return truncated.bitwiseIsEqual(value);
6896 }
6897 
6898 /// Checks whether the given value, which currently has the given
6899 /// source semantics, has the same value when coerced through the
6900 /// target semantics.
6901 ///
6902 /// The value might be a vector of floats (or a complex number).
6903 bool IsSameFloatAfterCast(const APValue &value,
6904                           const llvm::fltSemantics &Src,
6905                           const llvm::fltSemantics &Tgt) {
6906   if (value.isFloat())
6907     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
6908 
6909   if (value.isVector()) {
6910     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
6911       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
6912         return false;
6913     return true;
6914   }
6915 
6916   assert(value.isComplexFloat());
6917   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
6918           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
6919 }
6920 
6921 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
6922 
6923 bool IsZero(Sema &S, Expr *E) {
6924   // Suppress cases where we are comparing against an enum constant.
6925   if (const DeclRefExpr *DR =
6926       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
6927     if (isa<EnumConstantDecl>(DR->getDecl()))
6928       return false;
6929 
6930   // Suppress cases where the '0' value is expanded from a macro.
6931   if (E->getLocStart().isMacroID())
6932     return false;
6933 
6934   llvm::APSInt Value;
6935   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
6936 }
6937 
6938 bool HasEnumType(Expr *E) {
6939   // Strip off implicit integral promotions.
6940   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6941     if (ICE->getCastKind() != CK_IntegralCast &&
6942         ICE->getCastKind() != CK_NoOp)
6943       break;
6944     E = ICE->getSubExpr();
6945   }
6946 
6947   return E->getType()->isEnumeralType();
6948 }
6949 
6950 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
6951   // Disable warning in template instantiations.
6952   if (!S.ActiveTemplateInstantiations.empty())
6953     return;
6954 
6955   BinaryOperatorKind op = E->getOpcode();
6956   if (E->isValueDependent())
6957     return;
6958 
6959   if (op == BO_LT && IsZero(S, E->getRHS())) {
6960     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6961       << "< 0" << "false" << HasEnumType(E->getLHS())
6962       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6963   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
6964     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
6965       << ">= 0" << "true" << HasEnumType(E->getLHS())
6966       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6967   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
6968     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6969       << "0 >" << "false" << HasEnumType(E->getRHS())
6970       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6971   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
6972     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
6973       << "0 <=" << "true" << HasEnumType(E->getRHS())
6974       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
6975   }
6976 }
6977 
6978 void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
6979                                   Expr *Constant, Expr *Other,
6980                                   llvm::APSInt Value,
6981                                   bool RhsConstant) {
6982   // Disable warning in template instantiations.
6983   if (!S.ActiveTemplateInstantiations.empty())
6984     return;
6985 
6986   // TODO: Investigate using GetExprRange() to get tighter bounds
6987   // on the bit ranges.
6988   QualType OtherT = Other->getType();
6989   if (const auto *AT = OtherT->getAs<AtomicType>())
6990     OtherT = AT->getValueType();
6991   IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
6992   unsigned OtherWidth = OtherRange.Width;
6993 
6994   bool OtherIsBooleanType = Other->isKnownToHaveBooleanValue();
6995 
6996   // 0 values are handled later by CheckTrivialUnsignedComparison().
6997   if ((Value == 0) && (!OtherIsBooleanType))
6998     return;
6999 
7000   BinaryOperatorKind op = E->getOpcode();
7001   bool IsTrue = true;
7002 
7003   // Used for diagnostic printout.
7004   enum {
7005     LiteralConstant = 0,
7006     CXXBoolLiteralTrue,
7007     CXXBoolLiteralFalse
7008   } LiteralOrBoolConstant = LiteralConstant;
7009 
7010   if (!OtherIsBooleanType) {
7011     QualType ConstantT = Constant->getType();
7012     QualType CommonT = E->getLHS()->getType();
7013 
7014     if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
7015       return;
7016     assert((OtherT->isIntegerType() && ConstantT->isIntegerType()) &&
7017            "comparison with non-integer type");
7018 
7019     bool ConstantSigned = ConstantT->isSignedIntegerType();
7020     bool CommonSigned = CommonT->isSignedIntegerType();
7021 
7022     bool EqualityOnly = false;
7023 
7024     if (CommonSigned) {
7025       // The common type is signed, therefore no signed to unsigned conversion.
7026       if (!OtherRange.NonNegative) {
7027         // Check that the constant is representable in type OtherT.
7028         if (ConstantSigned) {
7029           if (OtherWidth >= Value.getMinSignedBits())
7030             return;
7031         } else { // !ConstantSigned
7032           if (OtherWidth >= Value.getActiveBits() + 1)
7033             return;
7034         }
7035       } else { // !OtherSigned
7036                // Check that the constant is representable in type OtherT.
7037         // Negative values are out of range.
7038         if (ConstantSigned) {
7039           if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
7040             return;
7041         } else { // !ConstantSigned
7042           if (OtherWidth >= Value.getActiveBits())
7043             return;
7044         }
7045       }
7046     } else { // !CommonSigned
7047       if (OtherRange.NonNegative) {
7048         if (OtherWidth >= Value.getActiveBits())
7049           return;
7050       } else { // OtherSigned
7051         assert(!ConstantSigned &&
7052                "Two signed types converted to unsigned types.");
7053         // Check to see if the constant is representable in OtherT.
7054         if (OtherWidth > Value.getActiveBits())
7055           return;
7056         // Check to see if the constant is equivalent to a negative value
7057         // cast to CommonT.
7058         if (S.Context.getIntWidth(ConstantT) ==
7059                 S.Context.getIntWidth(CommonT) &&
7060             Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
7061           return;
7062         // The constant value rests between values that OtherT can represent
7063         // after conversion.  Relational comparison still works, but equality
7064         // comparisons will be tautological.
7065         EqualityOnly = true;
7066       }
7067     }
7068 
7069     bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
7070 
7071     if (op == BO_EQ || op == BO_NE) {
7072       IsTrue = op == BO_NE;
7073     } else if (EqualityOnly) {
7074       return;
7075     } else if (RhsConstant) {
7076       if (op == BO_GT || op == BO_GE)
7077         IsTrue = !PositiveConstant;
7078       else // op == BO_LT || op == BO_LE
7079         IsTrue = PositiveConstant;
7080     } else {
7081       if (op == BO_LT || op == BO_LE)
7082         IsTrue = !PositiveConstant;
7083       else // op == BO_GT || op == BO_GE
7084         IsTrue = PositiveConstant;
7085     }
7086   } else {
7087     // Other isKnownToHaveBooleanValue
7088     enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
7089     enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
7090     enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
7091 
7092     static const struct LinkedConditions {
7093       CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
7094       CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
7095       CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
7096       CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
7097       CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
7098       CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
7099 
7100     } TruthTable = {
7101         // Constant on LHS.              | Constant on RHS.              |
7102         // LT_Zero| Zero  | One   |GT_One| LT_Zero| Zero  | One   |GT_One|
7103         { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
7104         { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
7105         { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
7106         { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
7107         { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
7108         { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
7109       };
7110 
7111     bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
7112 
7113     enum ConstantValue ConstVal = Zero;
7114     if (Value.isUnsigned() || Value.isNonNegative()) {
7115       if (Value == 0) {
7116         LiteralOrBoolConstant =
7117             ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
7118         ConstVal = Zero;
7119       } else if (Value == 1) {
7120         LiteralOrBoolConstant =
7121             ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
7122         ConstVal = One;
7123       } else {
7124         LiteralOrBoolConstant = LiteralConstant;
7125         ConstVal = GT_One;
7126       }
7127     } else {
7128       ConstVal = LT_Zero;
7129     }
7130 
7131     CompareBoolWithConstantResult CmpRes;
7132 
7133     switch (op) {
7134     case BO_LT:
7135       CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
7136       break;
7137     case BO_GT:
7138       CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
7139       break;
7140     case BO_LE:
7141       CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
7142       break;
7143     case BO_GE:
7144       CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
7145       break;
7146     case BO_EQ:
7147       CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
7148       break;
7149     case BO_NE:
7150       CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
7151       break;
7152     default:
7153       CmpRes = Unkwn;
7154       break;
7155     }
7156 
7157     if (CmpRes == AFals) {
7158       IsTrue = false;
7159     } else if (CmpRes == ATrue) {
7160       IsTrue = true;
7161     } else {
7162       return;
7163     }
7164   }
7165 
7166   // If this is a comparison to an enum constant, include that
7167   // constant in the diagnostic.
7168   const EnumConstantDecl *ED = nullptr;
7169   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
7170     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
7171 
7172   SmallString<64> PrettySourceValue;
7173   llvm::raw_svector_ostream OS(PrettySourceValue);
7174   if (ED)
7175     OS << '\'' << *ED << "' (" << Value << ")";
7176   else
7177     OS << Value;
7178 
7179   S.DiagRuntimeBehavior(
7180     E->getOperatorLoc(), E,
7181     S.PDiag(diag::warn_out_of_range_compare)
7182         << OS.str() << LiteralOrBoolConstant
7183         << OtherT << (OtherIsBooleanType && !OtherT->isBooleanType()) << IsTrue
7184         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
7185 }
7186 
7187 /// Analyze the operands of the given comparison.  Implements the
7188 /// fallback case from AnalyzeComparison.
7189 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
7190   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7191   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7192 }
7193 
7194 /// \brief Implements -Wsign-compare.
7195 ///
7196 /// \param E the binary operator to check for warnings
7197 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
7198   // The type the comparison is being performed in.
7199   QualType T = E->getLHS()->getType();
7200 
7201   // Only analyze comparison operators where both sides have been converted to
7202   // the same type.
7203   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
7204     return AnalyzeImpConvsInComparison(S, E);
7205 
7206   // Don't analyze value-dependent comparisons directly.
7207   if (E->isValueDependent())
7208     return AnalyzeImpConvsInComparison(S, E);
7209 
7210   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
7211   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
7212 
7213   bool IsComparisonConstant = false;
7214 
7215   // Check whether an integer constant comparison results in a value
7216   // of 'true' or 'false'.
7217   if (T->isIntegralType(S.Context)) {
7218     llvm::APSInt RHSValue;
7219     bool IsRHSIntegralLiteral =
7220       RHS->isIntegerConstantExpr(RHSValue, S.Context);
7221     llvm::APSInt LHSValue;
7222     bool IsLHSIntegralLiteral =
7223       LHS->isIntegerConstantExpr(LHSValue, S.Context);
7224     if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
7225         DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
7226     else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
7227       DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
7228     else
7229       IsComparisonConstant =
7230         (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
7231   } else if (!T->hasUnsignedIntegerRepresentation())
7232       IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
7233 
7234   // We don't do anything special if this isn't an unsigned integral
7235   // comparison:  we're only interested in integral comparisons, and
7236   // signed comparisons only happen in cases we don't care to warn about.
7237   //
7238   // We also don't care about value-dependent expressions or expressions
7239   // whose result is a constant.
7240   if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
7241     return AnalyzeImpConvsInComparison(S, E);
7242 
7243   // Check to see if one of the (unmodified) operands is of different
7244   // signedness.
7245   Expr *signedOperand, *unsignedOperand;
7246   if (LHS->getType()->hasSignedIntegerRepresentation()) {
7247     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
7248            "unsigned comparison between two signed integer expressions?");
7249     signedOperand = LHS;
7250     unsignedOperand = RHS;
7251   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
7252     signedOperand = RHS;
7253     unsignedOperand = LHS;
7254   } else {
7255     CheckTrivialUnsignedComparison(S, E);
7256     return AnalyzeImpConvsInComparison(S, E);
7257   }
7258 
7259   // Otherwise, calculate the effective range of the signed operand.
7260   IntRange signedRange = GetExprRange(S.Context, signedOperand);
7261 
7262   // Go ahead and analyze implicit conversions in the operands.  Note
7263   // that we skip the implicit conversions on both sides.
7264   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
7265   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
7266 
7267   // If the signed range is non-negative, -Wsign-compare won't fire,
7268   // but we should still check for comparisons which are always true
7269   // or false.
7270   if (signedRange.NonNegative)
7271     return CheckTrivialUnsignedComparison(S, E);
7272 
7273   // For (in)equality comparisons, if the unsigned operand is a
7274   // constant which cannot collide with a overflowed signed operand,
7275   // then reinterpreting the signed operand as unsigned will not
7276   // change the result of the comparison.
7277   if (E->isEqualityOp()) {
7278     unsigned comparisonWidth = S.Context.getIntWidth(T);
7279     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
7280 
7281     // We should never be unable to prove that the unsigned operand is
7282     // non-negative.
7283     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
7284 
7285     if (unsignedRange.Width < comparisonWidth)
7286       return;
7287   }
7288 
7289   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
7290     S.PDiag(diag::warn_mixed_sign_comparison)
7291       << LHS->getType() << RHS->getType()
7292       << LHS->getSourceRange() << RHS->getSourceRange());
7293 }
7294 
7295 /// Analyzes an attempt to assign the given value to a bitfield.
7296 ///
7297 /// Returns true if there was something fishy about the attempt.
7298 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
7299                                SourceLocation InitLoc) {
7300   assert(Bitfield->isBitField());
7301   if (Bitfield->isInvalidDecl())
7302     return false;
7303 
7304   // White-list bool bitfields.
7305   if (Bitfield->getType()->isBooleanType())
7306     return false;
7307 
7308   // Ignore value- or type-dependent expressions.
7309   if (Bitfield->getBitWidth()->isValueDependent() ||
7310       Bitfield->getBitWidth()->isTypeDependent() ||
7311       Init->isValueDependent() ||
7312       Init->isTypeDependent())
7313     return false;
7314 
7315   Expr *OriginalInit = Init->IgnoreParenImpCasts();
7316 
7317   llvm::APSInt Value;
7318   if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
7319     return false;
7320 
7321   unsigned OriginalWidth = Value.getBitWidth();
7322   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
7323 
7324   if (OriginalWidth <= FieldWidth)
7325     return false;
7326 
7327   // Compute the value which the bitfield will contain.
7328   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
7329   TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
7330 
7331   // Check whether the stored value is equal to the original value.
7332   TruncatedValue = TruncatedValue.extend(OriginalWidth);
7333   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
7334     return false;
7335 
7336   // Special-case bitfields of width 1: booleans are naturally 0/1, and
7337   // therefore don't strictly fit into a signed bitfield of width 1.
7338   if (FieldWidth == 1 && Value == 1)
7339     return false;
7340 
7341   std::string PrettyValue = Value.toString(10);
7342   std::string PrettyTrunc = TruncatedValue.toString(10);
7343 
7344   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
7345     << PrettyValue << PrettyTrunc << OriginalInit->getType()
7346     << Init->getSourceRange();
7347 
7348   return true;
7349 }
7350 
7351 /// Analyze the given simple or compound assignment for warning-worthy
7352 /// operations.
7353 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
7354   // Just recurse on the LHS.
7355   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
7356 
7357   // We want to recurse on the RHS as normal unless we're assigning to
7358   // a bitfield.
7359   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
7360     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
7361                                   E->getOperatorLoc())) {
7362       // Recurse, ignoring any implicit conversions on the RHS.
7363       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
7364                                         E->getOperatorLoc());
7365     }
7366   }
7367 
7368   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
7369 }
7370 
7371 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
7372 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
7373                      SourceLocation CContext, unsigned diag,
7374                      bool pruneControlFlow = false) {
7375   if (pruneControlFlow) {
7376     S.DiagRuntimeBehavior(E->getExprLoc(), E,
7377                           S.PDiag(diag)
7378                             << SourceType << T << E->getSourceRange()
7379                             << SourceRange(CContext));
7380     return;
7381   }
7382   S.Diag(E->getExprLoc(), diag)
7383     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
7384 }
7385 
7386 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
7387 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
7388                      unsigned diag, bool pruneControlFlow = false) {
7389   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
7390 }
7391 
7392 
7393 /// Diagnose an implicit cast from a floating point value to an integer value.
7394 void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
7395 
7396                              SourceLocation CContext) {
7397   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
7398   const bool PruneWarnings = !S.ActiveTemplateInstantiations.empty();
7399 
7400   Expr *InnerE = E->IgnoreParenImpCasts();
7401   // We also want to warn on, e.g., "int i = -1.234"
7402   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
7403     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
7404       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
7405 
7406   const bool IsLiteral =
7407       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
7408 
7409   llvm::APFloat Value(0.0);
7410   bool IsConstant =
7411     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
7412   if (!IsConstant) {
7413     return DiagnoseImpCast(S, E, T, CContext,
7414                            diag::warn_impcast_float_integer, PruneWarnings);
7415   }
7416 
7417   bool isExact = false;
7418 
7419   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
7420                             T->hasUnsignedIntegerRepresentation());
7421   if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
7422                              &isExact) == llvm::APFloat::opOK &&
7423       isExact) {
7424     if (IsLiteral) return;
7425     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
7426                            PruneWarnings);
7427   }
7428 
7429   unsigned DiagID = 0;
7430   if (IsLiteral) {
7431     // Warn on floating point literal to integer.
7432     DiagID = diag::warn_impcast_literal_float_to_integer;
7433   } else if (IntegerValue == 0) {
7434     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
7435       return DiagnoseImpCast(S, E, T, CContext,
7436                              diag::warn_impcast_float_integer, PruneWarnings);
7437     }
7438     // Warn on non-zero to zero conversion.
7439     DiagID = diag::warn_impcast_float_to_integer_zero;
7440   } else {
7441     if (IntegerValue.isUnsigned()) {
7442       if (!IntegerValue.isMaxValue()) {
7443         return DiagnoseImpCast(S, E, T, CContext,
7444                                diag::warn_impcast_float_integer, PruneWarnings);
7445       }
7446     } else {  // IntegerValue.isSigned()
7447       if (!IntegerValue.isMaxSignedValue() &&
7448           !IntegerValue.isMinSignedValue()) {
7449         return DiagnoseImpCast(S, E, T, CContext,
7450                                diag::warn_impcast_float_integer, PruneWarnings);
7451       }
7452     }
7453     // Warn on evaluatable floating point expression to integer conversion.
7454     DiagID = diag::warn_impcast_float_to_integer;
7455   }
7456 
7457   // FIXME: Force the precision of the source value down so we don't print
7458   // digits which are usually useless (we don't really care here if we
7459   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
7460   // would automatically print the shortest representation, but it's a bit
7461   // tricky to implement.
7462   SmallString<16> PrettySourceValue;
7463   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
7464   precision = (precision * 59 + 195) / 196;
7465   Value.toString(PrettySourceValue, precision);
7466 
7467   SmallString<16> PrettyTargetValue;
7468   if (IsBool)
7469     PrettyTargetValue = Value.isZero() ? "false" : "true";
7470   else
7471     IntegerValue.toString(PrettyTargetValue);
7472 
7473   if (PruneWarnings) {
7474     S.DiagRuntimeBehavior(E->getExprLoc(), E,
7475                           S.PDiag(DiagID)
7476                               << E->getType() << T.getUnqualifiedType()
7477                               << PrettySourceValue << PrettyTargetValue
7478                               << E->getSourceRange() << SourceRange(CContext));
7479   } else {
7480     S.Diag(E->getExprLoc(), DiagID)
7481         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
7482         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
7483   }
7484 }
7485 
7486 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
7487   if (!Range.Width) return "0";
7488 
7489   llvm::APSInt ValueInRange = Value;
7490   ValueInRange.setIsSigned(!Range.NonNegative);
7491   ValueInRange = ValueInRange.trunc(Range.Width);
7492   return ValueInRange.toString(10);
7493 }
7494 
7495 bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
7496   if (!isa<ImplicitCastExpr>(Ex))
7497     return false;
7498 
7499   Expr *InnerE = Ex->IgnoreParenImpCasts();
7500   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
7501   const Type *Source =
7502     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
7503   if (Target->isDependentType())
7504     return false;
7505 
7506   const BuiltinType *FloatCandidateBT =
7507     dyn_cast<BuiltinType>(ToBool ? Source : Target);
7508   const Type *BoolCandidateType = ToBool ? Target : Source;
7509 
7510   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7511           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
7512 }
7513 
7514 void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
7515                                       SourceLocation CC) {
7516   unsigned NumArgs = TheCall->getNumArgs();
7517   for (unsigned i = 0; i < NumArgs; ++i) {
7518     Expr *CurrA = TheCall->getArg(i);
7519     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
7520       continue;
7521 
7522     bool IsSwapped = ((i > 0) &&
7523         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
7524     IsSwapped |= ((i < (NumArgs - 1)) &&
7525         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
7526     if (IsSwapped) {
7527       // Warn on this floating-point to bool conversion.
7528       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
7529                       CurrA->getType(), CC,
7530                       diag::warn_impcast_floating_point_to_bool);
7531     }
7532   }
7533 }
7534 
7535 void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC) {
7536   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
7537                         E->getExprLoc()))
7538     return;
7539 
7540   // Don't warn on functions which have return type nullptr_t.
7541   if (isa<CallExpr>(E))
7542     return;
7543 
7544   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
7545   const Expr::NullPointerConstantKind NullKind =
7546       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
7547   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
7548     return;
7549 
7550   // Return if target type is a safe conversion.
7551   if (T->isAnyPointerType() || T->isBlockPointerType() ||
7552       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
7553     return;
7554 
7555   SourceLocation Loc = E->getSourceRange().getBegin();
7556 
7557   // Venture through the macro stacks to get to the source of macro arguments.
7558   // The new location is a better location than the complete location that was
7559   // passed in.
7560   while (S.SourceMgr.isMacroArgExpansion(Loc))
7561     Loc = S.SourceMgr.getImmediateMacroCallerLoc(Loc);
7562 
7563   while (S.SourceMgr.isMacroArgExpansion(CC))
7564     CC = S.SourceMgr.getImmediateMacroCallerLoc(CC);
7565 
7566   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
7567   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
7568     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
7569         Loc, S.SourceMgr, S.getLangOpts());
7570     if (MacroName == "NULL")
7571       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
7572   }
7573 
7574   // Only warn if the null and context location are in the same macro expansion.
7575   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
7576     return;
7577 
7578   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7579       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << clang::SourceRange(CC)
7580       << FixItHint::CreateReplacement(Loc,
7581                                       S.getFixItZeroLiteralForType(T, Loc));
7582 }
7583 
7584 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7585                            ObjCArrayLiteral *ArrayLiteral);
7586 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7587                                 ObjCDictionaryLiteral *DictionaryLiteral);
7588 
7589 /// Check a single element within a collection literal against the
7590 /// target element type.
7591 void checkObjCCollectionLiteralElement(Sema &S, QualType TargetElementType,
7592                                        Expr *Element, unsigned ElementKind) {
7593   // Skip a bitcast to 'id' or qualified 'id'.
7594   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7595     if (ICE->getCastKind() == CK_BitCast &&
7596         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
7597       Element = ICE->getSubExpr();
7598   }
7599 
7600   QualType ElementType = Element->getType();
7601   ExprResult ElementResult(Element);
7602   if (ElementType->getAs<ObjCObjectPointerType>() &&
7603       S.CheckSingleAssignmentConstraints(TargetElementType,
7604                                          ElementResult,
7605                                          false, false)
7606         != Sema::Compatible) {
7607     S.Diag(Element->getLocStart(),
7608            diag::warn_objc_collection_literal_element)
7609       << ElementType << ElementKind << TargetElementType
7610       << Element->getSourceRange();
7611   }
7612 
7613   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7614     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7615   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7616     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7617 }
7618 
7619 /// Check an Objective-C array literal being converted to the given
7620 /// target type.
7621 void checkObjCArrayLiteral(Sema &S, QualType TargetType,
7622                            ObjCArrayLiteral *ArrayLiteral) {
7623   if (!S.NSArrayDecl)
7624     return;
7625 
7626   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7627   if (!TargetObjCPtr)
7628     return;
7629 
7630   if (TargetObjCPtr->isUnspecialized() ||
7631       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7632         != S.NSArrayDecl->getCanonicalDecl())
7633     return;
7634 
7635   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7636   if (TypeArgs.size() != 1)
7637     return;
7638 
7639   QualType TargetElementType = TypeArgs[0];
7640   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
7641     checkObjCCollectionLiteralElement(S, TargetElementType,
7642                                       ArrayLiteral->getElement(I),
7643                                       0);
7644   }
7645 }
7646 
7647 /// Check an Objective-C dictionary literal being converted to the given
7648 /// target type.
7649 void checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
7650                                 ObjCDictionaryLiteral *DictionaryLiteral) {
7651   if (!S.NSDictionaryDecl)
7652     return;
7653 
7654   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
7655   if (!TargetObjCPtr)
7656     return;
7657 
7658   if (TargetObjCPtr->isUnspecialized() ||
7659       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7660         != S.NSDictionaryDecl->getCanonicalDecl())
7661     return;
7662 
7663   auto TypeArgs = TargetObjCPtr->getTypeArgs();
7664   if (TypeArgs.size() != 2)
7665     return;
7666 
7667   QualType TargetKeyType = TypeArgs[0];
7668   QualType TargetObjectType = TypeArgs[1];
7669   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
7670     auto Element = DictionaryLiteral->getKeyValueElement(I);
7671     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7672     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7673   }
7674 }
7675 
7676 // Helper function to filter out cases for constant width constant conversion.
7677 // Don't warn on char array initialization or for non-decimal values.
7678 bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
7679                                    SourceLocation CC) {
7680   // If initializing from a constant, and the constant starts with '0',
7681   // then it is a binary, octal, or hexadecimal.  Allow these constants
7682   // to fill all the bits, even if there is a sign change.
7683   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
7684     const char FirstLiteralCharacter =
7685         S.getSourceManager().getCharacterData(IntLit->getLocStart())[0];
7686     if (FirstLiteralCharacter == '0')
7687       return false;
7688   }
7689 
7690   // If the CC location points to a '{', and the type is char, then assume
7691   // assume it is an array initialization.
7692   if (CC.isValid() && T->isCharType()) {
7693     const char FirstContextCharacter =
7694         S.getSourceManager().getCharacterData(CC)[0];
7695     if (FirstContextCharacter == '{')
7696       return false;
7697   }
7698 
7699   return true;
7700 }
7701 
7702 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
7703                              SourceLocation CC, bool *ICContext = nullptr) {
7704   if (E->isTypeDependent() || E->isValueDependent()) return;
7705 
7706   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
7707   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
7708   if (Source == Target) return;
7709   if (Target->isDependentType()) return;
7710 
7711   // If the conversion context location is invalid don't complain. We also
7712   // don't want to emit a warning if the issue occurs from the expansion of
7713   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
7714   // delay this check as long as possible. Once we detect we are in that
7715   // scenario, we just return.
7716   if (CC.isInvalid())
7717     return;
7718 
7719   // Diagnose implicit casts to bool.
7720   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
7721     if (isa<StringLiteral>(E))
7722       // Warn on string literal to bool.  Checks for string literals in logical
7723       // and expressions, for instance, assert(0 && "error here"), are
7724       // prevented by a check in AnalyzeImplicitConversions().
7725       return DiagnoseImpCast(S, E, T, CC,
7726                              diag::warn_impcast_string_literal_to_bool);
7727     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7728         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7729       // This covers the literal expressions that evaluate to Objective-C
7730       // objects.
7731       return DiagnoseImpCast(S, E, T, CC,
7732                              diag::warn_impcast_objective_c_literal_to_bool);
7733     }
7734     if (Source->isPointerType() || Source->canDecayToPointerType()) {
7735       // Warn on pointer to bool conversion that is always true.
7736       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
7737                                      SourceRange(CC));
7738     }
7739   }
7740 
7741   // Check implicit casts from Objective-C collection literals to specialized
7742   // collection types, e.g., NSArray<NSString *> *.
7743   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7744     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
7745   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7746     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
7747 
7748   // Strip vector types.
7749   if (isa<VectorType>(Source)) {
7750     if (!isa<VectorType>(Target)) {
7751       if (S.SourceMgr.isInSystemMacro(CC))
7752         return;
7753       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
7754     }
7755 
7756     // If the vector cast is cast between two vectors of the same size, it is
7757     // a bitcast, not a conversion.
7758     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
7759       return;
7760 
7761     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
7762     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
7763   }
7764   if (auto VecTy = dyn_cast<VectorType>(Target))
7765     Target = VecTy->getElementType().getTypePtr();
7766 
7767   // Strip complex types.
7768   if (isa<ComplexType>(Source)) {
7769     if (!isa<ComplexType>(Target)) {
7770       if (S.SourceMgr.isInSystemMacro(CC))
7771         return;
7772 
7773       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
7774     }
7775 
7776     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
7777     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
7778   }
7779 
7780   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
7781   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
7782 
7783   // If the source is floating point...
7784   if (SourceBT && SourceBT->isFloatingPoint()) {
7785     // ...and the target is floating point...
7786     if (TargetBT && TargetBT->isFloatingPoint()) {
7787       // ...then warn if we're dropping FP rank.
7788 
7789       // Builtin FP kinds are ordered by increasing FP rank.
7790       if (SourceBT->getKind() > TargetBT->getKind()) {
7791         // Don't warn about float constants that are precisely
7792         // representable in the target type.
7793         Expr::EvalResult result;
7794         if (E->EvaluateAsRValue(result, S.Context)) {
7795           // Value might be a float, a float vector, or a float complex.
7796           if (IsSameFloatAfterCast(result.Val,
7797                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
7798                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
7799             return;
7800         }
7801 
7802         if (S.SourceMgr.isInSystemMacro(CC))
7803           return;
7804 
7805         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
7806       }
7807       // ... or possibly if we're increasing rank, too
7808       else if (TargetBT->getKind() > SourceBT->getKind()) {
7809         if (S.SourceMgr.isInSystemMacro(CC))
7810           return;
7811 
7812         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
7813       }
7814       return;
7815     }
7816 
7817     // If the target is integral, always warn.
7818     if (TargetBT && TargetBT->isInteger()) {
7819       if (S.SourceMgr.isInSystemMacro(CC))
7820         return;
7821 
7822       DiagnoseFloatingImpCast(S, E, T, CC);
7823     }
7824 
7825     // Detect the case where a call result is converted from floating-point to
7826     // to bool, and the final argument to the call is converted from bool, to
7827     // discover this typo:
7828     //
7829     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
7830     //
7831     // FIXME: This is an incredibly special case; is there some more general
7832     // way to detect this class of misplaced-parentheses bug?
7833     if (Target->isBooleanType() && isa<CallExpr>(E)) {
7834       // Check last argument of function call to see if it is an
7835       // implicit cast from a type matching the type the result
7836       // is being cast to.
7837       CallExpr *CEx = cast<CallExpr>(E);
7838       if (unsigned NumArgs = CEx->getNumArgs()) {
7839         Expr *LastA = CEx->getArg(NumArgs - 1);
7840         Expr *InnerE = LastA->IgnoreParenImpCasts();
7841         if (isa<ImplicitCastExpr>(LastA) &&
7842             InnerE->getType()->isBooleanType()) {
7843           // Warn on this floating-point to bool conversion
7844           DiagnoseImpCast(S, E, T, CC,
7845                           diag::warn_impcast_floating_point_to_bool);
7846         }
7847       }
7848     }
7849     return;
7850   }
7851 
7852   DiagnoseNullConversion(S, E, T, CC);
7853 
7854   if (!Source->isIntegerType() || !Target->isIntegerType())
7855     return;
7856 
7857   // TODO: remove this early return once the false positives for constant->bool
7858   // in templates, macros, etc, are reduced or removed.
7859   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
7860     return;
7861 
7862   IntRange SourceRange = GetExprRange(S.Context, E);
7863   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
7864 
7865   if (SourceRange.Width > TargetRange.Width) {
7866     // If the source is a constant, use a default-on diagnostic.
7867     // TODO: this should happen for bitfield stores, too.
7868     llvm::APSInt Value(32);
7869     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects)) {
7870       if (S.SourceMgr.isInSystemMacro(CC))
7871         return;
7872 
7873       std::string PrettySourceValue = Value.toString(10);
7874       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7875 
7876       S.DiagRuntimeBehavior(E->getExprLoc(), E,
7877         S.PDiag(diag::warn_impcast_integer_precision_constant)
7878             << PrettySourceValue << PrettyTargetValue
7879             << E->getType() << T << E->getSourceRange()
7880             << clang::SourceRange(CC));
7881       return;
7882     }
7883 
7884     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
7885     if (S.SourceMgr.isInSystemMacro(CC))
7886       return;
7887 
7888     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
7889       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7890                              /* pruneControlFlow */ true);
7891     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7892   }
7893 
7894   if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
7895       SourceRange.NonNegative && Source->isSignedIntegerType()) {
7896     // Warn when doing a signed to signed conversion, warn if the positive
7897     // source value is exactly the width of the target type, which will
7898     // cause a negative value to be stored.
7899 
7900     llvm::APSInt Value;
7901     if (E->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects) &&
7902         !S.SourceMgr.isInSystemMacro(CC)) {
7903       if (isSameWidthConstantConversion(S, E, T, CC)) {
7904         std::string PrettySourceValue = Value.toString(10);
7905         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7906 
7907         S.DiagRuntimeBehavior(
7908             E->getExprLoc(), E,
7909             S.PDiag(diag::warn_impcast_integer_precision_constant)
7910                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
7911                 << E->getSourceRange() << clang::SourceRange(CC));
7912         return;
7913       }
7914     }
7915 
7916     // Fall through for non-constants to give a sign conversion warning.
7917   }
7918 
7919   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7920       (!TargetRange.NonNegative && SourceRange.NonNegative &&
7921        SourceRange.Width == TargetRange.Width)) {
7922     if (S.SourceMgr.isInSystemMacro(CC))
7923       return;
7924 
7925     unsigned DiagID = diag::warn_impcast_integer_sign;
7926 
7927     // Traditionally, gcc has warned about this under -Wsign-compare.
7928     // We also want to warn about it in -Wconversion.
7929     // So if -Wconversion is off, use a completely identical diagnostic
7930     // in the sign-compare group.
7931     // The conditional-checking code will
7932     if (ICContext) {
7933       DiagID = diag::warn_impcast_integer_sign_conditional;
7934       *ICContext = true;
7935     }
7936 
7937     return DiagnoseImpCast(S, E, T, CC, DiagID);
7938   }
7939 
7940   // Diagnose conversions between different enumeration types.
7941   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
7942   // type, to give us better diagnostics.
7943   QualType SourceType = E->getType();
7944   if (!S.getLangOpts().CPlusPlus) {
7945     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7946       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
7947         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7948         SourceType = S.Context.getTypeDeclType(Enum);
7949         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
7950       }
7951   }
7952 
7953   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
7954     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
7955       if (SourceEnum->getDecl()->hasNameForLinkage() &&
7956           TargetEnum->getDecl()->hasNameForLinkage() &&
7957           SourceEnum != TargetEnum) {
7958         if (S.SourceMgr.isInSystemMacro(CC))
7959           return;
7960 
7961         return DiagnoseImpCast(S, E, SourceType, T, CC,
7962                                diag::warn_impcast_different_enum_types);
7963       }
7964 }
7965 
7966 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7967                               SourceLocation CC, QualType T);
7968 
7969 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
7970                              SourceLocation CC, bool &ICContext) {
7971   E = E->IgnoreParenImpCasts();
7972 
7973   if (isa<ConditionalOperator>(E))
7974     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7975 
7976   AnalyzeImplicitConversions(S, E, CC);
7977   if (E->getType() != T)
7978     return CheckImplicitConversion(S, E, T, CC, &ICContext);
7979 }
7980 
7981 void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
7982                               SourceLocation CC, QualType T) {
7983   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
7984 
7985   bool Suspicious = false;
7986   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
7987   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
7988 
7989   // If -Wconversion would have warned about either of the candidates
7990   // for a signedness conversion to the context type...
7991   if (!Suspicious) return;
7992 
7993   // ...but it's currently ignored...
7994   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7995     return;
7996 
7997   // ...then check whether it would have warned about either of the
7998   // candidates for a signedness conversion to the condition type.
7999   if (E->getType() == T) return;
8000 
8001   Suspicious = false;
8002   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
8003                           E->getType(), CC, &Suspicious);
8004   if (!Suspicious)
8005     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
8006                             E->getType(), CC, &Suspicious);
8007 }
8008 
8009 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8010 /// Input argument E is a logical expression.
8011 void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
8012   if (S.getLangOpts().Bool)
8013     return;
8014   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
8015 }
8016 
8017 /// AnalyzeImplicitConversions - Find and report any interesting
8018 /// implicit conversions in the given expression.  There are a couple
8019 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
8020 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
8021   QualType T = OrigE->getType();
8022   Expr *E = OrigE->IgnoreParenImpCasts();
8023 
8024   if (E->isTypeDependent() || E->isValueDependent())
8025     return;
8026 
8027   // For conditional operators, we analyze the arguments as if they
8028   // were being fed directly into the output.
8029   if (isa<ConditionalOperator>(E)) {
8030     ConditionalOperator *CO = cast<ConditionalOperator>(E);
8031     CheckConditionalOperator(S, CO, CC, T);
8032     return;
8033   }
8034 
8035   // Check implicit argument conversions for function calls.
8036   if (CallExpr *Call = dyn_cast<CallExpr>(E))
8037     CheckImplicitArgumentConversions(S, Call, CC);
8038 
8039   // Go ahead and check any implicit conversions we might have skipped.
8040   // The non-canonical typecheck is just an optimization;
8041   // CheckImplicitConversion will filter out dead implicit conversions.
8042   if (E->getType() != T)
8043     CheckImplicitConversion(S, E, T, CC);
8044 
8045   // Now continue drilling into this expression.
8046 
8047   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
8048     // The bound subexpressions in a PseudoObjectExpr are not reachable
8049     // as transitive children.
8050     // FIXME: Use a more uniform representation for this.
8051     for (auto *SE : POE->semantics())
8052       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
8053         AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
8054   }
8055 
8056   // Skip past explicit casts.
8057   if (isa<ExplicitCastExpr>(E)) {
8058     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
8059     return AnalyzeImplicitConversions(S, E, CC);
8060   }
8061 
8062   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8063     // Do a somewhat different check with comparison operators.
8064     if (BO->isComparisonOp())
8065       return AnalyzeComparison(S, BO);
8066 
8067     // And with simple assignments.
8068     if (BO->getOpcode() == BO_Assign)
8069       return AnalyzeAssignment(S, BO);
8070   }
8071 
8072   // These break the otherwise-useful invariant below.  Fortunately,
8073   // we don't really need to recurse into them, because any internal
8074   // expressions should have been analyzed already when they were
8075   // built into statements.
8076   if (isa<StmtExpr>(E)) return;
8077 
8078   // Don't descend into unevaluated contexts.
8079   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
8080 
8081   // Now just recurse over the expression's children.
8082   CC = E->getExprLoc();
8083   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
8084   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
8085   for (Stmt *SubStmt : E->children()) {
8086     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
8087     if (!ChildExpr)
8088       continue;
8089 
8090     if (IsLogicalAndOperator &&
8091         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
8092       // Ignore checking string literals that are in logical and operators.
8093       // This is a common pattern for asserts.
8094       continue;
8095     AnalyzeImplicitConversions(S, ChildExpr, CC);
8096   }
8097 
8098   if (BO && BO->isLogicalOp()) {
8099     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
8100     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8101       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8102 
8103     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
8104     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
8105       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
8106   }
8107 
8108   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E))
8109     if (U->getOpcode() == UO_LNot)
8110       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
8111 }
8112 
8113 } // end anonymous namespace
8114 
8115 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
8116 // Returns true when emitting a warning about taking the address of a reference.
8117 static bool CheckForReference(Sema &SemaRef, const Expr *E,
8118                               PartialDiagnostic PD) {
8119   E = E->IgnoreParenImpCasts();
8120 
8121   const FunctionDecl *FD = nullptr;
8122 
8123   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8124     if (!DRE->getDecl()->getType()->isReferenceType())
8125       return false;
8126   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8127     if (!M->getMemberDecl()->getType()->isReferenceType())
8128       return false;
8129   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
8130     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
8131       return false;
8132     FD = Call->getDirectCallee();
8133   } else {
8134     return false;
8135   }
8136 
8137   SemaRef.Diag(E->getExprLoc(), PD);
8138 
8139   // If possible, point to location of function.
8140   if (FD) {
8141     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
8142   }
8143 
8144   return true;
8145 }
8146 
8147 // Returns true if the SourceLocation is expanded from any macro body.
8148 // Returns false if the SourceLocation is invalid, is from not in a macro
8149 // expansion, or is from expanded from a top-level macro argument.
8150 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
8151   if (Loc.isInvalid())
8152     return false;
8153 
8154   while (Loc.isMacroID()) {
8155     if (SM.isMacroBodyExpansion(Loc))
8156       return true;
8157     Loc = SM.getImmediateMacroCallerLoc(Loc);
8158   }
8159 
8160   return false;
8161 }
8162 
8163 /// \brief Diagnose pointers that are always non-null.
8164 /// \param E the expression containing the pointer
8165 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
8166 /// compared to a null pointer
8167 /// \param IsEqual True when the comparison is equal to a null pointer
8168 /// \param Range Extra SourceRange to highlight in the diagnostic
8169 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
8170                                         Expr::NullPointerConstantKind NullKind,
8171                                         bool IsEqual, SourceRange Range) {
8172   if (!E)
8173     return;
8174 
8175   // Don't warn inside macros.
8176   if (E->getExprLoc().isMacroID()) {
8177     const SourceManager &SM = getSourceManager();
8178     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
8179         IsInAnyMacroBody(SM, Range.getBegin()))
8180       return;
8181   }
8182   E = E->IgnoreImpCasts();
8183 
8184   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
8185 
8186   if (isa<CXXThisExpr>(E)) {
8187     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
8188                                 : diag::warn_this_bool_conversion;
8189     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
8190     return;
8191   }
8192 
8193   bool IsAddressOf = false;
8194 
8195   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8196     if (UO->getOpcode() != UO_AddrOf)
8197       return;
8198     IsAddressOf = true;
8199     E = UO->getSubExpr();
8200   }
8201 
8202   if (IsAddressOf) {
8203     unsigned DiagID = IsCompare
8204                           ? diag::warn_address_of_reference_null_compare
8205                           : diag::warn_address_of_reference_bool_conversion;
8206     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
8207                                          << IsEqual;
8208     if (CheckForReference(*this, E, PD)) {
8209       return;
8210     }
8211   }
8212 
8213   auto ComplainAboutNonnullParamOrCall = [&](bool IsParam) {
8214     std::string Str;
8215     llvm::raw_string_ostream S(Str);
8216     E->printPretty(S, nullptr, getPrintingPolicy());
8217     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
8218                                 : diag::warn_cast_nonnull_to_bool;
8219     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
8220       << E->getSourceRange() << Range << IsEqual;
8221   };
8222 
8223   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
8224   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
8225     if (auto *Callee = Call->getDirectCallee()) {
8226       if (Callee->hasAttr<ReturnsNonNullAttr>()) {
8227         ComplainAboutNonnullParamOrCall(false);
8228         return;
8229       }
8230     }
8231   }
8232 
8233   // Expect to find a single Decl.  Skip anything more complicated.
8234   ValueDecl *D = nullptr;
8235   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
8236     D = R->getDecl();
8237   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
8238     D = M->getMemberDecl();
8239   }
8240 
8241   // Weak Decls can be null.
8242   if (!D || D->isWeak())
8243     return;
8244 
8245   // Check for parameter decl with nonnull attribute
8246   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
8247     if (getCurFunction() &&
8248         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
8249       if (PV->hasAttr<NonNullAttr>()) {
8250         ComplainAboutNonnullParamOrCall(true);
8251         return;
8252       }
8253 
8254       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
8255         auto ParamIter = std::find(FD->param_begin(), FD->param_end(), PV);
8256         assert(ParamIter != FD->param_end());
8257         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
8258 
8259         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
8260           if (!NonNull->args_size()) {
8261               ComplainAboutNonnullParamOrCall(true);
8262               return;
8263           }
8264 
8265           for (unsigned ArgNo : NonNull->args()) {
8266             if (ArgNo == ParamNo) {
8267               ComplainAboutNonnullParamOrCall(true);
8268               return;
8269             }
8270           }
8271         }
8272       }
8273     }
8274   }
8275 
8276   QualType T = D->getType();
8277   const bool IsArray = T->isArrayType();
8278   const bool IsFunction = T->isFunctionType();
8279 
8280   // Address of function is used to silence the function warning.
8281   if (IsAddressOf && IsFunction) {
8282     return;
8283   }
8284 
8285   // Found nothing.
8286   if (!IsAddressOf && !IsFunction && !IsArray)
8287     return;
8288 
8289   // Pretty print the expression for the diagnostic.
8290   std::string Str;
8291   llvm::raw_string_ostream S(Str);
8292   E->printPretty(S, nullptr, getPrintingPolicy());
8293 
8294   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
8295                               : diag::warn_impcast_pointer_to_bool;
8296   enum {
8297     AddressOf,
8298     FunctionPointer,
8299     ArrayPointer
8300   } DiagType;
8301   if (IsAddressOf)
8302     DiagType = AddressOf;
8303   else if (IsFunction)
8304     DiagType = FunctionPointer;
8305   else if (IsArray)
8306     DiagType = ArrayPointer;
8307   else
8308     llvm_unreachable("Could not determine diagnostic.");
8309   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
8310                                 << Range << IsEqual;
8311 
8312   if (!IsFunction)
8313     return;
8314 
8315   // Suggest '&' to silence the function warning.
8316   Diag(E->getExprLoc(), diag::note_function_warning_silence)
8317       << FixItHint::CreateInsertion(E->getLocStart(), "&");
8318 
8319   // Check to see if '()' fixit should be emitted.
8320   QualType ReturnType;
8321   UnresolvedSet<4> NonTemplateOverloads;
8322   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
8323   if (ReturnType.isNull())
8324     return;
8325 
8326   if (IsCompare) {
8327     // There are two cases here.  If there is null constant, the only suggest
8328     // for a pointer return type.  If the null is 0, then suggest if the return
8329     // type is a pointer or an integer type.
8330     if (!ReturnType->isPointerType()) {
8331       if (NullKind == Expr::NPCK_ZeroExpression ||
8332           NullKind == Expr::NPCK_ZeroLiteral) {
8333         if (!ReturnType->isIntegerType())
8334           return;
8335       } else {
8336         return;
8337       }
8338     }
8339   } else { // !IsCompare
8340     // For function to bool, only suggest if the function pointer has bool
8341     // return type.
8342     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
8343       return;
8344   }
8345   Diag(E->getExprLoc(), diag::note_function_to_function_call)
8346       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getLocEnd()), "()");
8347 }
8348 
8349 /// Diagnoses "dangerous" implicit conversions within the given
8350 /// expression (which is a full expression).  Implements -Wconversion
8351 /// and -Wsign-compare.
8352 ///
8353 /// \param CC the "context" location of the implicit conversion, i.e.
8354 ///   the most location of the syntactic entity requiring the implicit
8355 ///   conversion
8356 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
8357   // Don't diagnose in unevaluated contexts.
8358   if (isUnevaluatedContext())
8359     return;
8360 
8361   // Don't diagnose for value- or type-dependent expressions.
8362   if (E->isTypeDependent() || E->isValueDependent())
8363     return;
8364 
8365   // Check for array bounds violations in cases where the check isn't triggered
8366   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
8367   // ArraySubscriptExpr is on the RHS of a variable initialization.
8368   CheckArrayAccess(E);
8369 
8370   // This is not the right CC for (e.g.) a variable initialization.
8371   AnalyzeImplicitConversions(*this, E, CC);
8372 }
8373 
8374 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
8375 /// Input argument E is a logical expression.
8376 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
8377   ::CheckBoolLikeConversion(*this, E, CC);
8378 }
8379 
8380 /// Diagnose when expression is an integer constant expression and its evaluation
8381 /// results in integer overflow
8382 void Sema::CheckForIntOverflow (Expr *E) {
8383   // Use a work list to deal with nested struct initializers.
8384   SmallVector<Expr *, 2> Exprs(1, E);
8385 
8386   do {
8387     Expr *E = Exprs.pop_back_val();
8388 
8389     if (isa<BinaryOperator>(E->IgnoreParenCasts())) {
8390       E->IgnoreParenCasts()->EvaluateForOverflow(Context);
8391       continue;
8392     }
8393 
8394     if (auto InitList = dyn_cast<InitListExpr>(E))
8395       Exprs.append(InitList->inits().begin(), InitList->inits().end());
8396   } while (!Exprs.empty());
8397 }
8398 
8399 namespace {
8400 /// \brief Visitor for expressions which looks for unsequenced operations on the
8401 /// same object.
8402 class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
8403   typedef EvaluatedExprVisitor<SequenceChecker> Base;
8404 
8405   /// \brief A tree of sequenced regions within an expression. Two regions are
8406   /// unsequenced if one is an ancestor or a descendent of the other. When we
8407   /// finish processing an expression with sequencing, such as a comma
8408   /// expression, we fold its tree nodes into its parent, since they are
8409   /// unsequenced with respect to nodes we will visit later.
8410   class SequenceTree {
8411     struct Value {
8412       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
8413       unsigned Parent : 31;
8414       bool Merged : 1;
8415     };
8416     SmallVector<Value, 8> Values;
8417 
8418   public:
8419     /// \brief A region within an expression which may be sequenced with respect
8420     /// to some other region.
8421     class Seq {
8422       explicit Seq(unsigned N) : Index(N) {}
8423       unsigned Index;
8424       friend class SequenceTree;
8425     public:
8426       Seq() : Index(0) {}
8427     };
8428 
8429     SequenceTree() { Values.push_back(Value(0)); }
8430     Seq root() const { return Seq(0); }
8431 
8432     /// \brief Create a new sequence of operations, which is an unsequenced
8433     /// subset of \p Parent. This sequence of operations is sequenced with
8434     /// respect to other children of \p Parent.
8435     Seq allocate(Seq Parent) {
8436       Values.push_back(Value(Parent.Index));
8437       return Seq(Values.size() - 1);
8438     }
8439 
8440     /// \brief Merge a sequence of operations into its parent.
8441     void merge(Seq S) {
8442       Values[S.Index].Merged = true;
8443     }
8444 
8445     /// \brief Determine whether two operations are unsequenced. This operation
8446     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
8447     /// should have been merged into its parent as appropriate.
8448     bool isUnsequenced(Seq Cur, Seq Old) {
8449       unsigned C = representative(Cur.Index);
8450       unsigned Target = representative(Old.Index);
8451       while (C >= Target) {
8452         if (C == Target)
8453           return true;
8454         C = Values[C].Parent;
8455       }
8456       return false;
8457     }
8458 
8459   private:
8460     /// \brief Pick a representative for a sequence.
8461     unsigned representative(unsigned K) {
8462       if (Values[K].Merged)
8463         // Perform path compression as we go.
8464         return Values[K].Parent = representative(Values[K].Parent);
8465       return K;
8466     }
8467   };
8468 
8469   /// An object for which we can track unsequenced uses.
8470   typedef NamedDecl *Object;
8471 
8472   /// Different flavors of object usage which we track. We only track the
8473   /// least-sequenced usage of each kind.
8474   enum UsageKind {
8475     /// A read of an object. Multiple unsequenced reads are OK.
8476     UK_Use,
8477     /// A modification of an object which is sequenced before the value
8478     /// computation of the expression, such as ++n in C++.
8479     UK_ModAsValue,
8480     /// A modification of an object which is not sequenced before the value
8481     /// computation of the expression, such as n++.
8482     UK_ModAsSideEffect,
8483 
8484     UK_Count = UK_ModAsSideEffect + 1
8485   };
8486 
8487   struct Usage {
8488     Usage() : Use(nullptr), Seq() {}
8489     Expr *Use;
8490     SequenceTree::Seq Seq;
8491   };
8492 
8493   struct UsageInfo {
8494     UsageInfo() : Diagnosed(false) {}
8495     Usage Uses[UK_Count];
8496     /// Have we issued a diagnostic for this variable already?
8497     bool Diagnosed;
8498   };
8499   typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
8500 
8501   Sema &SemaRef;
8502   /// Sequenced regions within the expression.
8503   SequenceTree Tree;
8504   /// Declaration modifications and references which we have seen.
8505   UsageInfoMap UsageMap;
8506   /// The region we are currently within.
8507   SequenceTree::Seq Region;
8508   /// Filled in with declarations which were modified as a side-effect
8509   /// (that is, post-increment operations).
8510   SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
8511   /// Expressions to check later. We defer checking these to reduce
8512   /// stack usage.
8513   SmallVectorImpl<Expr *> &WorkList;
8514 
8515   /// RAII object wrapping the visitation of a sequenced subexpression of an
8516   /// expression. At the end of this process, the side-effects of the evaluation
8517   /// become sequenced with respect to the value computation of the result, so
8518   /// we downgrade any UK_ModAsSideEffect within the evaluation to
8519   /// UK_ModAsValue.
8520   struct SequencedSubexpression {
8521     SequencedSubexpression(SequenceChecker &Self)
8522       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
8523       Self.ModAsSideEffect = &ModAsSideEffect;
8524     }
8525     ~SequencedSubexpression() {
8526       for (auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
8527            MI != ME; ++MI) {
8528         UsageInfo &U = Self.UsageMap[MI->first];
8529         auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
8530         Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
8531         SideEffectUsage = MI->second;
8532       }
8533       Self.ModAsSideEffect = OldModAsSideEffect;
8534     }
8535 
8536     SequenceChecker &Self;
8537     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
8538     SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
8539   };
8540 
8541   /// RAII object wrapping the visitation of a subexpression which we might
8542   /// choose to evaluate as a constant. If any subexpression is evaluated and
8543   /// found to be non-constant, this allows us to suppress the evaluation of
8544   /// the outer expression.
8545   class EvaluationTracker {
8546   public:
8547     EvaluationTracker(SequenceChecker &Self)
8548         : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
8549       Self.EvalTracker = this;
8550     }
8551     ~EvaluationTracker() {
8552       Self.EvalTracker = Prev;
8553       if (Prev)
8554         Prev->EvalOK &= EvalOK;
8555     }
8556 
8557     bool evaluate(const Expr *E, bool &Result) {
8558       if (!EvalOK || E->isValueDependent())
8559         return false;
8560       EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
8561       return EvalOK;
8562     }
8563 
8564   private:
8565     SequenceChecker &Self;
8566     EvaluationTracker *Prev;
8567     bool EvalOK;
8568   } *EvalTracker;
8569 
8570   /// \brief Find the object which is produced by the specified expression,
8571   /// if any.
8572   Object getObject(Expr *E, bool Mod) const {
8573     E = E->IgnoreParenCasts();
8574     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8575       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
8576         return getObject(UO->getSubExpr(), Mod);
8577     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8578       if (BO->getOpcode() == BO_Comma)
8579         return getObject(BO->getRHS(), Mod);
8580       if (Mod && BO->isAssignmentOp())
8581         return getObject(BO->getLHS(), Mod);
8582     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8583       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
8584       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8585         return ME->getMemberDecl();
8586     } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8587       // FIXME: If this is a reference, map through to its value.
8588       return DRE->getDecl();
8589     return nullptr;
8590   }
8591 
8592   /// \brief Note that an object was modified or used by an expression.
8593   void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
8594     Usage &U = UI.Uses[UK];
8595     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8596       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8597         ModAsSideEffect->push_back(std::make_pair(O, U));
8598       U.Use = Ref;
8599       U.Seq = Region;
8600     }
8601   }
8602   /// \brief Check whether a modification or use conflicts with a prior usage.
8603   void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
8604                   bool IsModMod) {
8605     if (UI.Diagnosed)
8606       return;
8607 
8608     const Usage &U = UI.Uses[OtherKind];
8609     if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8610       return;
8611 
8612     Expr *Mod = U.Use;
8613     Expr *ModOrUse = Ref;
8614     if (OtherKind == UK_Use)
8615       std::swap(Mod, ModOrUse);
8616 
8617     SemaRef.Diag(Mod->getExprLoc(),
8618                  IsModMod ? diag::warn_unsequenced_mod_mod
8619                           : diag::warn_unsequenced_mod_use)
8620       << O << SourceRange(ModOrUse->getExprLoc());
8621     UI.Diagnosed = true;
8622   }
8623 
8624   void notePreUse(Object O, Expr *Use) {
8625     UsageInfo &U = UsageMap[O];
8626     // Uses conflict with other modifications.
8627     checkUsage(O, U, Use, UK_ModAsValue, false);
8628   }
8629   void notePostUse(Object O, Expr *Use) {
8630     UsageInfo &U = UsageMap[O];
8631     checkUsage(O, U, Use, UK_ModAsSideEffect, false);
8632     addUsage(U, O, Use, UK_Use);
8633   }
8634 
8635   void notePreMod(Object O, Expr *Mod) {
8636     UsageInfo &U = UsageMap[O];
8637     // Modifications conflict with other modifications and with uses.
8638     checkUsage(O, U, Mod, UK_ModAsValue, true);
8639     checkUsage(O, U, Mod, UK_Use, false);
8640   }
8641   void notePostMod(Object O, Expr *Use, UsageKind UK) {
8642     UsageInfo &U = UsageMap[O];
8643     checkUsage(O, U, Use, UK_ModAsSideEffect, true);
8644     addUsage(U, O, Use, UK);
8645   }
8646 
8647 public:
8648   SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
8649       : Base(S.Context), SemaRef(S), Region(Tree.root()),
8650         ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
8651     Visit(E);
8652   }
8653 
8654   void VisitStmt(Stmt *S) {
8655     // Skip all statements which aren't expressions for now.
8656   }
8657 
8658   void VisitExpr(Expr *E) {
8659     // By default, just recurse to evaluated subexpressions.
8660     Base::VisitStmt(E);
8661   }
8662 
8663   void VisitCastExpr(CastExpr *E) {
8664     Object O = Object();
8665     if (E->getCastKind() == CK_LValueToRValue)
8666       O = getObject(E->getSubExpr(), false);
8667 
8668     if (O)
8669       notePreUse(O, E);
8670     VisitExpr(E);
8671     if (O)
8672       notePostUse(O, E);
8673   }
8674 
8675   void VisitBinComma(BinaryOperator *BO) {
8676     // C++11 [expr.comma]p1:
8677     //   Every value computation and side effect associated with the left
8678     //   expression is sequenced before every value computation and side
8679     //   effect associated with the right expression.
8680     SequenceTree::Seq LHS = Tree.allocate(Region);
8681     SequenceTree::Seq RHS = Tree.allocate(Region);
8682     SequenceTree::Seq OldRegion = Region;
8683 
8684     {
8685       SequencedSubexpression SeqLHS(*this);
8686       Region = LHS;
8687       Visit(BO->getLHS());
8688     }
8689 
8690     Region = RHS;
8691     Visit(BO->getRHS());
8692 
8693     Region = OldRegion;
8694 
8695     // Forget that LHS and RHS are sequenced. They are both unsequenced
8696     // with respect to other stuff.
8697     Tree.merge(LHS);
8698     Tree.merge(RHS);
8699   }
8700 
8701   void VisitBinAssign(BinaryOperator *BO) {
8702     // The modification is sequenced after the value computation of the LHS
8703     // and RHS, so check it before inspecting the operands and update the
8704     // map afterwards.
8705     Object O = getObject(BO->getLHS(), true);
8706     if (!O)
8707       return VisitExpr(BO);
8708 
8709     notePreMod(O, BO);
8710 
8711     // C++11 [expr.ass]p7:
8712     //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
8713     //   only once.
8714     //
8715     // Therefore, for a compound assignment operator, O is considered used
8716     // everywhere except within the evaluation of E1 itself.
8717     if (isa<CompoundAssignOperator>(BO))
8718       notePreUse(O, BO);
8719 
8720     Visit(BO->getLHS());
8721 
8722     if (isa<CompoundAssignOperator>(BO))
8723       notePostUse(O, BO);
8724 
8725     Visit(BO->getRHS());
8726 
8727     // C++11 [expr.ass]p1:
8728     //   the assignment is sequenced [...] before the value computation of the
8729     //   assignment expression.
8730     // C11 6.5.16/3 has no such rule.
8731     notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8732                                                        : UK_ModAsSideEffect);
8733   }
8734 
8735   void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
8736     VisitBinAssign(CAO);
8737   }
8738 
8739   void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8740   void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8741   void VisitUnaryPreIncDec(UnaryOperator *UO) {
8742     Object O = getObject(UO->getSubExpr(), true);
8743     if (!O)
8744       return VisitExpr(UO);
8745 
8746     notePreMod(O, UO);
8747     Visit(UO->getSubExpr());
8748     // C++11 [expr.pre.incr]p1:
8749     //   the expression ++x is equivalent to x+=1
8750     notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8751                                                        : UK_ModAsSideEffect);
8752   }
8753 
8754   void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8755   void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8756   void VisitUnaryPostIncDec(UnaryOperator *UO) {
8757     Object O = getObject(UO->getSubExpr(), true);
8758     if (!O)
8759       return VisitExpr(UO);
8760 
8761     notePreMod(O, UO);
8762     Visit(UO->getSubExpr());
8763     notePostMod(O, UO, UK_ModAsSideEffect);
8764   }
8765 
8766   /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
8767   void VisitBinLOr(BinaryOperator *BO) {
8768     // The side-effects of the LHS of an '&&' are sequenced before the
8769     // value computation of the RHS, and hence before the value computation
8770     // of the '&&' itself, unless the LHS evaluates to zero. We treat them
8771     // as if they were unconditionally sequenced.
8772     EvaluationTracker Eval(*this);
8773     {
8774       SequencedSubexpression Sequenced(*this);
8775       Visit(BO->getLHS());
8776     }
8777 
8778     bool Result;
8779     if (Eval.evaluate(BO->getLHS(), Result)) {
8780       if (!Result)
8781         Visit(BO->getRHS());
8782     } else {
8783       // Check for unsequenced operations in the RHS, treating it as an
8784       // entirely separate evaluation.
8785       //
8786       // FIXME: If there are operations in the RHS which are unsequenced
8787       // with respect to operations outside the RHS, and those operations
8788       // are unconditionally evaluated, diagnose them.
8789       WorkList.push_back(BO->getRHS());
8790     }
8791   }
8792   void VisitBinLAnd(BinaryOperator *BO) {
8793     EvaluationTracker Eval(*this);
8794     {
8795       SequencedSubexpression Sequenced(*this);
8796       Visit(BO->getLHS());
8797     }
8798 
8799     bool Result;
8800     if (Eval.evaluate(BO->getLHS(), Result)) {
8801       if (Result)
8802         Visit(BO->getRHS());
8803     } else {
8804       WorkList.push_back(BO->getRHS());
8805     }
8806   }
8807 
8808   // Only visit the condition, unless we can be sure which subexpression will
8809   // be chosen.
8810   void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
8811     EvaluationTracker Eval(*this);
8812     {
8813       SequencedSubexpression Sequenced(*this);
8814       Visit(CO->getCond());
8815     }
8816 
8817     bool Result;
8818     if (Eval.evaluate(CO->getCond(), Result))
8819       Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
8820     else {
8821       WorkList.push_back(CO->getTrueExpr());
8822       WorkList.push_back(CO->getFalseExpr());
8823     }
8824   }
8825 
8826   void VisitCallExpr(CallExpr *CE) {
8827     // C++11 [intro.execution]p15:
8828     //   When calling a function [...], every value computation and side effect
8829     //   associated with any argument expression, or with the postfix expression
8830     //   designating the called function, is sequenced before execution of every
8831     //   expression or statement in the body of the function [and thus before
8832     //   the value computation of its result].
8833     SequencedSubexpression Sequenced(*this);
8834     Base::VisitCallExpr(CE);
8835 
8836     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
8837   }
8838 
8839   void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
8840     // This is a call, so all subexpressions are sequenced before the result.
8841     SequencedSubexpression Sequenced(*this);
8842 
8843     if (!CCE->isListInitialization())
8844       return VisitExpr(CCE);
8845 
8846     // In C++11, list initializations are sequenced.
8847     SmallVector<SequenceTree::Seq, 32> Elts;
8848     SequenceTree::Seq Parent = Region;
8849     for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
8850                                         E = CCE->arg_end();
8851          I != E; ++I) {
8852       Region = Tree.allocate(Parent);
8853       Elts.push_back(Region);
8854       Visit(*I);
8855     }
8856 
8857     // Forget that the initializers are sequenced.
8858     Region = Parent;
8859     for (unsigned I = 0; I < Elts.size(); ++I)
8860       Tree.merge(Elts[I]);
8861   }
8862 
8863   void VisitInitListExpr(InitListExpr *ILE) {
8864     if (!SemaRef.getLangOpts().CPlusPlus11)
8865       return VisitExpr(ILE);
8866 
8867     // In C++11, list initializations are sequenced.
8868     SmallVector<SequenceTree::Seq, 32> Elts;
8869     SequenceTree::Seq Parent = Region;
8870     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
8871       Expr *E = ILE->getInit(I);
8872       if (!E) continue;
8873       Region = Tree.allocate(Parent);
8874       Elts.push_back(Region);
8875       Visit(E);
8876     }
8877 
8878     // Forget that the initializers are sequenced.
8879     Region = Parent;
8880     for (unsigned I = 0; I < Elts.size(); ++I)
8881       Tree.merge(Elts[I]);
8882   }
8883 };
8884 } // end anonymous namespace
8885 
8886 void Sema::CheckUnsequencedOperations(Expr *E) {
8887   SmallVector<Expr *, 8> WorkList;
8888   WorkList.push_back(E);
8889   while (!WorkList.empty()) {
8890     Expr *Item = WorkList.pop_back_val();
8891     SequenceChecker(*this, Item, WorkList);
8892   }
8893 }
8894 
8895 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
8896                               bool IsConstexpr) {
8897   CheckImplicitConversions(E, CheckLoc);
8898   CheckUnsequencedOperations(E);
8899   if (!IsConstexpr && !E->isValueDependent())
8900     CheckForIntOverflow(E);
8901 }
8902 
8903 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
8904                                        FieldDecl *BitField,
8905                                        Expr *Init) {
8906   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
8907 }
8908 
8909 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
8910                                          SourceLocation Loc) {
8911   if (!PType->isVariablyModifiedType())
8912     return;
8913   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8914     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
8915     return;
8916   }
8917   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8918     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
8919     return;
8920   }
8921   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8922     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
8923     return;
8924   }
8925 
8926   const ArrayType *AT = S.Context.getAsArrayType(PType);
8927   if (!AT)
8928     return;
8929 
8930   if (AT->getSizeModifier() != ArrayType::Star) {
8931     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
8932     return;
8933   }
8934 
8935   S.Diag(Loc, diag::err_array_star_in_function_definition);
8936 }
8937 
8938 /// CheckParmsForFunctionDef - Check that the parameters of the given
8939 /// function are appropriate for the definition of a function. This
8940 /// takes care of any checks that cannot be performed on the
8941 /// declaration itself, e.g., that the types of each of the function
8942 /// parameters are complete.
8943 bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
8944                                     ParmVarDecl *const *PEnd,
8945                                     bool CheckParameterNames) {
8946   bool HasInvalidParm = false;
8947   for (; P != PEnd; ++P) {
8948     ParmVarDecl *Param = *P;
8949 
8950     // C99 6.7.5.3p4: the parameters in a parameter type list in a
8951     // function declarator that is part of a function definition of
8952     // that function shall not have incomplete type.
8953     //
8954     // This is also C++ [dcl.fct]p6.
8955     if (!Param->isInvalidDecl() &&
8956         RequireCompleteType(Param->getLocation(), Param->getType(),
8957                             diag::err_typecheck_decl_incomplete_type)) {
8958       Param->setInvalidDecl();
8959       HasInvalidParm = true;
8960     }
8961 
8962     // C99 6.9.1p5: If the declarator includes a parameter type list, the
8963     // declaration of each parameter shall include an identifier.
8964     if (CheckParameterNames &&
8965         Param->getIdentifier() == nullptr &&
8966         !Param->isImplicit() &&
8967         !getLangOpts().CPlusPlus)
8968       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8969 
8970     // C99 6.7.5.3p12:
8971     //   If the function declarator is not part of a definition of that
8972     //   function, parameters may have incomplete type and may use the [*]
8973     //   notation in their sequences of declarator specifiers to specify
8974     //   variable length array types.
8975     QualType PType = Param->getOriginalType();
8976     // FIXME: This diagnostic should point the '[*]' if source-location
8977     // information is added for it.
8978     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
8979 
8980     // MSVC destroys objects passed by value in the callee.  Therefore a
8981     // function definition which takes such a parameter must be able to call the
8982     // object's destructor.  However, we don't perform any direct access check
8983     // on the dtor.
8984     if (getLangOpts().CPlusPlus && Context.getTargetInfo()
8985                                        .getCXXABI()
8986                                        .areArgsDestroyedLeftToRightInCallee()) {
8987       if (!Param->isInvalidDecl()) {
8988         if (const RecordType *RT = Param->getType()->getAs<RecordType>()) {
8989           CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8990           if (!ClassDecl->isInvalidDecl() &&
8991               !ClassDecl->hasIrrelevantDestructor() &&
8992               !ClassDecl->isDependentContext()) {
8993             CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
8994             MarkFunctionReferenced(Param->getLocation(), Destructor);
8995             DiagnoseUseOfDecl(Destructor, Param->getLocation());
8996           }
8997         }
8998       }
8999     }
9000 
9001     // Parameters with the pass_object_size attribute only need to be marked
9002     // constant at function definitions. Because we lack information about
9003     // whether we're on a declaration or definition when we're instantiating the
9004     // attribute, we need to check for constness here.
9005     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
9006       if (!Param->getType().isConstQualified())
9007         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
9008             << Attr->getSpelling() << 1;
9009   }
9010 
9011   return HasInvalidParm;
9012 }
9013 
9014 /// CheckCastAlign - Implements -Wcast-align, which warns when a
9015 /// pointer cast increases the alignment requirements.
9016 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
9017   // This is actually a lot of work to potentially be doing on every
9018   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
9019   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
9020     return;
9021 
9022   // Ignore dependent types.
9023   if (T->isDependentType() || Op->getType()->isDependentType())
9024     return;
9025 
9026   // Require that the destination be a pointer type.
9027   const PointerType *DestPtr = T->getAs<PointerType>();
9028   if (!DestPtr) return;
9029 
9030   // If the destination has alignment 1, we're done.
9031   QualType DestPointee = DestPtr->getPointeeType();
9032   if (DestPointee->isIncompleteType()) return;
9033   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
9034   if (DestAlign.isOne()) return;
9035 
9036   // Require that the source be a pointer type.
9037   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
9038   if (!SrcPtr) return;
9039   QualType SrcPointee = SrcPtr->getPointeeType();
9040 
9041   // Whitelist casts from cv void*.  We already implicitly
9042   // whitelisted casts to cv void*, since they have alignment 1.
9043   // Also whitelist casts involving incomplete types, which implicitly
9044   // includes 'void'.
9045   if (SrcPointee->isIncompleteType()) return;
9046 
9047   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
9048   if (SrcAlign >= DestAlign) return;
9049 
9050   Diag(TRange.getBegin(), diag::warn_cast_align)
9051     << Op->getType() << T
9052     << static_cast<unsigned>(SrcAlign.getQuantity())
9053     << static_cast<unsigned>(DestAlign.getQuantity())
9054     << TRange << Op->getSourceRange();
9055 }
9056 
9057 static const Type* getElementType(const Expr *BaseExpr) {
9058   const Type* EltType = BaseExpr->getType().getTypePtr();
9059   if (EltType->isAnyPointerType())
9060     return EltType->getPointeeType().getTypePtr();
9061   else if (EltType->isArrayType())
9062     return EltType->getBaseElementTypeUnsafe();
9063   return EltType;
9064 }
9065 
9066 /// \brief Check whether this array fits the idiom of a size-one tail padded
9067 /// array member of a struct.
9068 ///
9069 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
9070 /// commonly used to emulate flexible arrays in C89 code.
9071 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
9072                                     const NamedDecl *ND) {
9073   if (Size != 1 || !ND) return false;
9074 
9075   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
9076   if (!FD) return false;
9077 
9078   // Don't consider sizes resulting from macro expansions or template argument
9079   // substitution to form C89 tail-padded arrays.
9080 
9081   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
9082   while (TInfo) {
9083     TypeLoc TL = TInfo->getTypeLoc();
9084     // Look through typedefs.
9085     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
9086       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
9087       TInfo = TDL->getTypeSourceInfo();
9088       continue;
9089     }
9090     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
9091       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
9092       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
9093         return false;
9094     }
9095     break;
9096   }
9097 
9098   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
9099   if (!RD) return false;
9100   if (RD->isUnion()) return false;
9101   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9102     if (!CRD->isStandardLayout()) return false;
9103   }
9104 
9105   // See if this is the last field decl in the record.
9106   const Decl *D = FD;
9107   while ((D = D->getNextDeclInContext()))
9108     if (isa<FieldDecl>(D))
9109       return false;
9110   return true;
9111 }
9112 
9113 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
9114                             const ArraySubscriptExpr *ASE,
9115                             bool AllowOnePastEnd, bool IndexNegated) {
9116   IndexExpr = IndexExpr->IgnoreParenImpCasts();
9117   if (IndexExpr->isValueDependent())
9118     return;
9119 
9120   const Type *EffectiveType = getElementType(BaseExpr);
9121   BaseExpr = BaseExpr->IgnoreParenCasts();
9122   const ConstantArrayType *ArrayTy =
9123     Context.getAsConstantArrayType(BaseExpr->getType());
9124   if (!ArrayTy)
9125     return;
9126 
9127   llvm::APSInt index;
9128   if (!IndexExpr->EvaluateAsInt(index, Context, Expr::SE_AllowSideEffects))
9129     return;
9130   if (IndexNegated)
9131     index = -index;
9132 
9133   const NamedDecl *ND = nullptr;
9134   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9135     ND = dyn_cast<NamedDecl>(DRE->getDecl());
9136   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9137     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9138 
9139   if (index.isUnsigned() || !index.isNegative()) {
9140     llvm::APInt size = ArrayTy->getSize();
9141     if (!size.isStrictlyPositive())
9142       return;
9143 
9144     const Type* BaseType = getElementType(BaseExpr);
9145     if (BaseType != EffectiveType) {
9146       // Make sure we're comparing apples to apples when comparing index to size
9147       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
9148       uint64_t array_typesize = Context.getTypeSize(BaseType);
9149       // Handle ptrarith_typesize being zero, such as when casting to void*
9150       if (!ptrarith_typesize) ptrarith_typesize = 1;
9151       if (ptrarith_typesize != array_typesize) {
9152         // There's a cast to a different size type involved
9153         uint64_t ratio = array_typesize / ptrarith_typesize;
9154         // TODO: Be smarter about handling cases where array_typesize is not a
9155         // multiple of ptrarith_typesize
9156         if (ptrarith_typesize * ratio == array_typesize)
9157           size *= llvm::APInt(size.getBitWidth(), ratio);
9158       }
9159     }
9160 
9161     if (size.getBitWidth() > index.getBitWidth())
9162       index = index.zext(size.getBitWidth());
9163     else if (size.getBitWidth() < index.getBitWidth())
9164       size = size.zext(index.getBitWidth());
9165 
9166     // For array subscripting the index must be less than size, but for pointer
9167     // arithmetic also allow the index (offset) to be equal to size since
9168     // computing the next address after the end of the array is legal and
9169     // commonly done e.g. in C++ iterators and range-based for loops.
9170     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
9171       return;
9172 
9173     // Also don't warn for arrays of size 1 which are members of some
9174     // structure. These are often used to approximate flexible arrays in C89
9175     // code.
9176     if (IsTailPaddedMemberArray(*this, size, ND))
9177       return;
9178 
9179     // Suppress the warning if the subscript expression (as identified by the
9180     // ']' location) and the index expression are both from macro expansions
9181     // within a system header.
9182     if (ASE) {
9183       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
9184           ASE->getRBracketLoc());
9185       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
9186         SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
9187             IndexExpr->getLocStart());
9188         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
9189           return;
9190       }
9191     }
9192 
9193     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
9194     if (ASE)
9195       DiagID = diag::warn_array_index_exceeds_bounds;
9196 
9197     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9198                         PDiag(DiagID) << index.toString(10, true)
9199                           << size.toString(10, true)
9200                           << (unsigned)size.getLimitedValue(~0U)
9201                           << IndexExpr->getSourceRange());
9202   } else {
9203     unsigned DiagID = diag::warn_array_index_precedes_bounds;
9204     if (!ASE) {
9205       DiagID = diag::warn_ptr_arith_precedes_bounds;
9206       if (index.isNegative()) index = -index;
9207     }
9208 
9209     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
9210                         PDiag(DiagID) << index.toString(10, true)
9211                           << IndexExpr->getSourceRange());
9212   }
9213 
9214   if (!ND) {
9215     // Try harder to find a NamedDecl to point at in the note.
9216     while (const ArraySubscriptExpr *ASE =
9217            dyn_cast<ArraySubscriptExpr>(BaseExpr))
9218       BaseExpr = ASE->getBase()->IgnoreParenCasts();
9219     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
9220       ND = dyn_cast<NamedDecl>(DRE->getDecl());
9221     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
9222       ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
9223   }
9224 
9225   if (ND)
9226     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
9227                         PDiag(diag::note_array_index_out_of_bounds)
9228                           << ND->getDeclName());
9229 }
9230 
9231 void Sema::CheckArrayAccess(const Expr *expr) {
9232   int AllowOnePastEnd = 0;
9233   while (expr) {
9234     expr = expr->IgnoreParenImpCasts();
9235     switch (expr->getStmtClass()) {
9236       case Stmt::ArraySubscriptExprClass: {
9237         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
9238         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
9239                          AllowOnePastEnd > 0);
9240         return;
9241       }
9242       case Stmt::OMPArraySectionExprClass: {
9243         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
9244         if (ASE->getLowerBound())
9245           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
9246                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
9247         return;
9248       }
9249       case Stmt::UnaryOperatorClass: {
9250         // Only unwrap the * and & unary operators
9251         const UnaryOperator *UO = cast<UnaryOperator>(expr);
9252         expr = UO->getSubExpr();
9253         switch (UO->getOpcode()) {
9254           case UO_AddrOf:
9255             AllowOnePastEnd++;
9256             break;
9257           case UO_Deref:
9258             AllowOnePastEnd--;
9259             break;
9260           default:
9261             return;
9262         }
9263         break;
9264       }
9265       case Stmt::ConditionalOperatorClass: {
9266         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
9267         if (const Expr *lhs = cond->getLHS())
9268           CheckArrayAccess(lhs);
9269         if (const Expr *rhs = cond->getRHS())
9270           CheckArrayAccess(rhs);
9271         return;
9272       }
9273       default:
9274         return;
9275     }
9276   }
9277 }
9278 
9279 //===--- CHECK: Objective-C retain cycles ----------------------------------//
9280 
9281 namespace {
9282   struct RetainCycleOwner {
9283     RetainCycleOwner() : Variable(nullptr), Indirect(false) {}
9284     VarDecl *Variable;
9285     SourceRange Range;
9286     SourceLocation Loc;
9287     bool Indirect;
9288 
9289     void setLocsFrom(Expr *e) {
9290       Loc = e->getExprLoc();
9291       Range = e->getSourceRange();
9292     }
9293   };
9294 } // end anonymous namespace
9295 
9296 /// Consider whether capturing the given variable can possibly lead to
9297 /// a retain cycle.
9298 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
9299   // In ARC, it's captured strongly iff the variable has __strong
9300   // lifetime.  In MRR, it's captured strongly if the variable is
9301   // __block and has an appropriate type.
9302   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9303     return false;
9304 
9305   owner.Variable = var;
9306   if (ref)
9307     owner.setLocsFrom(ref);
9308   return true;
9309 }
9310 
9311 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
9312   while (true) {
9313     e = e->IgnoreParens();
9314     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
9315       switch (cast->getCastKind()) {
9316       case CK_BitCast:
9317       case CK_LValueBitCast:
9318       case CK_LValueToRValue:
9319       case CK_ARCReclaimReturnedObject:
9320         e = cast->getSubExpr();
9321         continue;
9322 
9323       default:
9324         return false;
9325       }
9326     }
9327 
9328     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
9329       ObjCIvarDecl *ivar = ref->getDecl();
9330       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
9331         return false;
9332 
9333       // Try to find a retain cycle in the base.
9334       if (!findRetainCycleOwner(S, ref->getBase(), owner))
9335         return false;
9336 
9337       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
9338       owner.Indirect = true;
9339       return true;
9340     }
9341 
9342     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
9343       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
9344       if (!var) return false;
9345       return considerVariable(var, ref, owner);
9346     }
9347 
9348     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
9349       if (member->isArrow()) return false;
9350 
9351       // Don't count this as an indirect ownership.
9352       e = member->getBase();
9353       continue;
9354     }
9355 
9356     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
9357       // Only pay attention to pseudo-objects on property references.
9358       ObjCPropertyRefExpr *pre
9359         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
9360                                               ->IgnoreParens());
9361       if (!pre) return false;
9362       if (pre->isImplicitProperty()) return false;
9363       ObjCPropertyDecl *property = pre->getExplicitProperty();
9364       if (!property->isRetaining() &&
9365           !(property->getPropertyIvarDecl() &&
9366             property->getPropertyIvarDecl()->getType()
9367               .getObjCLifetime() == Qualifiers::OCL_Strong))
9368           return false;
9369 
9370       owner.Indirect = true;
9371       if (pre->isSuperReceiver()) {
9372         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
9373         if (!owner.Variable)
9374           return false;
9375         owner.Loc = pre->getLocation();
9376         owner.Range = pre->getSourceRange();
9377         return true;
9378       }
9379       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
9380                               ->getSourceExpr());
9381       continue;
9382     }
9383 
9384     // Array ivars?
9385 
9386     return false;
9387   }
9388 }
9389 
9390 namespace {
9391   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
9392     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
9393       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
9394         Context(Context), Variable(variable), Capturer(nullptr),
9395         VarWillBeReased(false) {}
9396     ASTContext &Context;
9397     VarDecl *Variable;
9398     Expr *Capturer;
9399     bool VarWillBeReased;
9400 
9401     void VisitDeclRefExpr(DeclRefExpr *ref) {
9402       if (ref->getDecl() == Variable && !Capturer)
9403         Capturer = ref;
9404     }
9405 
9406     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
9407       if (Capturer) return;
9408       Visit(ref->getBase());
9409       if (Capturer && ref->isFreeIvar())
9410         Capturer = ref;
9411     }
9412 
9413     void VisitBlockExpr(BlockExpr *block) {
9414       // Look inside nested blocks
9415       if (block->getBlockDecl()->capturesVariable(Variable))
9416         Visit(block->getBlockDecl()->getBody());
9417     }
9418 
9419     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
9420       if (Capturer) return;
9421       if (OVE->getSourceExpr())
9422         Visit(OVE->getSourceExpr());
9423     }
9424     void VisitBinaryOperator(BinaryOperator *BinOp) {
9425       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
9426         return;
9427       Expr *LHS = BinOp->getLHS();
9428       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
9429         if (DRE->getDecl() != Variable)
9430           return;
9431         if (Expr *RHS = BinOp->getRHS()) {
9432           RHS = RHS->IgnoreParenCasts();
9433           llvm::APSInt Value;
9434           VarWillBeReased =
9435             (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
9436         }
9437       }
9438     }
9439   };
9440 } // end anonymous namespace
9441 
9442 /// Check whether the given argument is a block which captures a
9443 /// variable.
9444 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
9445   assert(owner.Variable && owner.Loc.isValid());
9446 
9447   e = e->IgnoreParenCasts();
9448 
9449   // Look through [^{...} copy] and Block_copy(^{...}).
9450   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
9451     Selector Cmd = ME->getSelector();
9452     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
9453       e = ME->getInstanceReceiver();
9454       if (!e)
9455         return nullptr;
9456       e = e->IgnoreParenCasts();
9457     }
9458   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
9459     if (CE->getNumArgs() == 1) {
9460       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
9461       if (Fn) {
9462         const IdentifierInfo *FnI = Fn->getIdentifier();
9463         if (FnI && FnI->isStr("_Block_copy")) {
9464           e = CE->getArg(0)->IgnoreParenCasts();
9465         }
9466       }
9467     }
9468   }
9469 
9470   BlockExpr *block = dyn_cast<BlockExpr>(e);
9471   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
9472     return nullptr;
9473 
9474   FindCaptureVisitor visitor(S.Context, owner.Variable);
9475   visitor.Visit(block->getBlockDecl()->getBody());
9476   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
9477 }
9478 
9479 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
9480                                 RetainCycleOwner &owner) {
9481   assert(capturer);
9482   assert(owner.Variable && owner.Loc.isValid());
9483 
9484   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
9485     << owner.Variable << capturer->getSourceRange();
9486   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
9487     << owner.Indirect << owner.Range;
9488 }
9489 
9490 /// Check for a keyword selector that starts with the word 'add' or
9491 /// 'set'.
9492 static bool isSetterLikeSelector(Selector sel) {
9493   if (sel.isUnarySelector()) return false;
9494 
9495   StringRef str = sel.getNameForSlot(0);
9496   while (!str.empty() && str.front() == '_') str = str.substr(1);
9497   if (str.startswith("set"))
9498     str = str.substr(3);
9499   else if (str.startswith("add")) {
9500     // Specially whitelist 'addOperationWithBlock:'.
9501     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
9502       return false;
9503     str = str.substr(3);
9504   }
9505   else
9506     return false;
9507 
9508   if (str.empty()) return true;
9509   return !isLowercase(str.front());
9510 }
9511 
9512 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
9513                                                     ObjCMessageExpr *Message) {
9514   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
9515                                                 Message->getReceiverInterface(),
9516                                                 NSAPI::ClassId_NSMutableArray);
9517   if (!IsMutableArray) {
9518     return None;
9519   }
9520 
9521   Selector Sel = Message->getSelector();
9522 
9523   Optional<NSAPI::NSArrayMethodKind> MKOpt =
9524     S.NSAPIObj->getNSArrayMethodKind(Sel);
9525   if (!MKOpt) {
9526     return None;
9527   }
9528 
9529   NSAPI::NSArrayMethodKind MK = *MKOpt;
9530 
9531   switch (MK) {
9532     case NSAPI::NSMutableArr_addObject:
9533     case NSAPI::NSMutableArr_insertObjectAtIndex:
9534     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
9535       return 0;
9536     case NSAPI::NSMutableArr_replaceObjectAtIndex:
9537       return 1;
9538 
9539     default:
9540       return None;
9541   }
9542 
9543   return None;
9544 }
9545 
9546 static
9547 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
9548                                                   ObjCMessageExpr *Message) {
9549   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
9550                                             Message->getReceiverInterface(),
9551                                             NSAPI::ClassId_NSMutableDictionary);
9552   if (!IsMutableDictionary) {
9553     return None;
9554   }
9555 
9556   Selector Sel = Message->getSelector();
9557 
9558   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
9559     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
9560   if (!MKOpt) {
9561     return None;
9562   }
9563 
9564   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
9565 
9566   switch (MK) {
9567     case NSAPI::NSMutableDict_setObjectForKey:
9568     case NSAPI::NSMutableDict_setValueForKey:
9569     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
9570       return 0;
9571 
9572     default:
9573       return None;
9574   }
9575 
9576   return None;
9577 }
9578 
9579 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
9580   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
9581                                                 Message->getReceiverInterface(),
9582                                                 NSAPI::ClassId_NSMutableSet);
9583 
9584   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
9585                                             Message->getReceiverInterface(),
9586                                             NSAPI::ClassId_NSMutableOrderedSet);
9587   if (!IsMutableSet && !IsMutableOrderedSet) {
9588     return None;
9589   }
9590 
9591   Selector Sel = Message->getSelector();
9592 
9593   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
9594   if (!MKOpt) {
9595     return None;
9596   }
9597 
9598   NSAPI::NSSetMethodKind MK = *MKOpt;
9599 
9600   switch (MK) {
9601     case NSAPI::NSMutableSet_addObject:
9602     case NSAPI::NSOrderedSet_setObjectAtIndex:
9603     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
9604     case NSAPI::NSOrderedSet_insertObjectAtIndex:
9605       return 0;
9606     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
9607       return 1;
9608   }
9609 
9610   return None;
9611 }
9612 
9613 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
9614   if (!Message->isInstanceMessage()) {
9615     return;
9616   }
9617 
9618   Optional<int> ArgOpt;
9619 
9620   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
9621       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
9622       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
9623     return;
9624   }
9625 
9626   int ArgIndex = *ArgOpt;
9627 
9628   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
9629   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
9630     Arg = OE->getSourceExpr()->IgnoreImpCasts();
9631   }
9632 
9633   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
9634     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9635       if (ArgRE->isObjCSelfExpr()) {
9636         Diag(Message->getSourceRange().getBegin(),
9637              diag::warn_objc_circular_container)
9638           << ArgRE->getDecl()->getName() << StringRef("super");
9639       }
9640     }
9641   } else {
9642     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
9643 
9644     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
9645       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
9646     }
9647 
9648     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9649       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9650         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9651           ValueDecl *Decl = ReceiverRE->getDecl();
9652           Diag(Message->getSourceRange().getBegin(),
9653                diag::warn_objc_circular_container)
9654             << Decl->getName() << Decl->getName();
9655           if (!ArgRE->isObjCSelfExpr()) {
9656             Diag(Decl->getLocation(),
9657                  diag::note_objc_circular_container_declared_here)
9658               << Decl->getName();
9659           }
9660         }
9661       }
9662     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9663       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
9664         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9665           ObjCIvarDecl *Decl = IvarRE->getDecl();
9666           Diag(Message->getSourceRange().getBegin(),
9667                diag::warn_objc_circular_container)
9668             << Decl->getName() << Decl->getName();
9669           Diag(Decl->getLocation(),
9670                diag::note_objc_circular_container_declared_here)
9671             << Decl->getName();
9672         }
9673       }
9674     }
9675   }
9676 }
9677 
9678 /// Check a message send to see if it's likely to cause a retain cycle.
9679 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
9680   // Only check instance methods whose selector looks like a setter.
9681   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
9682     return;
9683 
9684   // Try to find a variable that the receiver is strongly owned by.
9685   RetainCycleOwner owner;
9686   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
9687     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
9688       return;
9689   } else {
9690     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
9691     owner.Variable = getCurMethodDecl()->getSelfDecl();
9692     owner.Loc = msg->getSuperLoc();
9693     owner.Range = msg->getSuperLoc();
9694   }
9695 
9696   // Check whether the receiver is captured by any of the arguments.
9697   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
9698     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
9699       return diagnoseRetainCycle(*this, capturer, owner);
9700 }
9701 
9702 /// Check a property assign to see if it's likely to cause a retain cycle.
9703 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
9704   RetainCycleOwner owner;
9705   if (!findRetainCycleOwner(*this, receiver, owner))
9706     return;
9707 
9708   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
9709     diagnoseRetainCycle(*this, capturer, owner);
9710 }
9711 
9712 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
9713   RetainCycleOwner Owner;
9714   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
9715     return;
9716 
9717   // Because we don't have an expression for the variable, we have to set the
9718   // location explicitly here.
9719   Owner.Loc = Var->getLocation();
9720   Owner.Range = Var->getSourceRange();
9721 
9722   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
9723     diagnoseRetainCycle(*this, Capturer, Owner);
9724 }
9725 
9726 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
9727                                      Expr *RHS, bool isProperty) {
9728   // Check if RHS is an Objective-C object literal, which also can get
9729   // immediately zapped in a weak reference.  Note that we explicitly
9730   // allow ObjCStringLiterals, since those are designed to never really die.
9731   RHS = RHS->IgnoreParenImpCasts();
9732 
9733   // This enum needs to match with the 'select' in
9734   // warn_objc_arc_literal_assign (off-by-1).
9735   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
9736   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
9737     return false;
9738 
9739   S.Diag(Loc, diag::warn_arc_literal_assign)
9740     << (unsigned) Kind
9741     << (isProperty ? 0 : 1)
9742     << RHS->getSourceRange();
9743 
9744   return true;
9745 }
9746 
9747 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
9748                                     Qualifiers::ObjCLifetime LT,
9749                                     Expr *RHS, bool isProperty) {
9750   // Strip off any implicit cast added to get to the one ARC-specific.
9751   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9752     if (cast->getCastKind() == CK_ARCConsumeObject) {
9753       S.Diag(Loc, diag::warn_arc_retained_assign)
9754         << (LT == Qualifiers::OCL_ExplicitNone)
9755         << (isProperty ? 0 : 1)
9756         << RHS->getSourceRange();
9757       return true;
9758     }
9759     RHS = cast->getSubExpr();
9760   }
9761 
9762   if (LT == Qualifiers::OCL_Weak &&
9763       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
9764     return true;
9765 
9766   return false;
9767 }
9768 
9769 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
9770                               QualType LHS, Expr *RHS) {
9771   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
9772 
9773   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
9774     return false;
9775 
9776   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
9777     return true;
9778 
9779   return false;
9780 }
9781 
9782 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
9783                               Expr *LHS, Expr *RHS) {
9784   QualType LHSType;
9785   // PropertyRef on LHS type need be directly obtained from
9786   // its declaration as it has a PseudoType.
9787   ObjCPropertyRefExpr *PRE
9788     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
9789   if (PRE && !PRE->isImplicitProperty()) {
9790     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9791     if (PD)
9792       LHSType = PD->getType();
9793   }
9794 
9795   if (LHSType.isNull())
9796     LHSType = LHS->getType();
9797 
9798   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
9799 
9800   if (LT == Qualifiers::OCL_Weak) {
9801     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
9802       getCurFunction()->markSafeWeakUse(LHS);
9803   }
9804 
9805   if (checkUnsafeAssigns(Loc, LHSType, RHS))
9806     return;
9807 
9808   // FIXME. Check for other life times.
9809   if (LT != Qualifiers::OCL_None)
9810     return;
9811 
9812   if (PRE) {
9813     if (PRE->isImplicitProperty())
9814       return;
9815     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
9816     if (!PD)
9817       return;
9818 
9819     unsigned Attributes = PD->getPropertyAttributes();
9820     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
9821       // when 'assign' attribute was not explicitly specified
9822       // by user, ignore it and rely on property type itself
9823       // for lifetime info.
9824       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
9825       if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9826           LHSType->isObjCRetainableType())
9827         return;
9828 
9829       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
9830         if (cast->getCastKind() == CK_ARCConsumeObject) {
9831           Diag(Loc, diag::warn_arc_retained_property_assign)
9832           << RHS->getSourceRange();
9833           return;
9834         }
9835         RHS = cast->getSubExpr();
9836       }
9837     }
9838     else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
9839       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
9840         return;
9841     }
9842   }
9843 }
9844 
9845 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
9846 
9847 namespace {
9848 bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
9849                                  SourceLocation StmtLoc,
9850                                  const NullStmt *Body) {
9851   // Do not warn if the body is a macro that expands to nothing, e.g:
9852   //
9853   // #define CALL(x)
9854   // if (condition)
9855   //   CALL(0);
9856   //
9857   if (Body->hasLeadingEmptyMacro())
9858     return false;
9859 
9860   // Get line numbers of statement and body.
9861   bool StmtLineInvalid;
9862   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
9863                                                       &StmtLineInvalid);
9864   if (StmtLineInvalid)
9865     return false;
9866 
9867   bool BodyLineInvalid;
9868   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
9869                                                       &BodyLineInvalid);
9870   if (BodyLineInvalid)
9871     return false;
9872 
9873   // Warn if null statement and body are on the same line.
9874   if (StmtLine != BodyLine)
9875     return false;
9876 
9877   return true;
9878 }
9879 } // end anonymous namespace
9880 
9881 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
9882                                  const Stmt *Body,
9883                                  unsigned DiagID) {
9884   // Since this is a syntactic check, don't emit diagnostic for template
9885   // instantiations, this just adds noise.
9886   if (CurrentInstantiationScope)
9887     return;
9888 
9889   // The body should be a null statement.
9890   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9891   if (!NBody)
9892     return;
9893 
9894   // Do the usual checks.
9895   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9896     return;
9897 
9898   Diag(NBody->getSemiLoc(), DiagID);
9899   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9900 }
9901 
9902 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
9903                                  const Stmt *PossibleBody) {
9904   assert(!CurrentInstantiationScope); // Ensured by caller
9905 
9906   SourceLocation StmtLoc;
9907   const Stmt *Body;
9908   unsigned DiagID;
9909   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9910     StmtLoc = FS->getRParenLoc();
9911     Body = FS->getBody();
9912     DiagID = diag::warn_empty_for_body;
9913   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9914     StmtLoc = WS->getCond()->getSourceRange().getEnd();
9915     Body = WS->getBody();
9916     DiagID = diag::warn_empty_while_body;
9917   } else
9918     return; // Neither `for' nor `while'.
9919 
9920   // The body should be a null statement.
9921   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
9922   if (!NBody)
9923     return;
9924 
9925   // Skip expensive checks if diagnostic is disabled.
9926   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
9927     return;
9928 
9929   // Do the usual checks.
9930   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9931     return;
9932 
9933   // `for(...);' and `while(...);' are popular idioms, so in order to keep
9934   // noise level low, emit diagnostics only if for/while is followed by a
9935   // CompoundStmt, e.g.:
9936   //    for (int i = 0; i < n; i++);
9937   //    {
9938   //      a(i);
9939   //    }
9940   // or if for/while is followed by a statement with more indentation
9941   // than for/while itself:
9942   //    for (int i = 0; i < n; i++);
9943   //      a(i);
9944   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9945   if (!ProbableTypo) {
9946     bool BodyColInvalid;
9947     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
9948                              PossibleBody->getLocStart(),
9949                              &BodyColInvalid);
9950     if (BodyColInvalid)
9951       return;
9952 
9953     bool StmtColInvalid;
9954     unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
9955                              S->getLocStart(),
9956                              &StmtColInvalid);
9957     if (StmtColInvalid)
9958       return;
9959 
9960     if (BodyCol > StmtCol)
9961       ProbableTypo = true;
9962   }
9963 
9964   if (ProbableTypo) {
9965     Diag(NBody->getSemiLoc(), DiagID);
9966     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
9967   }
9968 }
9969 
9970 //===--- CHECK: Warn on self move with std::move. -------------------------===//
9971 
9972 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
9973 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
9974                              SourceLocation OpLoc) {
9975   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9976     return;
9977 
9978   if (!ActiveTemplateInstantiations.empty())
9979     return;
9980 
9981   // Strip parens and casts away.
9982   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9983   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9984 
9985   // Check for a call expression
9986   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
9987   if (!CE || CE->getNumArgs() != 1)
9988     return;
9989 
9990   // Check for a call to std::move
9991   const FunctionDecl *FD = CE->getDirectCallee();
9992   if (!FD || !FD->isInStdNamespace() || !FD->getIdentifier() ||
9993       !FD->getIdentifier()->isStr("move"))
9994     return;
9995 
9996   // Get argument from std::move
9997   RHSExpr = CE->getArg(0);
9998 
9999   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10000   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10001 
10002   // Two DeclRefExpr's, check that the decls are the same.
10003   if (LHSDeclRef && RHSDeclRef) {
10004     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10005       return;
10006     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10007         RHSDeclRef->getDecl()->getCanonicalDecl())
10008       return;
10009 
10010     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10011                                         << LHSExpr->getSourceRange()
10012                                         << RHSExpr->getSourceRange();
10013     return;
10014   }
10015 
10016   // Member variables require a different approach to check for self moves.
10017   // MemberExpr's are the same if every nested MemberExpr refers to the same
10018   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
10019   // the base Expr's are CXXThisExpr's.
10020   const Expr *LHSBase = LHSExpr;
10021   const Expr *RHSBase = RHSExpr;
10022   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
10023   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
10024   if (!LHSME || !RHSME)
10025     return;
10026 
10027   while (LHSME && RHSME) {
10028     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
10029         RHSME->getMemberDecl()->getCanonicalDecl())
10030       return;
10031 
10032     LHSBase = LHSME->getBase();
10033     RHSBase = RHSME->getBase();
10034     LHSME = dyn_cast<MemberExpr>(LHSBase);
10035     RHSME = dyn_cast<MemberExpr>(RHSBase);
10036   }
10037 
10038   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
10039   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
10040   if (LHSDeclRef && RHSDeclRef) {
10041     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
10042       return;
10043     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
10044         RHSDeclRef->getDecl()->getCanonicalDecl())
10045       return;
10046 
10047     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10048                                         << LHSExpr->getSourceRange()
10049                                         << RHSExpr->getSourceRange();
10050     return;
10051   }
10052 
10053   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
10054     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
10055                                         << LHSExpr->getSourceRange()
10056                                         << RHSExpr->getSourceRange();
10057 }
10058 
10059 //===--- Layout compatibility ----------------------------------------------//
10060 
10061 namespace {
10062 
10063 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
10064 
10065 /// \brief Check if two enumeration types are layout-compatible.
10066 bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
10067   // C++11 [dcl.enum] p8:
10068   // Two enumeration types are layout-compatible if they have the same
10069   // underlying type.
10070   return ED1->isComplete() && ED2->isComplete() &&
10071          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
10072 }
10073 
10074 /// \brief Check if two fields are layout-compatible.
10075 bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
10076   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
10077     return false;
10078 
10079   if (Field1->isBitField() != Field2->isBitField())
10080     return false;
10081 
10082   if (Field1->isBitField()) {
10083     // Make sure that the bit-fields are the same length.
10084     unsigned Bits1 = Field1->getBitWidthValue(C);
10085     unsigned Bits2 = Field2->getBitWidthValue(C);
10086 
10087     if (Bits1 != Bits2)
10088       return false;
10089   }
10090 
10091   return true;
10092 }
10093 
10094 /// \brief Check if two standard-layout structs are layout-compatible.
10095 /// (C++11 [class.mem] p17)
10096 bool isLayoutCompatibleStruct(ASTContext &C,
10097                               RecordDecl *RD1,
10098                               RecordDecl *RD2) {
10099   // If both records are C++ classes, check that base classes match.
10100   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
10101     // If one of records is a CXXRecordDecl we are in C++ mode,
10102     // thus the other one is a CXXRecordDecl, too.
10103     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
10104     // Check number of base classes.
10105     if (D1CXX->getNumBases() != D2CXX->getNumBases())
10106       return false;
10107 
10108     // Check the base classes.
10109     for (CXXRecordDecl::base_class_const_iterator
10110                Base1 = D1CXX->bases_begin(),
10111            BaseEnd1 = D1CXX->bases_end(),
10112               Base2 = D2CXX->bases_begin();
10113          Base1 != BaseEnd1;
10114          ++Base1, ++Base2) {
10115       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
10116         return false;
10117     }
10118   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
10119     // If only RD2 is a C++ class, it should have zero base classes.
10120     if (D2CXX->getNumBases() > 0)
10121       return false;
10122   }
10123 
10124   // Check the fields.
10125   RecordDecl::field_iterator Field2 = RD2->field_begin(),
10126                              Field2End = RD2->field_end(),
10127                              Field1 = RD1->field_begin(),
10128                              Field1End = RD1->field_end();
10129   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
10130     if (!isLayoutCompatible(C, *Field1, *Field2))
10131       return false;
10132   }
10133   if (Field1 != Field1End || Field2 != Field2End)
10134     return false;
10135 
10136   return true;
10137 }
10138 
10139 /// \brief Check if two standard-layout unions are layout-compatible.
10140 /// (C++11 [class.mem] p18)
10141 bool isLayoutCompatibleUnion(ASTContext &C,
10142                              RecordDecl *RD1,
10143                              RecordDecl *RD2) {
10144   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
10145   for (auto *Field2 : RD2->fields())
10146     UnmatchedFields.insert(Field2);
10147 
10148   for (auto *Field1 : RD1->fields()) {
10149     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
10150         I = UnmatchedFields.begin(),
10151         E = UnmatchedFields.end();
10152 
10153     for ( ; I != E; ++I) {
10154       if (isLayoutCompatible(C, Field1, *I)) {
10155         bool Result = UnmatchedFields.erase(*I);
10156         (void) Result;
10157         assert(Result);
10158         break;
10159       }
10160     }
10161     if (I == E)
10162       return false;
10163   }
10164 
10165   return UnmatchedFields.empty();
10166 }
10167 
10168 bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
10169   if (RD1->isUnion() != RD2->isUnion())
10170     return false;
10171 
10172   if (RD1->isUnion())
10173     return isLayoutCompatibleUnion(C, RD1, RD2);
10174   else
10175     return isLayoutCompatibleStruct(C, RD1, RD2);
10176 }
10177 
10178 /// \brief Check if two types are layout-compatible in C++11 sense.
10179 bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
10180   if (T1.isNull() || T2.isNull())
10181     return false;
10182 
10183   // C++11 [basic.types] p11:
10184   // If two types T1 and T2 are the same type, then T1 and T2 are
10185   // layout-compatible types.
10186   if (C.hasSameType(T1, T2))
10187     return true;
10188 
10189   T1 = T1.getCanonicalType().getUnqualifiedType();
10190   T2 = T2.getCanonicalType().getUnqualifiedType();
10191 
10192   const Type::TypeClass TC1 = T1->getTypeClass();
10193   const Type::TypeClass TC2 = T2->getTypeClass();
10194 
10195   if (TC1 != TC2)
10196     return false;
10197 
10198   if (TC1 == Type::Enum) {
10199     return isLayoutCompatible(C,
10200                               cast<EnumType>(T1)->getDecl(),
10201                               cast<EnumType>(T2)->getDecl());
10202   } else if (TC1 == Type::Record) {
10203     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
10204       return false;
10205 
10206     return isLayoutCompatible(C,
10207                               cast<RecordType>(T1)->getDecl(),
10208                               cast<RecordType>(T2)->getDecl());
10209   }
10210 
10211   return false;
10212 }
10213 } // end anonymous namespace
10214 
10215 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
10216 
10217 namespace {
10218 /// \brief Given a type tag expression find the type tag itself.
10219 ///
10220 /// \param TypeExpr Type tag expression, as it appears in user's code.
10221 ///
10222 /// \param VD Declaration of an identifier that appears in a type tag.
10223 ///
10224 /// \param MagicValue Type tag magic value.
10225 bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
10226                      const ValueDecl **VD, uint64_t *MagicValue) {
10227   while(true) {
10228     if (!TypeExpr)
10229       return false;
10230 
10231     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
10232 
10233     switch (TypeExpr->getStmtClass()) {
10234     case Stmt::UnaryOperatorClass: {
10235       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
10236       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
10237         TypeExpr = UO->getSubExpr();
10238         continue;
10239       }
10240       return false;
10241     }
10242 
10243     case Stmt::DeclRefExprClass: {
10244       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
10245       *VD = DRE->getDecl();
10246       return true;
10247     }
10248 
10249     case Stmt::IntegerLiteralClass: {
10250       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
10251       llvm::APInt MagicValueAPInt = IL->getValue();
10252       if (MagicValueAPInt.getActiveBits() <= 64) {
10253         *MagicValue = MagicValueAPInt.getZExtValue();
10254         return true;
10255       } else
10256         return false;
10257     }
10258 
10259     case Stmt::BinaryConditionalOperatorClass:
10260     case Stmt::ConditionalOperatorClass: {
10261       const AbstractConditionalOperator *ACO =
10262           cast<AbstractConditionalOperator>(TypeExpr);
10263       bool Result;
10264       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
10265         if (Result)
10266           TypeExpr = ACO->getTrueExpr();
10267         else
10268           TypeExpr = ACO->getFalseExpr();
10269         continue;
10270       }
10271       return false;
10272     }
10273 
10274     case Stmt::BinaryOperatorClass: {
10275       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
10276       if (BO->getOpcode() == BO_Comma) {
10277         TypeExpr = BO->getRHS();
10278         continue;
10279       }
10280       return false;
10281     }
10282 
10283     default:
10284       return false;
10285     }
10286   }
10287 }
10288 
10289 /// \brief Retrieve the C type corresponding to type tag TypeExpr.
10290 ///
10291 /// \param TypeExpr Expression that specifies a type tag.
10292 ///
10293 /// \param MagicValues Registered magic values.
10294 ///
10295 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
10296 ///        kind.
10297 ///
10298 /// \param TypeInfo Information about the corresponding C type.
10299 ///
10300 /// \returns true if the corresponding C type was found.
10301 bool GetMatchingCType(
10302         const IdentifierInfo *ArgumentKind,
10303         const Expr *TypeExpr, const ASTContext &Ctx,
10304         const llvm::DenseMap<Sema::TypeTagMagicValue,
10305                              Sema::TypeTagData> *MagicValues,
10306         bool &FoundWrongKind,
10307         Sema::TypeTagData &TypeInfo) {
10308   FoundWrongKind = false;
10309 
10310   // Variable declaration that has type_tag_for_datatype attribute.
10311   const ValueDecl *VD = nullptr;
10312 
10313   uint64_t MagicValue;
10314 
10315   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
10316     return false;
10317 
10318   if (VD) {
10319     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
10320       if (I->getArgumentKind() != ArgumentKind) {
10321         FoundWrongKind = true;
10322         return false;
10323       }
10324       TypeInfo.Type = I->getMatchingCType();
10325       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
10326       TypeInfo.MustBeNull = I->getMustBeNull();
10327       return true;
10328     }
10329     return false;
10330   }
10331 
10332   if (!MagicValues)
10333     return false;
10334 
10335   llvm::DenseMap<Sema::TypeTagMagicValue,
10336                  Sema::TypeTagData>::const_iterator I =
10337       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
10338   if (I == MagicValues->end())
10339     return false;
10340 
10341   TypeInfo = I->second;
10342   return true;
10343 }
10344 } // end anonymous namespace
10345 
10346 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
10347                                       uint64_t MagicValue, QualType Type,
10348                                       bool LayoutCompatible,
10349                                       bool MustBeNull) {
10350   if (!TypeTagForDatatypeMagicValues)
10351     TypeTagForDatatypeMagicValues.reset(
10352         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
10353 
10354   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
10355   (*TypeTagForDatatypeMagicValues)[Magic] =
10356       TypeTagData(Type, LayoutCompatible, MustBeNull);
10357 }
10358 
10359 namespace {
10360 bool IsSameCharType(QualType T1, QualType T2) {
10361   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
10362   if (!BT1)
10363     return false;
10364 
10365   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
10366   if (!BT2)
10367     return false;
10368 
10369   BuiltinType::Kind T1Kind = BT1->getKind();
10370   BuiltinType::Kind T2Kind = BT2->getKind();
10371 
10372   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
10373          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
10374          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
10375          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
10376 }
10377 } // end anonymous namespace
10378 
10379 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
10380                                     const Expr * const *ExprArgs) {
10381   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
10382   bool IsPointerAttr = Attr->getIsPointer();
10383 
10384   const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
10385   bool FoundWrongKind;
10386   TypeTagData TypeInfo;
10387   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
10388                         TypeTagForDatatypeMagicValues.get(),
10389                         FoundWrongKind, TypeInfo)) {
10390     if (FoundWrongKind)
10391       Diag(TypeTagExpr->getExprLoc(),
10392            diag::warn_type_tag_for_datatype_wrong_kind)
10393         << TypeTagExpr->getSourceRange();
10394     return;
10395   }
10396 
10397   const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
10398   if (IsPointerAttr) {
10399     // Skip implicit cast of pointer to `void *' (as a function argument).
10400     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
10401       if (ICE->getType()->isVoidPointerType() &&
10402           ICE->getCastKind() == CK_BitCast)
10403         ArgumentExpr = ICE->getSubExpr();
10404   }
10405   QualType ArgumentType = ArgumentExpr->getType();
10406 
10407   // Passing a `void*' pointer shouldn't trigger a warning.
10408   if (IsPointerAttr && ArgumentType->isVoidPointerType())
10409     return;
10410 
10411   if (TypeInfo.MustBeNull) {
10412     // Type tag with matching void type requires a null pointer.
10413     if (!ArgumentExpr->isNullPointerConstant(Context,
10414                                              Expr::NPC_ValueDependentIsNotNull)) {
10415       Diag(ArgumentExpr->getExprLoc(),
10416            diag::warn_type_safety_null_pointer_required)
10417           << ArgumentKind->getName()
10418           << ArgumentExpr->getSourceRange()
10419           << TypeTagExpr->getSourceRange();
10420     }
10421     return;
10422   }
10423 
10424   QualType RequiredType = TypeInfo.Type;
10425   if (IsPointerAttr)
10426     RequiredType = Context.getPointerType(RequiredType);
10427 
10428   bool mismatch = false;
10429   if (!TypeInfo.LayoutCompatible) {
10430     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
10431 
10432     // C++11 [basic.fundamental] p1:
10433     // Plain char, signed char, and unsigned char are three distinct types.
10434     //
10435     // But we treat plain `char' as equivalent to `signed char' or `unsigned
10436     // char' depending on the current char signedness mode.
10437     if (mismatch)
10438       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
10439                                            RequiredType->getPointeeType())) ||
10440           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
10441         mismatch = false;
10442   } else
10443     if (IsPointerAttr)
10444       mismatch = !isLayoutCompatible(Context,
10445                                      ArgumentType->getPointeeType(),
10446                                      RequiredType->getPointeeType());
10447     else
10448       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
10449 
10450   if (mismatch)
10451     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
10452         << ArgumentType << ArgumentKind
10453         << TypeInfo.LayoutCompatible << RequiredType
10454         << ArgumentExpr->getSourceRange()
10455         << TypeTagExpr->getSourceRange();
10456 }
10457