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