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