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