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/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Analysis/Analyses/FormatString.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "clang/Basic/TargetBuiltins.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include <limits>
39 using namespace clang;
40 using namespace sema;
41 
42 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43                                                     unsigned ByteNo) const {
44   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45                                PP.getLangOptions(), PP.getTargetInfo());
46 }
47 
48 
49 /// CheckablePrintfAttr - does a function call have a "printf" attribute
50 /// and arguments that merit checking?
51 bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52   if (Format->getType() == "printf") return true;
53   if (Format->getType() == "printf0") {
54     // printf0 allows null "format" string; if so don't check format/args
55     unsigned format_idx = Format->getFormatIdx() - 1;
56     // Does the index refer to the implicit object argument?
57     if (isa<CXXMemberCallExpr>(TheCall)) {
58       if (format_idx == 0)
59         return false;
60       --format_idx;
61     }
62     if (format_idx < TheCall->getNumArgs()) {
63       Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
64       if (!Format->isNullPointerConstant(Context,
65                                          Expr::NPC_ValueDependentIsNull))
66         return true;
67     }
68   }
69   return false;
70 }
71 
72 /// Checks that a call expression's argument count is the desired number.
73 /// This is useful when doing custom type-checking.  Returns true on error.
74 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75   unsigned argCount = call->getNumArgs();
76   if (argCount == desiredArgCount) return false;
77 
78   if (argCount < desiredArgCount)
79     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80         << 0 /*function call*/ << desiredArgCount << argCount
81         << call->getSourceRange();
82 
83   // Highlight all the excess arguments.
84   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85                     call->getArg(argCount - 1)->getLocEnd());
86 
87   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88     << 0 /*function call*/ << desiredArgCount << argCount
89     << call->getArg(1)->getSourceRange();
90 }
91 
92 /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93 /// annotation is a non wide string literal.
94 static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95   Arg = Arg->IgnoreParenCasts();
96   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97   if (!Literal || !Literal->isAscii()) {
98     S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99       << Arg->getSourceRange();
100     return true;
101   }
102   return false;
103 }
104 
105 ExprResult
106 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
107   ExprResult TheCallResult(Owned(TheCall));
108 
109   // Find out if any arguments are required to be integer constant expressions.
110   unsigned ICEArguments = 0;
111   ASTContext::GetBuiltinTypeError Error;
112   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113   if (Error != ASTContext::GE_None)
114     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
115 
116   // If any arguments are required to be ICE's, check and diagnose.
117   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118     // Skip arguments not required to be ICE's.
119     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120 
121     llvm::APSInt Result;
122     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123       return true;
124     ICEArguments &= ~(1 << ArgNo);
125   }
126 
127   switch (BuiltinID) {
128   case Builtin::BI__builtin___CFStringMakeConstantString:
129     assert(TheCall->getNumArgs() == 1 &&
130            "Wrong # arguments to builtin CFStringMakeConstantString");
131     if (CheckObjCString(TheCall->getArg(0)))
132       return ExprError();
133     break;
134   case Builtin::BI__builtin_stdarg_start:
135   case Builtin::BI__builtin_va_start:
136     if (SemaBuiltinVAStart(TheCall))
137       return ExprError();
138     break;
139   case Builtin::BI__builtin_isgreater:
140   case Builtin::BI__builtin_isgreaterequal:
141   case Builtin::BI__builtin_isless:
142   case Builtin::BI__builtin_islessequal:
143   case Builtin::BI__builtin_islessgreater:
144   case Builtin::BI__builtin_isunordered:
145     if (SemaBuiltinUnorderedCompare(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_fpclassify:
149     if (SemaBuiltinFPClassification(TheCall, 6))
150       return ExprError();
151     break;
152   case Builtin::BI__builtin_isfinite:
153   case Builtin::BI__builtin_isinf:
154   case Builtin::BI__builtin_isinf_sign:
155   case Builtin::BI__builtin_isnan:
156   case Builtin::BI__builtin_isnormal:
157     if (SemaBuiltinFPClassification(TheCall, 1))
158       return ExprError();
159     break;
160   case Builtin::BI__builtin_shufflevector:
161     return SemaBuiltinShuffleVector(TheCall);
162     // TheCall will be freed by the smart pointer here, but that's fine, since
163     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
164   case Builtin::BI__builtin_prefetch:
165     if (SemaBuiltinPrefetch(TheCall))
166       return ExprError();
167     break;
168   case Builtin::BI__builtin_object_size:
169     if (SemaBuiltinObjectSize(TheCall))
170       return ExprError();
171     break;
172   case Builtin::BI__builtin_longjmp:
173     if (SemaBuiltinLongjmp(TheCall))
174       return ExprError();
175     break;
176 
177   case Builtin::BI__builtin_classify_type:
178     if (checkArgCount(*this, TheCall, 1)) return true;
179     TheCall->setType(Context.IntTy);
180     break;
181   case Builtin::BI__builtin_constant_p:
182     if (checkArgCount(*this, TheCall, 1)) return true;
183     TheCall->setType(Context.IntTy);
184     break;
185   case Builtin::BI__sync_fetch_and_add:
186   case Builtin::BI__sync_fetch_and_sub:
187   case Builtin::BI__sync_fetch_and_or:
188   case Builtin::BI__sync_fetch_and_and:
189   case Builtin::BI__sync_fetch_and_xor:
190   case Builtin::BI__sync_add_and_fetch:
191   case Builtin::BI__sync_sub_and_fetch:
192   case Builtin::BI__sync_and_and_fetch:
193   case Builtin::BI__sync_or_and_fetch:
194   case Builtin::BI__sync_xor_and_fetch:
195   case Builtin::BI__sync_val_compare_and_swap:
196   case Builtin::BI__sync_bool_compare_and_swap:
197   case Builtin::BI__sync_lock_test_and_set:
198   case Builtin::BI__sync_lock_release:
199   case Builtin::BI__sync_swap:
200     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
201   case Builtin::BI__atomic_load:
202     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203   case Builtin::BI__atomic_store:
204     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205   case Builtin::BI__atomic_exchange:
206     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207   case Builtin::BI__atomic_compare_exchange_strong:
208     return SemaAtomicOpsOverloaded(move(TheCallResult),
209                                    AtomicExpr::CmpXchgStrong);
210   case Builtin::BI__atomic_compare_exchange_weak:
211     return SemaAtomicOpsOverloaded(move(TheCallResult),
212                                    AtomicExpr::CmpXchgWeak);
213   case Builtin::BI__atomic_fetch_add:
214     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215   case Builtin::BI__atomic_fetch_sub:
216     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217   case Builtin::BI__atomic_fetch_and:
218     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219   case Builtin::BI__atomic_fetch_or:
220     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221   case Builtin::BI__atomic_fetch_xor:
222     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
223   case Builtin::BI__builtin_annotation:
224     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225       return ExprError();
226     break;
227   }
228 
229   // Since the target specific builtins for each arch overlap, only check those
230   // of the arch we are compiling for.
231   if (BuiltinID >= Builtin::FirstTSBuiltin) {
232     switch (Context.getTargetInfo().getTriple().getArch()) {
233       case llvm::Triple::arm:
234       case llvm::Triple::thumb:
235         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236           return ExprError();
237         break;
238       default:
239         break;
240     }
241   }
242 
243   return move(TheCallResult);
244 }
245 
246 // Get the valid immediate range for the specified NEON type code.
247 static unsigned RFT(unsigned t, bool shift = false) {
248   NeonTypeFlags Type(t);
249   int IsQuad = Type.isQuad();
250   switch (Type.getEltType()) {
251   case NeonTypeFlags::Int8:
252   case NeonTypeFlags::Poly8:
253     return shift ? 7 : (8 << IsQuad) - 1;
254   case NeonTypeFlags::Int16:
255   case NeonTypeFlags::Poly16:
256     return shift ? 15 : (4 << IsQuad) - 1;
257   case NeonTypeFlags::Int32:
258     return shift ? 31 : (2 << IsQuad) - 1;
259   case NeonTypeFlags::Int64:
260     return shift ? 63 : (1 << IsQuad) - 1;
261   case NeonTypeFlags::Float16:
262     assert(!shift && "cannot shift float types!");
263     return (4 << IsQuad) - 1;
264   case NeonTypeFlags::Float32:
265     assert(!shift && "cannot shift float types!");
266     return (2 << IsQuad) - 1;
267   }
268   return 0;
269 }
270 
271 /// getNeonEltType - Return the QualType corresponding to the elements of
272 /// the vector type specified by the NeonTypeFlags.  This is used to check
273 /// the pointer arguments for Neon load/store intrinsics.
274 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
275   switch (Flags.getEltType()) {
276   case NeonTypeFlags::Int8:
277     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
278   case NeonTypeFlags::Int16:
279     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
280   case NeonTypeFlags::Int32:
281     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
282   case NeonTypeFlags::Int64:
283     return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
284   case NeonTypeFlags::Poly8:
285     return Context.SignedCharTy;
286   case NeonTypeFlags::Poly16:
287     return Context.ShortTy;
288   case NeonTypeFlags::Float16:
289     return Context.UnsignedShortTy;
290   case NeonTypeFlags::Float32:
291     return Context.FloatTy;
292   }
293   return QualType();
294 }
295 
296 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
297   llvm::APSInt Result;
298 
299   unsigned mask = 0;
300   unsigned TV = 0;
301   bool HasPtr = false;
302   bool HasConstPtr = false;
303   switch (BuiltinID) {
304 #define GET_NEON_OVERLOAD_CHECK
305 #include "clang/Basic/arm_neon.inc"
306 #undef GET_NEON_OVERLOAD_CHECK
307   }
308 
309   // For NEON intrinsics which are overloaded on vector element type, validate
310   // the immediate which specifies which variant to emit.
311   unsigned ImmArg = TheCall->getNumArgs()-1;
312   if (mask) {
313     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
314       return true;
315 
316     TV = Result.getLimitedValue(64);
317     if ((TV > 63) || (mask & (1 << TV)) == 0)
318       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
319         << TheCall->getArg(ImmArg)->getSourceRange();
320   }
321 
322   if (HasPtr || HasConstPtr) {
323     // Check that pointer arguments have the specified type.
324     for (unsigned ArgNo = 0; ArgNo < ImmArg; ++ArgNo) {
325       Expr *Arg = TheCall->getArg(ArgNo);
326       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
327         Arg = ICE->getSubExpr();
328       ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
329       QualType RHSTy = RHS.get()->getType();
330       if (!RHSTy->isPointerType())
331         continue;
332       QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
333       if (HasConstPtr)
334         EltTy = EltTy.withConst();
335       QualType LHSTy = Context.getPointerType(EltTy);
336       AssignConvertType ConvTy;
337       ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
338       if (RHS.isInvalid())
339         return true;
340       if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
341                                    RHS.get(), AA_Assigning))
342         return true;
343     }
344   }
345 
346   // For NEON intrinsics which take an immediate value as part of the
347   // instruction, range check them here.
348   unsigned i = 0, l = 0, u = 0;
349   switch (BuiltinID) {
350   default: return false;
351   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
352   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
353   case ARM::BI__builtin_arm_vcvtr_f:
354   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
355 #define GET_NEON_IMMEDIATE_CHECK
356 #include "clang/Basic/arm_neon.inc"
357 #undef GET_NEON_IMMEDIATE_CHECK
358   };
359 
360   // Check that the immediate argument is actually a constant.
361   if (SemaBuiltinConstantArg(TheCall, i, Result))
362     return true;
363 
364   // Range check against the upper/lower values for this isntruction.
365   unsigned Val = Result.getZExtValue();
366   if (Val < l || Val > (u + l))
367     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
368       << l << u+l << TheCall->getArg(i)->getSourceRange();
369 
370   // FIXME: VFP Intrinsics should error if VFP not present.
371   return false;
372 }
373 
374 /// CheckFunctionCall - Check a direct function call for various correctness
375 /// and safety properties not strictly enforced by the C type system.
376 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
377   // Get the IdentifierInfo* for the called function.
378   IdentifierInfo *FnInfo = FDecl->getIdentifier();
379 
380   // None of the checks below are needed for functions that don't have
381   // simple names (e.g., C++ conversion functions).
382   if (!FnInfo)
383     return false;
384 
385   // FIXME: This mechanism should be abstracted to be less fragile and
386   // more efficient. For example, just map function ids to custom
387   // handlers.
388 
389   // Printf and scanf checking.
390   for (specific_attr_iterator<FormatAttr>
391          i = FDecl->specific_attr_begin<FormatAttr>(),
392          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
393 
394     const FormatAttr *Format = *i;
395     const bool b = Format->getType() == "scanf";
396     if (b || CheckablePrintfAttr(Format, TheCall)) {
397       bool HasVAListArg = Format->getFirstArg() == 0;
398       CheckPrintfScanfArguments(TheCall, HasVAListArg,
399                                 Format->getFormatIdx() - 1,
400                                 HasVAListArg ? 0 : Format->getFirstArg() - 1,
401                                 !b);
402     }
403   }
404 
405   for (specific_attr_iterator<NonNullAttr>
406          i = FDecl->specific_attr_begin<NonNullAttr>(),
407          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
408     CheckNonNullArguments(*i, TheCall->getArgs(),
409                           TheCall->getCallee()->getLocStart());
410   }
411 
412   // Builtin handling
413   int CMF = -1;
414   switch (FDecl->getBuiltinID()) {
415   case Builtin::BI__builtin_memset:
416   case Builtin::BI__builtin___memset_chk:
417   case Builtin::BImemset:
418     CMF = CMF_Memset;
419     break;
420 
421   case Builtin::BI__builtin_memcpy:
422   case Builtin::BI__builtin___memcpy_chk:
423   case Builtin::BImemcpy:
424     CMF = CMF_Memcpy;
425     break;
426 
427   case Builtin::BI__builtin_memmove:
428   case Builtin::BI__builtin___memmove_chk:
429   case Builtin::BImemmove:
430     CMF = CMF_Memmove;
431     break;
432 
433   case Builtin::BIstrlcpy:
434   case Builtin::BIstrlcat:
435     CheckStrlcpycatArguments(TheCall, FnInfo);
436     break;
437 
438   case Builtin::BI__builtin_memcmp:
439     CMF = CMF_Memcmp;
440     break;
441 
442   case Builtin::BI__builtin_strncpy:
443   case Builtin::BI__builtin___strncpy_chk:
444   case Builtin::BIstrncpy:
445     CMF = CMF_Strncpy;
446     break;
447 
448   case Builtin::BI__builtin_strncmp:
449     CMF = CMF_Strncmp;
450     break;
451 
452   case Builtin::BI__builtin_strncasecmp:
453     CMF = CMF_Strncasecmp;
454     break;
455 
456   case Builtin::BI__builtin_strncat:
457   case Builtin::BIstrncat:
458     CMF = CMF_Strncat;
459     break;
460 
461   case Builtin::BI__builtin_strndup:
462   case Builtin::BIstrndup:
463     CMF = CMF_Strndup;
464     break;
465 
466   default:
467     if (FDecl->getLinkage() == ExternalLinkage &&
468         (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
469       if (FnInfo->isStr("memset"))
470         CMF = CMF_Memset;
471       else if (FnInfo->isStr("memcpy"))
472         CMF = CMF_Memcpy;
473       else if (FnInfo->isStr("memmove"))
474         CMF = CMF_Memmove;
475       else if (FnInfo->isStr("memcmp"))
476         CMF = CMF_Memcmp;
477       else if (FnInfo->isStr("strncpy"))
478         CMF = CMF_Strncpy;
479       else if (FnInfo->isStr("strncmp"))
480         CMF = CMF_Strncmp;
481       else if (FnInfo->isStr("strncasecmp"))
482         CMF = CMF_Strncasecmp;
483       else if (FnInfo->isStr("strncat"))
484         CMF = CMF_Strncat;
485       else if (FnInfo->isStr("strndup"))
486         CMF = CMF_Strndup;
487     }
488     break;
489   }
490 
491   // Memset/memcpy/memmove handling
492   if (CMF != -1)
493     CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
494 
495   return false;
496 }
497 
498 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
499   // Printf checking.
500   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
501   if (!Format)
502     return false;
503 
504   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505   if (!V)
506     return false;
507 
508   QualType Ty = V->getType();
509   if (!Ty->isBlockPointerType())
510     return false;
511 
512   const bool b = Format->getType() == "scanf";
513   if (!b && !CheckablePrintfAttr(Format, TheCall))
514     return false;
515 
516   bool HasVAListArg = Format->getFirstArg() == 0;
517   CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518                             HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
519 
520   return false;
521 }
522 
523 ExprResult
524 Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
527 
528   // All these operations take one of the following four forms:
529   // T   __atomic_load(_Atomic(T)*, int)                              (loads)
530   // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
531   // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532   //                                                                (cmpxchg)
533   // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
534   // where T is an appropriate type, and the int paremeterss are for orderings.
535   unsigned NumVals = 1;
536   unsigned NumOrders = 1;
537   if (Op == AtomicExpr::Load) {
538     NumVals = 0;
539   } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540     NumVals = 2;
541     NumOrders = 2;
542   }
543 
544   if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
545     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
546       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
547       << TheCall->getCallee()->getSourceRange();
548     return ExprError();
549   } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
550     Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
551          diag::err_typecheck_call_too_many_args)
552       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
553       << TheCall->getCallee()->getSourceRange();
554     return ExprError();
555   }
556 
557   // Inspect the first argument of the atomic operation.  This should always be
558   // a pointer to an _Atomic type.
559   Expr *Ptr = TheCall->getArg(0);
560   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
561   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
562   if (!pointerType) {
563     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
564       << Ptr->getType() << Ptr->getSourceRange();
565     return ExprError();
566   }
567 
568   QualType AtomTy = pointerType->getPointeeType();
569   if (!AtomTy->isAtomicType()) {
570     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
571       << Ptr->getType() << Ptr->getSourceRange();
572     return ExprError();
573   }
574   QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
575 
576   if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
577       !ValType->isIntegerType() && !ValType->isPointerType()) {
578     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
579       << Ptr->getType() << Ptr->getSourceRange();
580     return ExprError();
581   }
582 
583   if (!ValType->isIntegerType() &&
584       (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
585     Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
586       << Ptr->getType() << Ptr->getSourceRange();
587     return ExprError();
588   }
589 
590   switch (ValType.getObjCLifetime()) {
591   case Qualifiers::OCL_None:
592   case Qualifiers::OCL_ExplicitNone:
593     // okay
594     break;
595 
596   case Qualifiers::OCL_Weak:
597   case Qualifiers::OCL_Strong:
598   case Qualifiers::OCL_Autoreleasing:
599     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
600       << ValType << Ptr->getSourceRange();
601     return ExprError();
602   }
603 
604   QualType ResultType = ValType;
605   if (Op == AtomicExpr::Store)
606     ResultType = Context.VoidTy;
607   else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
608     ResultType = Context.BoolTy;
609 
610   // The first argument --- the pointer --- has a fixed type; we
611   // deduce the types of the rest of the arguments accordingly.  Walk
612   // the remaining arguments, converting them to the deduced value type.
613   for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
614     ExprResult Arg = TheCall->getArg(i);
615     QualType Ty;
616     if (i < NumVals+1) {
617       // The second argument to a cmpxchg is a pointer to the data which will
618       // be exchanged. The second argument to a pointer add/subtract is the
619       // amount to add/subtract, which must be a ptrdiff_t.  The third
620       // argument to a cmpxchg and the second argument in all other cases
621       // is the type of the value.
622       if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
623                      Op == AtomicExpr::CmpXchgStrong))
624          Ty = Context.getPointerType(ValType.getUnqualifiedType());
625       else if (!ValType->isIntegerType() &&
626                (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
627         Ty = Context.getPointerDiffType();
628       else
629         Ty = ValType;
630     } else {
631       // The order(s) are always converted to int.
632       Ty = Context.IntTy;
633     }
634     InitializedEntity Entity =
635         InitializedEntity::InitializeParameter(Context, Ty, false);
636     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
637     if (Arg.isInvalid())
638       return true;
639     TheCall->setArg(i, Arg.get());
640   }
641 
642   SmallVector<Expr*, 5> SubExprs;
643   SubExprs.push_back(Ptr);
644   if (Op == AtomicExpr::Load) {
645     SubExprs.push_back(TheCall->getArg(1)); // Order
646   } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
647     SubExprs.push_back(TheCall->getArg(2)); // Order
648     SubExprs.push_back(TheCall->getArg(1)); // Val1
649   } else {
650     SubExprs.push_back(TheCall->getArg(3)); // Order
651     SubExprs.push_back(TheCall->getArg(1)); // Val1
652     SubExprs.push_back(TheCall->getArg(2)); // Val2
653     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
654   }
655 
656   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
657                                         SubExprs.data(), SubExprs.size(),
658                                         ResultType, Op,
659                                         TheCall->getRParenLoc()));
660 }
661 
662 
663 /// checkBuiltinArgument - Given a call to a builtin function, perform
664 /// normal type-checking on the given argument, updating the call in
665 /// place.  This is useful when a builtin function requires custom
666 /// type-checking for some of its arguments but not necessarily all of
667 /// them.
668 ///
669 /// Returns true on error.
670 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
671   FunctionDecl *Fn = E->getDirectCallee();
672   assert(Fn && "builtin call without direct callee!");
673 
674   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
675   InitializedEntity Entity =
676     InitializedEntity::InitializeParameter(S.Context, Param);
677 
678   ExprResult Arg = E->getArg(0);
679   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
680   if (Arg.isInvalid())
681     return true;
682 
683   E->setArg(ArgIndex, Arg.take());
684   return false;
685 }
686 
687 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
688 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
689 /// type of its first argument.  The main ActOnCallExpr routines have already
690 /// promoted the types of arguments because all of these calls are prototyped as
691 /// void(...).
692 ///
693 /// This function goes through and does final semantic checking for these
694 /// builtins,
695 ExprResult
696 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
697   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
698   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
699   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
700 
701   // Ensure that we have at least one argument to do type inference from.
702   if (TheCall->getNumArgs() < 1) {
703     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
704       << 0 << 1 << TheCall->getNumArgs()
705       << TheCall->getCallee()->getSourceRange();
706     return ExprError();
707   }
708 
709   // Inspect the first argument of the atomic builtin.  This should always be
710   // a pointer type, whose element is an integral scalar or pointer type.
711   // Because it is a pointer type, we don't have to worry about any implicit
712   // casts here.
713   // FIXME: We don't allow floating point scalars as input.
714   Expr *FirstArg = TheCall->getArg(0);
715   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
716   if (!pointerType) {
717     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
718       << FirstArg->getType() << FirstArg->getSourceRange();
719     return ExprError();
720   }
721 
722   QualType ValType = pointerType->getPointeeType();
723   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
724       !ValType->isBlockPointerType()) {
725     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
726       << FirstArg->getType() << FirstArg->getSourceRange();
727     return ExprError();
728   }
729 
730   switch (ValType.getObjCLifetime()) {
731   case Qualifiers::OCL_None:
732   case Qualifiers::OCL_ExplicitNone:
733     // okay
734     break;
735 
736   case Qualifiers::OCL_Weak:
737   case Qualifiers::OCL_Strong:
738   case Qualifiers::OCL_Autoreleasing:
739     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
740       << ValType << FirstArg->getSourceRange();
741     return ExprError();
742   }
743 
744   // Strip any qualifiers off ValType.
745   ValType = ValType.getUnqualifiedType();
746 
747   // The majority of builtins return a value, but a few have special return
748   // types, so allow them to override appropriately below.
749   QualType ResultType = ValType;
750 
751   // We need to figure out which concrete builtin this maps onto.  For example,
752   // __sync_fetch_and_add with a 2 byte object turns into
753   // __sync_fetch_and_add_2.
754 #define BUILTIN_ROW(x) \
755   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
756     Builtin::BI##x##_8, Builtin::BI##x##_16 }
757 
758   static const unsigned BuiltinIndices[][5] = {
759     BUILTIN_ROW(__sync_fetch_and_add),
760     BUILTIN_ROW(__sync_fetch_and_sub),
761     BUILTIN_ROW(__sync_fetch_and_or),
762     BUILTIN_ROW(__sync_fetch_and_and),
763     BUILTIN_ROW(__sync_fetch_and_xor),
764 
765     BUILTIN_ROW(__sync_add_and_fetch),
766     BUILTIN_ROW(__sync_sub_and_fetch),
767     BUILTIN_ROW(__sync_and_and_fetch),
768     BUILTIN_ROW(__sync_or_and_fetch),
769     BUILTIN_ROW(__sync_xor_and_fetch),
770 
771     BUILTIN_ROW(__sync_val_compare_and_swap),
772     BUILTIN_ROW(__sync_bool_compare_and_swap),
773     BUILTIN_ROW(__sync_lock_test_and_set),
774     BUILTIN_ROW(__sync_lock_release),
775     BUILTIN_ROW(__sync_swap)
776   };
777 #undef BUILTIN_ROW
778 
779   // Determine the index of the size.
780   unsigned SizeIndex;
781   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
782   case 1: SizeIndex = 0; break;
783   case 2: SizeIndex = 1; break;
784   case 4: SizeIndex = 2; break;
785   case 8: SizeIndex = 3; break;
786   case 16: SizeIndex = 4; break;
787   default:
788     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
789       << FirstArg->getType() << FirstArg->getSourceRange();
790     return ExprError();
791   }
792 
793   // Each of these builtins has one pointer argument, followed by some number of
794   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
795   // that we ignore.  Find out which row of BuiltinIndices to read from as well
796   // as the number of fixed args.
797   unsigned BuiltinID = FDecl->getBuiltinID();
798   unsigned BuiltinIndex, NumFixed = 1;
799   switch (BuiltinID) {
800   default: llvm_unreachable("Unknown overloaded atomic builtin!");
801   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
802   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
803   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
804   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
805   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
806 
807   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
808   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
809   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
810   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
811   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
812 
813   case Builtin::BI__sync_val_compare_and_swap:
814     BuiltinIndex = 10;
815     NumFixed = 2;
816     break;
817   case Builtin::BI__sync_bool_compare_and_swap:
818     BuiltinIndex = 11;
819     NumFixed = 2;
820     ResultType = Context.BoolTy;
821     break;
822   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
823   case Builtin::BI__sync_lock_release:
824     BuiltinIndex = 13;
825     NumFixed = 0;
826     ResultType = Context.VoidTy;
827     break;
828   case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
829   }
830 
831   // Now that we know how many fixed arguments we expect, first check that we
832   // have at least that many.
833   if (TheCall->getNumArgs() < 1+NumFixed) {
834     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835       << 0 << 1+NumFixed << TheCall->getNumArgs()
836       << TheCall->getCallee()->getSourceRange();
837     return ExprError();
838   }
839 
840   // Get the decl for the concrete builtin from this, we can tell what the
841   // concrete integer type we should convert to is.
842   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
843   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
844   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
845   FunctionDecl *NewBuiltinDecl =
846     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
847                                            TUScope, false, DRE->getLocStart()));
848 
849   // The first argument --- the pointer --- has a fixed type; we
850   // deduce the types of the rest of the arguments accordingly.  Walk
851   // the remaining arguments, converting them to the deduced value type.
852   for (unsigned i = 0; i != NumFixed; ++i) {
853     ExprResult Arg = TheCall->getArg(i+1);
854 
855     // GCC does an implicit conversion to the pointer or integer ValType.  This
856     // can fail in some cases (1i -> int**), check for this error case now.
857     // Initialize the argument.
858     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
859                                                    ValType, /*consume*/ false);
860     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
861     if (Arg.isInvalid())
862       return ExprError();
863 
864     // Okay, we have something that *can* be converted to the right type.  Check
865     // to see if there is a potentially weird extension going on here.  This can
866     // happen when you do an atomic operation on something like an char* and
867     // pass in 42.  The 42 gets converted to char.  This is even more strange
868     // for things like 45.123 -> char, etc.
869     // FIXME: Do this check.
870     TheCall->setArg(i+1, Arg.take());
871   }
872 
873   ASTContext& Context = this->getASTContext();
874 
875   // Create a new DeclRefExpr to refer to the new decl.
876   DeclRefExpr* NewDRE = DeclRefExpr::Create(
877       Context,
878       DRE->getQualifierLoc(),
879       NewBuiltinDecl,
880       DRE->getLocation(),
881       NewBuiltinDecl->getType(),
882       DRE->getValueKind());
883 
884   // Set the callee in the CallExpr.
885   // FIXME: This leaks the original parens and implicit casts.
886   ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
887   if (PromotedCall.isInvalid())
888     return ExprError();
889   TheCall->setCallee(PromotedCall.take());
890 
891   // Change the result type of the call to match the original value type. This
892   // is arbitrary, but the codegen for these builtins ins design to handle it
893   // gracefully.
894   TheCall->setType(ResultType);
895 
896   return move(TheCallResult);
897 }
898 
899 /// CheckObjCString - Checks that the argument to the builtin
900 /// CFString constructor is correct
901 /// Note: It might also make sense to do the UTF-16 conversion here (would
902 /// simplify the backend).
903 bool Sema::CheckObjCString(Expr *Arg) {
904   Arg = Arg->IgnoreParenCasts();
905   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
906 
907   if (!Literal || !Literal->isAscii()) {
908     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
909       << Arg->getSourceRange();
910     return true;
911   }
912 
913   if (Literal->containsNonAsciiOrNull()) {
914     StringRef String = Literal->getString();
915     unsigned NumBytes = String.size();
916     SmallVector<UTF16, 128> ToBuf(NumBytes);
917     const UTF8 *FromPtr = (UTF8 *)String.data();
918     UTF16 *ToPtr = &ToBuf[0];
919 
920     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
921                                                  &ToPtr, ToPtr + NumBytes,
922                                                  strictConversion);
923     // Check for conversion failure.
924     if (Result != conversionOK)
925       Diag(Arg->getLocStart(),
926            diag::warn_cfstring_truncated) << Arg->getSourceRange();
927   }
928   return false;
929 }
930 
931 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
932 /// Emit an error and return true on failure, return false on success.
933 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
934   Expr *Fn = TheCall->getCallee();
935   if (TheCall->getNumArgs() > 2) {
936     Diag(TheCall->getArg(2)->getLocStart(),
937          diag::err_typecheck_call_too_many_args)
938       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
939       << Fn->getSourceRange()
940       << SourceRange(TheCall->getArg(2)->getLocStart(),
941                      (*(TheCall->arg_end()-1))->getLocEnd());
942     return true;
943   }
944 
945   if (TheCall->getNumArgs() < 2) {
946     return Diag(TheCall->getLocEnd(),
947       diag::err_typecheck_call_too_few_args_at_least)
948       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
949   }
950 
951   // Type-check the first argument normally.
952   if (checkBuiltinArgument(*this, TheCall, 0))
953     return true;
954 
955   // Determine whether the current function is variadic or not.
956   BlockScopeInfo *CurBlock = getCurBlock();
957   bool isVariadic;
958   if (CurBlock)
959     isVariadic = CurBlock->TheDecl->isVariadic();
960   else if (FunctionDecl *FD = getCurFunctionDecl())
961     isVariadic = FD->isVariadic();
962   else
963     isVariadic = getCurMethodDecl()->isVariadic();
964 
965   if (!isVariadic) {
966     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
967     return true;
968   }
969 
970   // Verify that the second argument to the builtin is the last argument of the
971   // current function or method.
972   bool SecondArgIsLastNamedArgument = false;
973   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
974 
975   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
976     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
977       // FIXME: This isn't correct for methods (results in bogus warning).
978       // Get the last formal in the current function.
979       const ParmVarDecl *LastArg;
980       if (CurBlock)
981         LastArg = *(CurBlock->TheDecl->param_end()-1);
982       else if (FunctionDecl *FD = getCurFunctionDecl())
983         LastArg = *(FD->param_end()-1);
984       else
985         LastArg = *(getCurMethodDecl()->param_end()-1);
986       SecondArgIsLastNamedArgument = PV == LastArg;
987     }
988   }
989 
990   if (!SecondArgIsLastNamedArgument)
991     Diag(TheCall->getArg(1)->getLocStart(),
992          diag::warn_second_parameter_of_va_start_not_last_named_argument);
993   return false;
994 }
995 
996 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
997 /// friends.  This is declared to take (...), so we have to check everything.
998 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
999   if (TheCall->getNumArgs() < 2)
1000     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1001       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1002   if (TheCall->getNumArgs() > 2)
1003     return Diag(TheCall->getArg(2)->getLocStart(),
1004                 diag::err_typecheck_call_too_many_args)
1005       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1006       << SourceRange(TheCall->getArg(2)->getLocStart(),
1007                      (*(TheCall->arg_end()-1))->getLocEnd());
1008 
1009   ExprResult OrigArg0 = TheCall->getArg(0);
1010   ExprResult OrigArg1 = TheCall->getArg(1);
1011 
1012   // Do standard promotions between the two arguments, returning their common
1013   // type.
1014   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1015   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1016     return true;
1017 
1018   // Make sure any conversions are pushed back into the call; this is
1019   // type safe since unordered compare builtins are declared as "_Bool
1020   // foo(...)".
1021   TheCall->setArg(0, OrigArg0.get());
1022   TheCall->setArg(1, OrigArg1.get());
1023 
1024   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1025     return false;
1026 
1027   // If the common type isn't a real floating type, then the arguments were
1028   // invalid for this operation.
1029   if (!Res->isRealFloatingType())
1030     return Diag(OrigArg0.get()->getLocStart(),
1031                 diag::err_typecheck_call_invalid_ordered_compare)
1032       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1033       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1034 
1035   return false;
1036 }
1037 
1038 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1039 /// __builtin_isnan and friends.  This is declared to take (...), so we have
1040 /// to check everything. We expect the last argument to be a floating point
1041 /// value.
1042 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1043   if (TheCall->getNumArgs() < NumArgs)
1044     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1045       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1046   if (TheCall->getNumArgs() > NumArgs)
1047     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1048                 diag::err_typecheck_call_too_many_args)
1049       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1050       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1051                      (*(TheCall->arg_end()-1))->getLocEnd());
1052 
1053   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1054 
1055   if (OrigArg->isTypeDependent())
1056     return false;
1057 
1058   // This operation requires a non-_Complex floating-point number.
1059   if (!OrigArg->getType()->isRealFloatingType())
1060     return Diag(OrigArg->getLocStart(),
1061                 diag::err_typecheck_call_invalid_unary_fp)
1062       << OrigArg->getType() << OrigArg->getSourceRange();
1063 
1064   // If this is an implicit conversion from float -> double, remove it.
1065   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1066     Expr *CastArg = Cast->getSubExpr();
1067     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1068       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1069              "promotion from float to double is the only expected cast here");
1070       Cast->setSubExpr(0);
1071       TheCall->setArg(NumArgs-1, CastArg);
1072       OrigArg = CastArg;
1073     }
1074   }
1075 
1076   return false;
1077 }
1078 
1079 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1080 // This is declared to take (...), so we have to check everything.
1081 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1082   if (TheCall->getNumArgs() < 2)
1083     return ExprError(Diag(TheCall->getLocEnd(),
1084                           diag::err_typecheck_call_too_few_args_at_least)
1085       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1086       << TheCall->getSourceRange());
1087 
1088   // Determine which of the following types of shufflevector we're checking:
1089   // 1) unary, vector mask: (lhs, mask)
1090   // 2) binary, vector mask: (lhs, rhs, mask)
1091   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1092   QualType resType = TheCall->getArg(0)->getType();
1093   unsigned numElements = 0;
1094 
1095   if (!TheCall->getArg(0)->isTypeDependent() &&
1096       !TheCall->getArg(1)->isTypeDependent()) {
1097     QualType LHSType = TheCall->getArg(0)->getType();
1098     QualType RHSType = TheCall->getArg(1)->getType();
1099 
1100     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1101       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1102         << SourceRange(TheCall->getArg(0)->getLocStart(),
1103                        TheCall->getArg(1)->getLocEnd());
1104       return ExprError();
1105     }
1106 
1107     numElements = LHSType->getAs<VectorType>()->getNumElements();
1108     unsigned numResElements = TheCall->getNumArgs() - 2;
1109 
1110     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1111     // with mask.  If so, verify that RHS is an integer vector type with the
1112     // same number of elts as lhs.
1113     if (TheCall->getNumArgs() == 2) {
1114       if (!RHSType->hasIntegerRepresentation() ||
1115           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1116         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1117           << SourceRange(TheCall->getArg(1)->getLocStart(),
1118                          TheCall->getArg(1)->getLocEnd());
1119       numResElements = numElements;
1120     }
1121     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1122       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1123         << SourceRange(TheCall->getArg(0)->getLocStart(),
1124                        TheCall->getArg(1)->getLocEnd());
1125       return ExprError();
1126     } else if (numElements != numResElements) {
1127       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1128       resType = Context.getVectorType(eltType, numResElements,
1129                                       VectorType::GenericVector);
1130     }
1131   }
1132 
1133   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1134     if (TheCall->getArg(i)->isTypeDependent() ||
1135         TheCall->getArg(i)->isValueDependent())
1136       continue;
1137 
1138     llvm::APSInt Result(32);
1139     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1140       return ExprError(Diag(TheCall->getLocStart(),
1141                   diag::err_shufflevector_nonconstant_argument)
1142                 << TheCall->getArg(i)->getSourceRange());
1143 
1144     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1145       return ExprError(Diag(TheCall->getLocStart(),
1146                   diag::err_shufflevector_argument_too_large)
1147                << TheCall->getArg(i)->getSourceRange());
1148   }
1149 
1150   SmallVector<Expr*, 32> exprs;
1151 
1152   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1153     exprs.push_back(TheCall->getArg(i));
1154     TheCall->setArg(i, 0);
1155   }
1156 
1157   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1158                                             exprs.size(), resType,
1159                                             TheCall->getCallee()->getLocStart(),
1160                                             TheCall->getRParenLoc()));
1161 }
1162 
1163 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1164 // This is declared to take (const void*, ...) and can take two
1165 // optional constant int args.
1166 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1167   unsigned NumArgs = TheCall->getNumArgs();
1168 
1169   if (NumArgs > 3)
1170     return Diag(TheCall->getLocEnd(),
1171              diag::err_typecheck_call_too_many_args_at_most)
1172              << 0 /*function call*/ << 3 << NumArgs
1173              << TheCall->getSourceRange();
1174 
1175   // Argument 0 is checked for us and the remaining arguments must be
1176   // constant integers.
1177   for (unsigned i = 1; i != NumArgs; ++i) {
1178     Expr *Arg = TheCall->getArg(i);
1179 
1180     llvm::APSInt Result;
1181     if (SemaBuiltinConstantArg(TheCall, i, Result))
1182       return true;
1183 
1184     // FIXME: gcc issues a warning and rewrites these to 0. These
1185     // seems especially odd for the third argument since the default
1186     // is 3.
1187     if (i == 1) {
1188       if (Result.getLimitedValue() > 1)
1189         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1190              << "0" << "1" << Arg->getSourceRange();
1191     } else {
1192       if (Result.getLimitedValue() > 3)
1193         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1194             << "0" << "3" << Arg->getSourceRange();
1195     }
1196   }
1197 
1198   return false;
1199 }
1200 
1201 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1202 /// TheCall is a constant expression.
1203 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1204                                   llvm::APSInt &Result) {
1205   Expr *Arg = TheCall->getArg(ArgNum);
1206   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1207   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1208 
1209   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1210 
1211   if (!Arg->isIntegerConstantExpr(Result, Context))
1212     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1213                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1214 
1215   return false;
1216 }
1217 
1218 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1219 /// int type). This simply type checks that type is one of the defined
1220 /// constants (0-3).
1221 // For compatibility check 0-3, llvm only handles 0 and 2.
1222 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1223   llvm::APSInt Result;
1224 
1225   // Check constant-ness first.
1226   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1227     return true;
1228 
1229   Expr *Arg = TheCall->getArg(1);
1230   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1231     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1232              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1233   }
1234 
1235   return false;
1236 }
1237 
1238 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1239 /// This checks that val is a constant 1.
1240 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1241   Expr *Arg = TheCall->getArg(1);
1242   llvm::APSInt Result;
1243 
1244   // TODO: This is less than ideal. Overload this to take a value.
1245   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1246     return true;
1247 
1248   if (Result != 1)
1249     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1250              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1251 
1252   return false;
1253 }
1254 
1255 // Handle i > 1 ? "x" : "y", recursively.
1256 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1257                                   bool HasVAListArg,
1258                                   unsigned format_idx, unsigned firstDataArg,
1259                                   bool isPrintf, bool inFunctionCall) {
1260  tryAgain:
1261   if (E->isTypeDependent() || E->isValueDependent())
1262     return false;
1263 
1264   E = E->IgnoreParens();
1265 
1266   switch (E->getStmtClass()) {
1267   case Stmt::BinaryConditionalOperatorClass:
1268   case Stmt::ConditionalOperatorClass: {
1269     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1270     return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1271                                   format_idx, firstDataArg, isPrintf,
1272                                   inFunctionCall)
1273         && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1274                                   format_idx, firstDataArg, isPrintf,
1275                                   inFunctionCall);
1276   }
1277 
1278   case Stmt::IntegerLiteralClass:
1279     // Technically -Wformat-nonliteral does not warn about this case.
1280     // The behavior of printf and friends in this case is implementation
1281     // dependent.  Ideally if the format string cannot be null then
1282     // it should have a 'nonnull' attribute in the function prototype.
1283     return true;
1284 
1285   case Stmt::ImplicitCastExprClass: {
1286     E = cast<ImplicitCastExpr>(E)->getSubExpr();
1287     goto tryAgain;
1288   }
1289 
1290   case Stmt::OpaqueValueExprClass:
1291     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1292       E = src;
1293       goto tryAgain;
1294     }
1295     return false;
1296 
1297   case Stmt::PredefinedExprClass:
1298     // While __func__, etc., are technically not string literals, they
1299     // cannot contain format specifiers and thus are not a security
1300     // liability.
1301     return true;
1302 
1303   case Stmt::DeclRefExprClass: {
1304     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1305 
1306     // As an exception, do not flag errors for variables binding to
1307     // const string literals.
1308     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1309       bool isConstant = false;
1310       QualType T = DR->getType();
1311 
1312       if (const ArrayType *AT = Context.getAsArrayType(T)) {
1313         isConstant = AT->getElementType().isConstant(Context);
1314       } else if (const PointerType *PT = T->getAs<PointerType>()) {
1315         isConstant = T.isConstant(Context) &&
1316                      PT->getPointeeType().isConstant(Context);
1317       }
1318 
1319       if (isConstant) {
1320         if (const Expr *Init = VD->getAnyInitializer())
1321           return SemaCheckStringLiteral(Init, TheCall,
1322                                         HasVAListArg, format_idx, firstDataArg,
1323                                         isPrintf, /*inFunctionCall*/false);
1324       }
1325 
1326       // For vprintf* functions (i.e., HasVAListArg==true), we add a
1327       // special check to see if the format string is a function parameter
1328       // of the function calling the printf function.  If the function
1329       // has an attribute indicating it is a printf-like function, then we
1330       // should suppress warnings concerning non-literals being used in a call
1331       // to a vprintf function.  For example:
1332       //
1333       // void
1334       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1335       //      va_list ap;
1336       //      va_start(ap, fmt);
1337       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1338       //      ...
1339       //
1340       //
1341       //  FIXME: We don't have full attribute support yet, so just check to see
1342       //    if the argument is a DeclRefExpr that references a parameter.  We'll
1343       //    add proper support for checking the attribute later.
1344       if (HasVAListArg)
1345         if (isa<ParmVarDecl>(VD))
1346           return true;
1347     }
1348 
1349     return false;
1350   }
1351 
1352   case Stmt::CallExprClass: {
1353     const CallExpr *CE = cast<CallExpr>(E);
1354     if (const ImplicitCastExpr *ICE
1355           = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1356       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1357         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1358           if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1359             unsigned ArgIndex = FA->getFormatIdx();
1360             const Expr *Arg = CE->getArg(ArgIndex - 1);
1361 
1362             return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1363                                           format_idx, firstDataArg, isPrintf,
1364                                           inFunctionCall);
1365           }
1366         }
1367       }
1368     }
1369 
1370     return false;
1371   }
1372   case Stmt::ObjCStringLiteralClass:
1373   case Stmt::StringLiteralClass: {
1374     const StringLiteral *StrE = NULL;
1375 
1376     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1377       StrE = ObjCFExpr->getString();
1378     else
1379       StrE = cast<StringLiteral>(E);
1380 
1381     if (StrE) {
1382       CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1383                         firstDataArg, isPrintf, inFunctionCall);
1384       return true;
1385     }
1386 
1387     return false;
1388   }
1389 
1390   default:
1391     return false;
1392   }
1393 }
1394 
1395 void
1396 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1397                             const Expr * const *ExprArgs,
1398                             SourceLocation CallSiteLoc) {
1399   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1400                                   e = NonNull->args_end();
1401        i != e; ++i) {
1402     const Expr *ArgExpr = ExprArgs[*i];
1403     if (ArgExpr->isNullPointerConstant(Context,
1404                                        Expr::NPC_ValueDependentIsNotNull))
1405       Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1406   }
1407 }
1408 
1409 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1410 /// functions) for correct use of format strings.
1411 void
1412 Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1413                                 unsigned format_idx, unsigned firstDataArg,
1414                                 bool isPrintf) {
1415 
1416   const Expr *Fn = TheCall->getCallee();
1417 
1418   // The way the format attribute works in GCC, the implicit this argument
1419   // of member functions is counted. However, it doesn't appear in our own
1420   // lists, so decrement format_idx in that case.
1421   if (isa<CXXMemberCallExpr>(TheCall)) {
1422     const CXXMethodDecl *method_decl =
1423       dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1424     if (method_decl && method_decl->isInstance()) {
1425       // Catch a format attribute mistakenly referring to the object argument.
1426       if (format_idx == 0)
1427         return;
1428       --format_idx;
1429       if(firstDataArg != 0)
1430         --firstDataArg;
1431     }
1432   }
1433 
1434   // CHECK: printf/scanf-like function is called with no format string.
1435   if (format_idx >= TheCall->getNumArgs()) {
1436     Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1437       << Fn->getSourceRange();
1438     return;
1439   }
1440 
1441   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1442 
1443   // CHECK: format string is not a string literal.
1444   //
1445   // Dynamically generated format strings are difficult to
1446   // automatically vet at compile time.  Requiring that format strings
1447   // are string literals: (1) permits the checking of format strings by
1448   // the compiler and thereby (2) can practically remove the source of
1449   // many format string exploits.
1450 
1451   // Format string can be either ObjC string (e.g. @"%d") or
1452   // C string (e.g. "%d")
1453   // ObjC string uses the same format specifiers as C string, so we can use
1454   // the same format string checking logic for both ObjC and C strings.
1455   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1456                              firstDataArg, isPrintf))
1457     return;  // Literal format string found, check done!
1458 
1459   // If there are no arguments specified, warn with -Wformat-security, otherwise
1460   // warn only with -Wformat-nonliteral.
1461   if (TheCall->getNumArgs() == format_idx+1)
1462     Diag(TheCall->getArg(format_idx)->getLocStart(),
1463          diag::warn_format_nonliteral_noargs)
1464       << OrigFormatExpr->getSourceRange();
1465   else
1466     Diag(TheCall->getArg(format_idx)->getLocStart(),
1467          diag::warn_format_nonliteral)
1468            << OrigFormatExpr->getSourceRange();
1469 }
1470 
1471 namespace {
1472 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1473 protected:
1474   Sema &S;
1475   const StringLiteral *FExpr;
1476   const Expr *OrigFormatExpr;
1477   const unsigned FirstDataArg;
1478   const unsigned NumDataArgs;
1479   const bool IsObjCLiteral;
1480   const char *Beg; // Start of format string.
1481   const bool HasVAListArg;
1482   const CallExpr *TheCall;
1483   unsigned FormatIdx;
1484   llvm::BitVector CoveredArgs;
1485   bool usesPositionalArgs;
1486   bool atFirstArg;
1487   bool inFunctionCall;
1488 public:
1489   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1490                      const Expr *origFormatExpr, unsigned firstDataArg,
1491                      unsigned numDataArgs, bool isObjCLiteral,
1492                      const char *beg, bool hasVAListArg,
1493                      const CallExpr *theCall, unsigned formatIdx,
1494                      bool inFunctionCall)
1495     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1496       FirstDataArg(firstDataArg),
1497       NumDataArgs(numDataArgs),
1498       IsObjCLiteral(isObjCLiteral), Beg(beg),
1499       HasVAListArg(hasVAListArg),
1500       TheCall(theCall), FormatIdx(formatIdx),
1501       usesPositionalArgs(false), atFirstArg(true),
1502       inFunctionCall(inFunctionCall) {
1503         CoveredArgs.resize(numDataArgs);
1504         CoveredArgs.reset();
1505       }
1506 
1507   void DoneProcessing();
1508 
1509   void HandleIncompleteSpecifier(const char *startSpecifier,
1510                                  unsigned specifierLen);
1511 
1512   virtual void HandleInvalidPosition(const char *startSpecifier,
1513                                      unsigned specifierLen,
1514                                      analyze_format_string::PositionContext p);
1515 
1516   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1517 
1518   void HandleNullChar(const char *nullCharacter);
1519 
1520   template <typename Range>
1521   static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1522                                    const Expr *ArgumentExpr,
1523                                    PartialDiagnostic PDiag,
1524                                    SourceLocation StringLoc,
1525                                    bool IsStringLocation, Range StringRange,
1526                                    FixItHint Fixit = FixItHint());
1527 
1528 protected:
1529   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1530                                         const char *startSpec,
1531                                         unsigned specifierLen,
1532                                         const char *csStart, unsigned csLen);
1533 
1534   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1535                                          const char *startSpec,
1536                                          unsigned specifierLen);
1537 
1538   SourceRange getFormatStringRange();
1539   CharSourceRange getSpecifierRange(const char *startSpecifier,
1540                                     unsigned specifierLen);
1541   SourceLocation getLocationOfByte(const char *x);
1542 
1543   const Expr *getDataArg(unsigned i) const;
1544 
1545   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1546                     const analyze_format_string::ConversionSpecifier &CS,
1547                     const char *startSpecifier, unsigned specifierLen,
1548                     unsigned argIndex);
1549 
1550   template <typename Range>
1551   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1552                             bool IsStringLocation, Range StringRange,
1553                             FixItHint Fixit = FixItHint());
1554 
1555   void CheckPositionalAndNonpositionalArgs(
1556       const analyze_format_string::FormatSpecifier *FS);
1557 };
1558 }
1559 
1560 SourceRange CheckFormatHandler::getFormatStringRange() {
1561   return OrigFormatExpr->getSourceRange();
1562 }
1563 
1564 CharSourceRange CheckFormatHandler::
1565 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1566   SourceLocation Start = getLocationOfByte(startSpecifier);
1567   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1568 
1569   // Advance the end SourceLocation by one due to half-open ranges.
1570   End = End.getLocWithOffset(1);
1571 
1572   return CharSourceRange::getCharRange(Start, End);
1573 }
1574 
1575 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1576   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1577 }
1578 
1579 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1580                                                    unsigned specifierLen){
1581   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1582                        getLocationOfByte(startSpecifier),
1583                        /*IsStringLocation*/true,
1584                        getSpecifierRange(startSpecifier, specifierLen));
1585 }
1586 
1587 void
1588 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1589                                      analyze_format_string::PositionContext p) {
1590   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1591                          << (unsigned) p,
1592                        getLocationOfByte(startPos), /*IsStringLocation*/true,
1593                        getSpecifierRange(startPos, posLen));
1594 }
1595 
1596 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1597                                             unsigned posLen) {
1598   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1599                                getLocationOfByte(startPos),
1600                                /*IsStringLocation*/true,
1601                                getSpecifierRange(startPos, posLen));
1602 }
1603 
1604 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1605   if (!IsObjCLiteral) {
1606     // The presence of a null character is likely an error.
1607     EmitFormatDiagnostic(
1608       S.PDiag(diag::warn_printf_format_string_contains_null_char),
1609       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1610       getFormatStringRange());
1611   }
1612 }
1613 
1614 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1615   return TheCall->getArg(FirstDataArg + i);
1616 }
1617 
1618 void CheckFormatHandler::DoneProcessing() {
1619     // Does the number of data arguments exceed the number of
1620     // format conversions in the format string?
1621   if (!HasVAListArg) {
1622       // Find any arguments that weren't covered.
1623     CoveredArgs.flip();
1624     signed notCoveredArg = CoveredArgs.find_first();
1625     if (notCoveredArg >= 0) {
1626       assert((unsigned)notCoveredArg < NumDataArgs);
1627       EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1628                            getDataArg((unsigned) notCoveredArg)->getLocStart(),
1629                            /*IsStringLocation*/false, getFormatStringRange());
1630     }
1631   }
1632 }
1633 
1634 bool
1635 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1636                                                      SourceLocation Loc,
1637                                                      const char *startSpec,
1638                                                      unsigned specifierLen,
1639                                                      const char *csStart,
1640                                                      unsigned csLen) {
1641 
1642   bool keepGoing = true;
1643   if (argIndex < NumDataArgs) {
1644     // Consider the argument coverered, even though the specifier doesn't
1645     // make sense.
1646     CoveredArgs.set(argIndex);
1647   }
1648   else {
1649     // If argIndex exceeds the number of data arguments we
1650     // don't issue a warning because that is just a cascade of warnings (and
1651     // they may have intended '%%' anyway). We don't want to continue processing
1652     // the format string after this point, however, as we will like just get
1653     // gibberish when trying to match arguments.
1654     keepGoing = false;
1655   }
1656 
1657   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1658                          << StringRef(csStart, csLen),
1659                        Loc, /*IsStringLocation*/true,
1660                        getSpecifierRange(startSpec, specifierLen));
1661 
1662   return keepGoing;
1663 }
1664 
1665 void
1666 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1667                                                       const char *startSpec,
1668                                                       unsigned specifierLen) {
1669   EmitFormatDiagnostic(
1670     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1671     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1672 }
1673 
1674 bool
1675 CheckFormatHandler::CheckNumArgs(
1676   const analyze_format_string::FormatSpecifier &FS,
1677   const analyze_format_string::ConversionSpecifier &CS,
1678   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1679 
1680   if (argIndex >= NumDataArgs) {
1681     PartialDiagnostic PDiag = FS.usesPositionalArg()
1682       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1683            << (argIndex+1) << NumDataArgs)
1684       : S.PDiag(diag::warn_printf_insufficient_data_args);
1685     EmitFormatDiagnostic(
1686       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1687       getSpecifierRange(startSpecifier, specifierLen));
1688     return false;
1689   }
1690   return true;
1691 }
1692 
1693 template<typename Range>
1694 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1695                                               SourceLocation Loc,
1696                                               bool IsStringLocation,
1697                                               Range StringRange,
1698                                               FixItHint FixIt) {
1699   EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1700                        Loc, IsStringLocation, StringRange, FixIt);
1701 }
1702 
1703 /// \brief If the format string is not within the funcion call, emit a note
1704 /// so that the function call and string are in diagnostic messages.
1705 ///
1706 /// \param inFunctionCall if true, the format string is within the function
1707 /// call and only one diagnostic message will be produced.  Otherwise, an
1708 /// extra note will be emitted pointing to location of the format string.
1709 ///
1710 /// \param ArgumentExpr the expression that is passed as the format string
1711 /// argument in the function call.  Used for getting locations when two
1712 /// diagnostics are emitted.
1713 ///
1714 /// \param PDiag the callee should already have provided any strings for the
1715 /// diagnostic message.  This function only adds locations and fixits
1716 /// to diagnostics.
1717 ///
1718 /// \param Loc primary location for diagnostic.  If two diagnostics are
1719 /// required, one will be at Loc and a new SourceLocation will be created for
1720 /// the other one.
1721 ///
1722 /// \param IsStringLocation if true, Loc points to the format string should be
1723 /// used for the note.  Otherwise, Loc points to the argument list and will
1724 /// be used with PDiag.
1725 ///
1726 /// \param StringRange some or all of the string to highlight.  This is
1727 /// templated so it can accept either a CharSourceRange or a SourceRange.
1728 ///
1729 /// \param Fixit optional fix it hint for the format string.
1730 template<typename Range>
1731 void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1732                                               const Expr *ArgumentExpr,
1733                                               PartialDiagnostic PDiag,
1734                                               SourceLocation Loc,
1735                                               bool IsStringLocation,
1736                                               Range StringRange,
1737                                               FixItHint FixIt) {
1738   if (InFunctionCall)
1739     S.Diag(Loc, PDiag) << StringRange << FixIt;
1740   else {
1741     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1742       << ArgumentExpr->getSourceRange();
1743     S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1744            diag::note_format_string_defined)
1745       << StringRange << FixIt;
1746   }
1747 }
1748 
1749 //===--- CHECK: Printf format string checking ------------------------------===//
1750 
1751 namespace {
1752 class CheckPrintfHandler : public CheckFormatHandler {
1753 public:
1754   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1755                      const Expr *origFormatExpr, unsigned firstDataArg,
1756                      unsigned numDataArgs, bool isObjCLiteral,
1757                      const char *beg, bool hasVAListArg,
1758                      const CallExpr *theCall, unsigned formatIdx,
1759                      bool inFunctionCall)
1760   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1761                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1762                        theCall, formatIdx, inFunctionCall) {}
1763 
1764 
1765   bool HandleInvalidPrintfConversionSpecifier(
1766                                       const analyze_printf::PrintfSpecifier &FS,
1767                                       const char *startSpecifier,
1768                                       unsigned specifierLen);
1769 
1770   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1771                              const char *startSpecifier,
1772                              unsigned specifierLen);
1773 
1774   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1775                     const char *startSpecifier, unsigned specifierLen);
1776   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1777                            const analyze_printf::OptionalAmount &Amt,
1778                            unsigned type,
1779                            const char *startSpecifier, unsigned specifierLen);
1780   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1781                   const analyze_printf::OptionalFlag &flag,
1782                   const char *startSpecifier, unsigned specifierLen);
1783   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1784                          const analyze_printf::OptionalFlag &ignoredFlag,
1785                          const analyze_printf::OptionalFlag &flag,
1786                          const char *startSpecifier, unsigned specifierLen);
1787 };
1788 }
1789 
1790 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1791                                       const analyze_printf::PrintfSpecifier &FS,
1792                                       const char *startSpecifier,
1793                                       unsigned specifierLen) {
1794   const analyze_printf::PrintfConversionSpecifier &CS =
1795     FS.getConversionSpecifier();
1796 
1797   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1798                                           getLocationOfByte(CS.getStart()),
1799                                           startSpecifier, specifierLen,
1800                                           CS.getStart(), CS.getLength());
1801 }
1802 
1803 bool CheckPrintfHandler::HandleAmount(
1804                                const analyze_format_string::OptionalAmount &Amt,
1805                                unsigned k, const char *startSpecifier,
1806                                unsigned specifierLen) {
1807 
1808   if (Amt.hasDataArgument()) {
1809     if (!HasVAListArg) {
1810       unsigned argIndex = Amt.getArgIndex();
1811       if (argIndex >= NumDataArgs) {
1812         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1813                                << k,
1814                              getLocationOfByte(Amt.getStart()),
1815                              /*IsStringLocation*/true,
1816                              getSpecifierRange(startSpecifier, specifierLen));
1817         // Don't do any more checking.  We will just emit
1818         // spurious errors.
1819         return false;
1820       }
1821 
1822       // Type check the data argument.  It should be an 'int'.
1823       // Although not in conformance with C99, we also allow the argument to be
1824       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1825       // doesn't emit a warning for that case.
1826       CoveredArgs.set(argIndex);
1827       const Expr *Arg = getDataArg(argIndex);
1828       QualType T = Arg->getType();
1829 
1830       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1831       assert(ATR.isValid());
1832 
1833       if (!ATR.matchesType(S.Context, T)) {
1834         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1835                                << k << ATR.getRepresentativeType(S.Context)
1836                                << T << Arg->getSourceRange(),
1837                              getLocationOfByte(Amt.getStart()),
1838                              /*IsStringLocation*/true,
1839                              getSpecifierRange(startSpecifier, specifierLen));
1840         // Don't do any more checking.  We will just emit
1841         // spurious errors.
1842         return false;
1843       }
1844     }
1845   }
1846   return true;
1847 }
1848 
1849 void CheckPrintfHandler::HandleInvalidAmount(
1850                                       const analyze_printf::PrintfSpecifier &FS,
1851                                       const analyze_printf::OptionalAmount &Amt,
1852                                       unsigned type,
1853                                       const char *startSpecifier,
1854                                       unsigned specifierLen) {
1855   const analyze_printf::PrintfConversionSpecifier &CS =
1856     FS.getConversionSpecifier();
1857 
1858   FixItHint fixit =
1859     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1860       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1861                                  Amt.getConstantLength()))
1862       : FixItHint();
1863 
1864   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1865                          << type << CS.toString(),
1866                        getLocationOfByte(Amt.getStart()),
1867                        /*IsStringLocation*/true,
1868                        getSpecifierRange(startSpecifier, specifierLen),
1869                        fixit);
1870 }
1871 
1872 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1873                                     const analyze_printf::OptionalFlag &flag,
1874                                     const char *startSpecifier,
1875                                     unsigned specifierLen) {
1876   // Warn about pointless flag with a fixit removal.
1877   const analyze_printf::PrintfConversionSpecifier &CS =
1878     FS.getConversionSpecifier();
1879   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1880                          << flag.toString() << CS.toString(),
1881                        getLocationOfByte(flag.getPosition()),
1882                        /*IsStringLocation*/true,
1883                        getSpecifierRange(startSpecifier, specifierLen),
1884                        FixItHint::CreateRemoval(
1885                          getSpecifierRange(flag.getPosition(), 1)));
1886 }
1887 
1888 void CheckPrintfHandler::HandleIgnoredFlag(
1889                                 const analyze_printf::PrintfSpecifier &FS,
1890                                 const analyze_printf::OptionalFlag &ignoredFlag,
1891                                 const analyze_printf::OptionalFlag &flag,
1892                                 const char *startSpecifier,
1893                                 unsigned specifierLen) {
1894   // Warn about ignored flag with a fixit removal.
1895   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1896                          << ignoredFlag.toString() << flag.toString(),
1897                        getLocationOfByte(ignoredFlag.getPosition()),
1898                        /*IsStringLocation*/true,
1899                        getSpecifierRange(startSpecifier, specifierLen),
1900                        FixItHint::CreateRemoval(
1901                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
1902 }
1903 
1904 bool
1905 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1906                                             &FS,
1907                                           const char *startSpecifier,
1908                                           unsigned specifierLen) {
1909 
1910   using namespace analyze_format_string;
1911   using namespace analyze_printf;
1912   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1913 
1914   if (FS.consumesDataArgument()) {
1915     if (atFirstArg) {
1916         atFirstArg = false;
1917         usesPositionalArgs = FS.usesPositionalArg();
1918     }
1919     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1920       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1921                                         startSpecifier, specifierLen);
1922       return false;
1923     }
1924   }
1925 
1926   // First check if the field width, precision, and conversion specifier
1927   // have matching data arguments.
1928   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1929                     startSpecifier, specifierLen)) {
1930     return false;
1931   }
1932 
1933   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1934                     startSpecifier, specifierLen)) {
1935     return false;
1936   }
1937 
1938   if (!CS.consumesDataArgument()) {
1939     // FIXME: Technically specifying a precision or field width here
1940     // makes no sense.  Worth issuing a warning at some point.
1941     return true;
1942   }
1943 
1944   // Consume the argument.
1945   unsigned argIndex = FS.getArgIndex();
1946   if (argIndex < NumDataArgs) {
1947     // The check to see if the argIndex is valid will come later.
1948     // We set the bit here because we may exit early from this
1949     // function if we encounter some other error.
1950     CoveredArgs.set(argIndex);
1951   }
1952 
1953   // Check for using an Objective-C specific conversion specifier
1954   // in a non-ObjC literal.
1955   if (!IsObjCLiteral && CS.isObjCArg()) {
1956     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1957                                                   specifierLen);
1958   }
1959 
1960   // Check for invalid use of field width
1961   if (!FS.hasValidFieldWidth()) {
1962     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1963         startSpecifier, specifierLen);
1964   }
1965 
1966   // Check for invalid use of precision
1967   if (!FS.hasValidPrecision()) {
1968     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1969         startSpecifier, specifierLen);
1970   }
1971 
1972   // Check each flag does not conflict with any other component.
1973   if (!FS.hasValidThousandsGroupingPrefix())
1974     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1975   if (!FS.hasValidLeadingZeros())
1976     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1977   if (!FS.hasValidPlusPrefix())
1978     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1979   if (!FS.hasValidSpacePrefix())
1980     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1981   if (!FS.hasValidAlternativeForm())
1982     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1983   if (!FS.hasValidLeftJustified())
1984     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1985 
1986   // Check that flags are not ignored by another flag
1987   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1988     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1989         startSpecifier, specifierLen);
1990   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1991     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1992             startSpecifier, specifierLen);
1993 
1994   // Check the length modifier is valid with the given conversion specifier.
1995   const LengthModifier &LM = FS.getLengthModifier();
1996   if (!FS.hasValidLengthModifier())
1997     EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
1998                            << LM.toString() << CS.toString(),
1999                          getLocationOfByte(LM.getStart()),
2000                          /*IsStringLocation*/true,
2001                          getSpecifierRange(startSpecifier, specifierLen),
2002                          FixItHint::CreateRemoval(
2003                            getSpecifierRange(LM.getStart(),
2004                                              LM.getLength())));
2005 
2006   // Are we using '%n'?
2007   if (CS.getKind() == ConversionSpecifier::nArg) {
2008     // Issue a warning about this being a possible security issue.
2009     EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2010                          getLocationOfByte(CS.getStart()),
2011                          /*IsStringLocation*/true,
2012                          getSpecifierRange(startSpecifier, specifierLen));
2013     // Continue checking the other format specifiers.
2014     return true;
2015   }
2016 
2017   // The remaining checks depend on the data arguments.
2018   if (HasVAListArg)
2019     return true;
2020 
2021   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2022     return false;
2023 
2024   // Now type check the data expression that matches the
2025   // format specifier.
2026   const Expr *Ex = getDataArg(argIndex);
2027   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2028   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2029     // Check if we didn't match because of an implicit cast from a 'char'
2030     // or 'short' to an 'int'.  This is done because printf is a varargs
2031     // function.
2032     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
2033       if (ICE->getType() == S.Context.IntTy) {
2034         // All further checking is done on the subexpression.
2035         Ex = ICE->getSubExpr();
2036         if (ATR.matchesType(S.Context, Ex->getType()))
2037           return true;
2038       }
2039 
2040     // We may be able to offer a FixItHint if it is a supported type.
2041     PrintfSpecifier fixedFS = FS;
2042     bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2043 
2044     if (success) {
2045       // Get the fix string from the fixed format specifier
2046       llvm::SmallString<128> buf;
2047       llvm::raw_svector_ostream os(buf);
2048       fixedFS.toString(os);
2049 
2050       // FIXME: getRepresentativeType() perhaps should return a string
2051       // instead of a QualType to better handle when the representative
2052       // type is 'wint_t' (which is defined in the system headers).
2053       EmitFormatDiagnostic(
2054         S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2055           << ATR.getRepresentativeType(S.Context) << Ex->getType()
2056           << Ex->getSourceRange(),
2057         getLocationOfByte(CS.getStart()),
2058         /*IsStringLocation*/true,
2059         getSpecifierRange(startSpecifier, specifierLen),
2060         FixItHint::CreateReplacement(
2061           getSpecifierRange(startSpecifier, specifierLen),
2062           os.str()));
2063     }
2064     else {
2065       S.Diag(getLocationOfByte(CS.getStart()),
2066              diag::warn_printf_conversion_argument_type_mismatch)
2067         << ATR.getRepresentativeType(S.Context) << Ex->getType()
2068         << getSpecifierRange(startSpecifier, specifierLen)
2069         << Ex->getSourceRange();
2070     }
2071   }
2072 
2073   return true;
2074 }
2075 
2076 //===--- CHECK: Scanf format string checking ------------------------------===//
2077 
2078 namespace {
2079 class CheckScanfHandler : public CheckFormatHandler {
2080 public:
2081   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2082                     const Expr *origFormatExpr, unsigned firstDataArg,
2083                     unsigned numDataArgs, bool isObjCLiteral,
2084                     const char *beg, bool hasVAListArg,
2085                     const CallExpr *theCall, unsigned formatIdx,
2086                     bool inFunctionCall)
2087   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2088                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
2089                        theCall, formatIdx, inFunctionCall) {}
2090 
2091   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2092                             const char *startSpecifier,
2093                             unsigned specifierLen);
2094 
2095   bool HandleInvalidScanfConversionSpecifier(
2096           const analyze_scanf::ScanfSpecifier &FS,
2097           const char *startSpecifier,
2098           unsigned specifierLen);
2099 
2100   void HandleIncompleteScanList(const char *start, const char *end);
2101 };
2102 }
2103 
2104 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2105                                                  const char *end) {
2106   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2107                        getLocationOfByte(end), /*IsStringLocation*/true,
2108                        getSpecifierRange(start, end - start));
2109 }
2110 
2111 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2112                                         const analyze_scanf::ScanfSpecifier &FS,
2113                                         const char *startSpecifier,
2114                                         unsigned specifierLen) {
2115 
2116   const analyze_scanf::ScanfConversionSpecifier &CS =
2117     FS.getConversionSpecifier();
2118 
2119   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2120                                           getLocationOfByte(CS.getStart()),
2121                                           startSpecifier, specifierLen,
2122                                           CS.getStart(), CS.getLength());
2123 }
2124 
2125 bool CheckScanfHandler::HandleScanfSpecifier(
2126                                        const analyze_scanf::ScanfSpecifier &FS,
2127                                        const char *startSpecifier,
2128                                        unsigned specifierLen) {
2129 
2130   using namespace analyze_scanf;
2131   using namespace analyze_format_string;
2132 
2133   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2134 
2135   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2136   // be used to decide if we are using positional arguments consistently.
2137   if (FS.consumesDataArgument()) {
2138     if (atFirstArg) {
2139       atFirstArg = false;
2140       usesPositionalArgs = FS.usesPositionalArg();
2141     }
2142     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2143       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2144                                         startSpecifier, specifierLen);
2145       return false;
2146     }
2147   }
2148 
2149   // Check if the field with is non-zero.
2150   const OptionalAmount &Amt = FS.getFieldWidth();
2151   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2152     if (Amt.getConstantAmount() == 0) {
2153       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2154                                                    Amt.getConstantLength());
2155       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2156                            getLocationOfByte(Amt.getStart()),
2157                            /*IsStringLocation*/true, R,
2158                            FixItHint::CreateRemoval(R));
2159     }
2160   }
2161 
2162   if (!FS.consumesDataArgument()) {
2163     // FIXME: Technically specifying a precision or field width here
2164     // makes no sense.  Worth issuing a warning at some point.
2165     return true;
2166   }
2167 
2168   // Consume the argument.
2169   unsigned argIndex = FS.getArgIndex();
2170   if (argIndex < NumDataArgs) {
2171       // The check to see if the argIndex is valid will come later.
2172       // We set the bit here because we may exit early from this
2173       // function if we encounter some other error.
2174     CoveredArgs.set(argIndex);
2175   }
2176 
2177   // Check the length modifier is valid with the given conversion specifier.
2178   const LengthModifier &LM = FS.getLengthModifier();
2179   if (!FS.hasValidLengthModifier()) {
2180     S.Diag(getLocationOfByte(LM.getStart()),
2181            diag::warn_format_nonsensical_length)
2182       << LM.toString() << CS.toString()
2183       << getSpecifierRange(startSpecifier, specifierLen)
2184       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2185                                                     LM.getLength()));
2186   }
2187 
2188   // The remaining checks depend on the data arguments.
2189   if (HasVAListArg)
2190     return true;
2191 
2192   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2193     return false;
2194 
2195   // FIXME: Check that the argument type matches the format specifier.
2196 
2197   return true;
2198 }
2199 
2200 void Sema::CheckFormatString(const StringLiteral *FExpr,
2201                              const Expr *OrigFormatExpr,
2202                              const CallExpr *TheCall, bool HasVAListArg,
2203                              unsigned format_idx, unsigned firstDataArg,
2204                              bool isPrintf, bool inFunctionCall) {
2205 
2206   // CHECK: is the format string a wide literal?
2207   if (!FExpr->isAscii()) {
2208     CheckFormatHandler::EmitFormatDiagnostic(
2209       *this, inFunctionCall, TheCall->getArg(format_idx),
2210       PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2211       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2212     return;
2213   }
2214 
2215   // Str - The format string.  NOTE: this is NOT null-terminated!
2216   StringRef StrRef = FExpr->getString();
2217   const char *Str = StrRef.data();
2218   unsigned StrLen = StrRef.size();
2219   const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
2220 
2221   // CHECK: empty format string?
2222   if (StrLen == 0 && numDataArgs > 0) {
2223     CheckFormatHandler::EmitFormatDiagnostic(
2224       *this, inFunctionCall, TheCall->getArg(format_idx),
2225       PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2226       /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2227     return;
2228   }
2229 
2230   if (isPrintf) {
2231     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2232                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2233                          Str, HasVAListArg, TheCall, format_idx,
2234                          inFunctionCall);
2235 
2236     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2237       H.DoneProcessing();
2238   }
2239   else {
2240     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2241                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2242                         Str, HasVAListArg, TheCall, format_idx,
2243                         inFunctionCall);
2244 
2245     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2246       H.DoneProcessing();
2247   }
2248 }
2249 
2250 //===--- CHECK: Standard memory functions ---------------------------------===//
2251 
2252 /// \brief Determine whether the given type is a dynamic class type (e.g.,
2253 /// whether it has a vtable).
2254 static bool isDynamicClassType(QualType T) {
2255   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2256     if (CXXRecordDecl *Definition = Record->getDefinition())
2257       if (Definition->isDynamicClass())
2258         return true;
2259 
2260   return false;
2261 }
2262 
2263 /// \brief If E is a sizeof expression, returns its argument expression,
2264 /// otherwise returns NULL.
2265 static const Expr *getSizeOfExprArg(const Expr* E) {
2266   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2267       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2268     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2269       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2270 
2271   return 0;
2272 }
2273 
2274 /// \brief If E is a sizeof expression, returns its argument type.
2275 static QualType getSizeOfArgType(const Expr* E) {
2276   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2277       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2278     if (SizeOf->getKind() == clang::UETT_SizeOf)
2279       return SizeOf->getTypeOfArgument();
2280 
2281   return QualType();
2282 }
2283 
2284 /// \brief Check for dangerous or invalid arguments to memset().
2285 ///
2286 /// This issues warnings on known problematic, dangerous or unspecified
2287 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2288 /// function calls.
2289 ///
2290 /// \param Call The call expression to diagnose.
2291 void Sema::CheckMemaccessArguments(const CallExpr *Call,
2292                                    CheckedMemoryFunction CMF,
2293                                    IdentifierInfo *FnName) {
2294   // It is possible to have a non-standard definition of memset.  Validate
2295   // we have enough arguments, and if not, abort further checking.
2296   unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2297   if (Call->getNumArgs() < ExpectedNumArgs)
2298     return;
2299 
2300   unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2301   unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2302   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2303 
2304   // We have special checking when the length is a sizeof expression.
2305   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2306   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2307   llvm::FoldingSetNodeID SizeOfArgID;
2308 
2309   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2310     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2311     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2312 
2313     QualType DestTy = Dest->getType();
2314     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2315       QualType PointeeTy = DestPtrTy->getPointeeType();
2316 
2317       // Never warn about void type pointers. This can be used to suppress
2318       // false positives.
2319       if (PointeeTy->isVoidType())
2320         continue;
2321 
2322       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2323       // actually comparing the expressions for equality. Because computing the
2324       // expression IDs can be expensive, we only do this if the diagnostic is
2325       // enabled.
2326       if (SizeOfArg &&
2327           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2328                                    SizeOfArg->getExprLoc())) {
2329         // We only compute IDs for expressions if the warning is enabled, and
2330         // cache the sizeof arg's ID.
2331         if (SizeOfArgID == llvm::FoldingSetNodeID())
2332           SizeOfArg->Profile(SizeOfArgID, Context, true);
2333         llvm::FoldingSetNodeID DestID;
2334         Dest->Profile(DestID, Context, true);
2335         if (DestID == SizeOfArgID) {
2336           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2337           //       over sizeof(src) as well.
2338           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2339           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2340             if (UnaryOp->getOpcode() == UO_AddrOf)
2341               ActionIdx = 1; // If its an address-of operator, just remove it.
2342           if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2343             ActionIdx = 2; // If the pointee's size is sizeof(char),
2344                            // suggest an explicit length.
2345           unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
2346           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2347                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2348                                 << FnName << DestSrcSelect << ActionIdx
2349                                 << Dest->getSourceRange()
2350                                 << SizeOfArg->getSourceRange());
2351           break;
2352         }
2353       }
2354 
2355       // Also check for cases where the sizeof argument is the exact same
2356       // type as the memory argument, and where it points to a user-defined
2357       // record type.
2358       if (SizeOfArgTy != QualType()) {
2359         if (PointeeTy->isRecordType() &&
2360             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2361           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2362                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
2363                                 << FnName << SizeOfArgTy << ArgIdx
2364                                 << PointeeTy << Dest->getSourceRange()
2365                                 << LenExpr->getSourceRange());
2366           break;
2367         }
2368       }
2369 
2370       // Always complain about dynamic classes.
2371       if (isDynamicClassType(PointeeTy))
2372         DiagRuntimeBehavior(
2373           Dest->getExprLoc(), Dest,
2374           PDiag(diag::warn_dyn_class_memaccess)
2375             << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2376             // "overwritten" if we're warning about the destination for any call
2377             // but memcmp; otherwise a verb appropriate to the call.
2378             << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2379             << Call->getCallee()->getSourceRange());
2380       else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2381         DiagRuntimeBehavior(
2382           Dest->getExprLoc(), Dest,
2383           PDiag(diag::warn_arc_object_memaccess)
2384             << ArgIdx << FnName << PointeeTy
2385             << Call->getCallee()->getSourceRange());
2386       else
2387         continue;
2388 
2389       DiagRuntimeBehavior(
2390         Dest->getExprLoc(), Dest,
2391         PDiag(diag::note_bad_memaccess_silence)
2392           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2393       break;
2394     }
2395   }
2396 }
2397 
2398 // A little helper routine: ignore addition and subtraction of integer literals.
2399 // This intentionally does not ignore all integer constant expressions because
2400 // we don't want to remove sizeof().
2401 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2402   Ex = Ex->IgnoreParenCasts();
2403 
2404   for (;;) {
2405     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2406     if (!BO || !BO->isAdditiveOp())
2407       break;
2408 
2409     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2410     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2411 
2412     if (isa<IntegerLiteral>(RHS))
2413       Ex = LHS;
2414     else if (isa<IntegerLiteral>(LHS))
2415       Ex = RHS;
2416     else
2417       break;
2418   }
2419 
2420   return Ex;
2421 }
2422 
2423 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2424 // be the size of the source, instead of the destination.
2425 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2426                                     IdentifierInfo *FnName) {
2427 
2428   // Don't crash if the user has the wrong number of arguments
2429   if (Call->getNumArgs() != 3)
2430     return;
2431 
2432   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2433   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2434   const Expr *CompareWithSrc = NULL;
2435 
2436   // Look for 'strlcpy(dst, x, sizeof(x))'
2437   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2438     CompareWithSrc = Ex;
2439   else {
2440     // Look for 'strlcpy(dst, x, strlen(x))'
2441     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2442       if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
2443           && SizeCall->getNumArgs() == 1)
2444         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2445     }
2446   }
2447 
2448   if (!CompareWithSrc)
2449     return;
2450 
2451   // Determine if the argument to sizeof/strlen is equal to the source
2452   // argument.  In principle there's all kinds of things you could do
2453   // here, for instance creating an == expression and evaluating it with
2454   // EvaluateAsBooleanCondition, but this uses a more direct technique:
2455   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2456   if (!SrcArgDRE)
2457     return;
2458 
2459   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2460   if (!CompareWithSrcDRE ||
2461       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2462     return;
2463 
2464   const Expr *OriginalSizeArg = Call->getArg(2);
2465   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2466     << OriginalSizeArg->getSourceRange() << FnName;
2467 
2468   // Output a FIXIT hint if the destination is an array (rather than a
2469   // pointer to an array).  This could be enhanced to handle some
2470   // pointers if we know the actual size, like if DstArg is 'array+2'
2471   // we could say 'sizeof(array)-2'.
2472   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2473   QualType DstArgTy = DstArg->getType();
2474 
2475   // Only handle constant-sized or VLAs, but not flexible members.
2476   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2477     // Only issue the FIXIT for arrays of size > 1.
2478     if (CAT->getSize().getSExtValue() <= 1)
2479       return;
2480   } else if (!DstArgTy->isVariableArrayType()) {
2481     return;
2482   }
2483 
2484   llvm::SmallString<128> sizeString;
2485   llvm::raw_svector_ostream OS(sizeString);
2486   OS << "sizeof(";
2487   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2488   OS << ")";
2489 
2490   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2491     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2492                                     OS.str());
2493 }
2494 
2495 //===--- CHECK: Return Address of Stack Variable --------------------------===//
2496 
2497 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2498 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2499 
2500 /// CheckReturnStackAddr - Check if a return statement returns the address
2501 ///   of a stack variable.
2502 void
2503 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2504                            SourceLocation ReturnLoc) {
2505 
2506   Expr *stackE = 0;
2507   SmallVector<DeclRefExpr *, 8> refVars;
2508 
2509   // Perform checking for returned stack addresses, local blocks,
2510   // label addresses or references to temporaries.
2511   if (lhsType->isPointerType() ||
2512       (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2513     stackE = EvalAddr(RetValExp, refVars);
2514   } else if (lhsType->isReferenceType()) {
2515     stackE = EvalVal(RetValExp, refVars);
2516   }
2517 
2518   if (stackE == 0)
2519     return; // Nothing suspicious was found.
2520 
2521   SourceLocation diagLoc;
2522   SourceRange diagRange;
2523   if (refVars.empty()) {
2524     diagLoc = stackE->getLocStart();
2525     diagRange = stackE->getSourceRange();
2526   } else {
2527     // We followed through a reference variable. 'stackE' contains the
2528     // problematic expression but we will warn at the return statement pointing
2529     // at the reference variable. We will later display the "trail" of
2530     // reference variables using notes.
2531     diagLoc = refVars[0]->getLocStart();
2532     diagRange = refVars[0]->getSourceRange();
2533   }
2534 
2535   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2536     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2537                                              : diag::warn_ret_stack_addr)
2538      << DR->getDecl()->getDeclName() << diagRange;
2539   } else if (isa<BlockExpr>(stackE)) { // local block.
2540     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2541   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2542     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2543   } else { // local temporary.
2544     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2545                                              : diag::warn_ret_local_temp_addr)
2546      << diagRange;
2547   }
2548 
2549   // Display the "trail" of reference variables that we followed until we
2550   // found the problematic expression using notes.
2551   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2552     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2553     // If this var binds to another reference var, show the range of the next
2554     // var, otherwise the var binds to the problematic expression, in which case
2555     // show the range of the expression.
2556     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2557                                   : stackE->getSourceRange();
2558     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2559       << VD->getDeclName() << range;
2560   }
2561 }
2562 
2563 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2564 ///  check if the expression in a return statement evaluates to an address
2565 ///  to a location on the stack, a local block, an address of a label, or a
2566 ///  reference to local temporary. The recursion is used to traverse the
2567 ///  AST of the return expression, with recursion backtracking when we
2568 ///  encounter a subexpression that (1) clearly does not lead to one of the
2569 ///  above problematic expressions (2) is something we cannot determine leads to
2570 ///  a problematic expression based on such local checking.
2571 ///
2572 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2573 ///  the expression that they point to. Such variables are added to the
2574 ///  'refVars' vector so that we know what the reference variable "trail" was.
2575 ///
2576 ///  EvalAddr processes expressions that are pointers that are used as
2577 ///  references (and not L-values).  EvalVal handles all other values.
2578 ///  At the base case of the recursion is a check for the above problematic
2579 ///  expressions.
2580 ///
2581 ///  This implementation handles:
2582 ///
2583 ///   * pointer-to-pointer casts
2584 ///   * implicit conversions from array references to pointers
2585 ///   * taking the address of fields
2586 ///   * arbitrary interplay between "&" and "*" operators
2587 ///   * pointer arithmetic from an address of a stack variable
2588 ///   * taking the address of an array element where the array is on the stack
2589 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2590   if (E->isTypeDependent())
2591       return NULL;
2592 
2593   // We should only be called for evaluating pointer expressions.
2594   assert((E->getType()->isAnyPointerType() ||
2595           E->getType()->isBlockPointerType() ||
2596           E->getType()->isObjCQualifiedIdType()) &&
2597          "EvalAddr only works on pointers");
2598 
2599   E = E->IgnoreParens();
2600 
2601   // Our "symbolic interpreter" is just a dispatch off the currently
2602   // viewed AST node.  We then recursively traverse the AST by calling
2603   // EvalAddr and EvalVal appropriately.
2604   switch (E->getStmtClass()) {
2605   case Stmt::DeclRefExprClass: {
2606     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2607 
2608     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2609       // If this is a reference variable, follow through to the expression that
2610       // it points to.
2611       if (V->hasLocalStorage() &&
2612           V->getType()->isReferenceType() && V->hasInit()) {
2613         // Add the reference variable to the "trail".
2614         refVars.push_back(DR);
2615         return EvalAddr(V->getInit(), refVars);
2616       }
2617 
2618     return NULL;
2619   }
2620 
2621   case Stmt::UnaryOperatorClass: {
2622     // The only unary operator that make sense to handle here
2623     // is AddrOf.  All others don't make sense as pointers.
2624     UnaryOperator *U = cast<UnaryOperator>(E);
2625 
2626     if (U->getOpcode() == UO_AddrOf)
2627       return EvalVal(U->getSubExpr(), refVars);
2628     else
2629       return NULL;
2630   }
2631 
2632   case Stmt::BinaryOperatorClass: {
2633     // Handle pointer arithmetic.  All other binary operators are not valid
2634     // in this context.
2635     BinaryOperator *B = cast<BinaryOperator>(E);
2636     BinaryOperatorKind op = B->getOpcode();
2637 
2638     if (op != BO_Add && op != BO_Sub)
2639       return NULL;
2640 
2641     Expr *Base = B->getLHS();
2642 
2643     // Determine which argument is the real pointer base.  It could be
2644     // the RHS argument instead of the LHS.
2645     if (!Base->getType()->isPointerType()) Base = B->getRHS();
2646 
2647     assert (Base->getType()->isPointerType());
2648     return EvalAddr(Base, refVars);
2649   }
2650 
2651   // For conditional operators we need to see if either the LHS or RHS are
2652   // valid DeclRefExpr*s.  If one of them is valid, we return it.
2653   case Stmt::ConditionalOperatorClass: {
2654     ConditionalOperator *C = cast<ConditionalOperator>(E);
2655 
2656     // Handle the GNU extension for missing LHS.
2657     if (Expr *lhsExpr = C->getLHS()) {
2658     // In C++, we can have a throw-expression, which has 'void' type.
2659       if (!lhsExpr->getType()->isVoidType())
2660         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2661           return LHS;
2662     }
2663 
2664     // In C++, we can have a throw-expression, which has 'void' type.
2665     if (C->getRHS()->getType()->isVoidType())
2666       return NULL;
2667 
2668     return EvalAddr(C->getRHS(), refVars);
2669   }
2670 
2671   case Stmt::BlockExprClass:
2672     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2673       return E; // local block.
2674     return NULL;
2675 
2676   case Stmt::AddrLabelExprClass:
2677     return E; // address of label.
2678 
2679   case Stmt::ExprWithCleanupsClass:
2680     return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2681 
2682   // For casts, we need to handle conversions from arrays to
2683   // pointer values, and pointer-to-pointer conversions.
2684   case Stmt::ImplicitCastExprClass:
2685   case Stmt::CStyleCastExprClass:
2686   case Stmt::CXXFunctionalCastExprClass:
2687   case Stmt::ObjCBridgedCastExprClass: {
2688     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2689     QualType T = SubExpr->getType();
2690 
2691     if (SubExpr->getType()->isPointerType() ||
2692         SubExpr->getType()->isBlockPointerType() ||
2693         SubExpr->getType()->isObjCQualifiedIdType())
2694       return EvalAddr(SubExpr, refVars);
2695     else if (T->isArrayType())
2696       return EvalVal(SubExpr, refVars);
2697     else
2698       return 0;
2699   }
2700 
2701   // C++ casts.  For dynamic casts, static casts, and const casts, we
2702   // are always converting from a pointer-to-pointer, so we just blow
2703   // through the cast.  In the case the dynamic cast doesn't fail (and
2704   // return NULL), we take the conservative route and report cases
2705   // where we return the address of a stack variable.  For Reinterpre
2706   // FIXME: The comment about is wrong; we're not always converting
2707   // from pointer to pointer. I'm guessing that this code should also
2708   // handle references to objects.
2709   case Stmt::CXXStaticCastExprClass:
2710   case Stmt::CXXDynamicCastExprClass:
2711   case Stmt::CXXConstCastExprClass:
2712   case Stmt::CXXReinterpretCastExprClass: {
2713       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2714       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2715         return EvalAddr(S, refVars);
2716       else
2717         return NULL;
2718   }
2719 
2720   case Stmt::MaterializeTemporaryExprClass:
2721     if (Expr *Result = EvalAddr(
2722                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2723                                 refVars))
2724       return Result;
2725 
2726     return E;
2727 
2728   // Everything else: we simply don't reason about them.
2729   default:
2730     return NULL;
2731   }
2732 }
2733 
2734 
2735 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2736 ///   See the comments for EvalAddr for more details.
2737 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2738 do {
2739   // We should only be called for evaluating non-pointer expressions, or
2740   // expressions with a pointer type that are not used as references but instead
2741   // are l-values (e.g., DeclRefExpr with a pointer type).
2742 
2743   // Our "symbolic interpreter" is just a dispatch off the currently
2744   // viewed AST node.  We then recursively traverse the AST by calling
2745   // EvalAddr and EvalVal appropriately.
2746 
2747   E = E->IgnoreParens();
2748   switch (E->getStmtClass()) {
2749   case Stmt::ImplicitCastExprClass: {
2750     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2751     if (IE->getValueKind() == VK_LValue) {
2752       E = IE->getSubExpr();
2753       continue;
2754     }
2755     return NULL;
2756   }
2757 
2758   case Stmt::ExprWithCleanupsClass:
2759     return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2760 
2761   case Stmt::DeclRefExprClass: {
2762     // When we hit a DeclRefExpr we are looking at code that refers to a
2763     // variable's name. If it's not a reference variable we check if it has
2764     // local storage within the function, and if so, return the expression.
2765     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2766 
2767     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2768       if (V->hasLocalStorage()) {
2769         if (!V->getType()->isReferenceType())
2770           return DR;
2771 
2772         // Reference variable, follow through to the expression that
2773         // it points to.
2774         if (V->hasInit()) {
2775           // Add the reference variable to the "trail".
2776           refVars.push_back(DR);
2777           return EvalVal(V->getInit(), refVars);
2778         }
2779       }
2780 
2781     return NULL;
2782   }
2783 
2784   case Stmt::UnaryOperatorClass: {
2785     // The only unary operator that make sense to handle here
2786     // is Deref.  All others don't resolve to a "name."  This includes
2787     // handling all sorts of rvalues passed to a unary operator.
2788     UnaryOperator *U = cast<UnaryOperator>(E);
2789 
2790     if (U->getOpcode() == UO_Deref)
2791       return EvalAddr(U->getSubExpr(), refVars);
2792 
2793     return NULL;
2794   }
2795 
2796   case Stmt::ArraySubscriptExprClass: {
2797     // Array subscripts are potential references to data on the stack.  We
2798     // retrieve the DeclRefExpr* for the array variable if it indeed
2799     // has local storage.
2800     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2801   }
2802 
2803   case Stmt::ConditionalOperatorClass: {
2804     // For conditional operators we need to see if either the LHS or RHS are
2805     // non-NULL Expr's.  If one is non-NULL, we return it.
2806     ConditionalOperator *C = cast<ConditionalOperator>(E);
2807 
2808     // Handle the GNU extension for missing LHS.
2809     if (Expr *lhsExpr = C->getLHS())
2810       if (Expr *LHS = EvalVal(lhsExpr, refVars))
2811         return LHS;
2812 
2813     return EvalVal(C->getRHS(), refVars);
2814   }
2815 
2816   // Accesses to members are potential references to data on the stack.
2817   case Stmt::MemberExprClass: {
2818     MemberExpr *M = cast<MemberExpr>(E);
2819 
2820     // Check for indirect access.  We only want direct field accesses.
2821     if (M->isArrow())
2822       return NULL;
2823 
2824     // Check whether the member type is itself a reference, in which case
2825     // we're not going to refer to the member, but to what the member refers to.
2826     if (M->getMemberDecl()->getType()->isReferenceType())
2827       return NULL;
2828 
2829     return EvalVal(M->getBase(), refVars);
2830   }
2831 
2832   case Stmt::MaterializeTemporaryExprClass:
2833     if (Expr *Result = EvalVal(
2834                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2835                                refVars))
2836       return Result;
2837 
2838     return E;
2839 
2840   default:
2841     // Check that we don't return or take the address of a reference to a
2842     // temporary. This is only useful in C++.
2843     if (!E->isTypeDependent() && E->isRValue())
2844       return E;
2845 
2846     // Everything else: we simply don't reason about them.
2847     return NULL;
2848   }
2849 } while (true);
2850 }
2851 
2852 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2853 
2854 /// Check for comparisons of floating point operands using != and ==.
2855 /// Issue a warning if these are no self-comparisons, as they are not likely
2856 /// to do what the programmer intended.
2857 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
2858   bool EmitWarning = true;
2859 
2860   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2861   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
2862 
2863   // Special case: check for x == x (which is OK).
2864   // Do not emit warnings for such cases.
2865   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2866     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2867       if (DRL->getDecl() == DRR->getDecl())
2868         EmitWarning = false;
2869 
2870 
2871   // Special case: check for comparisons against literals that can be exactly
2872   //  represented by APFloat.  In such cases, do not emit a warning.  This
2873   //  is a heuristic: often comparison against such literals are used to
2874   //  detect if a value in a variable has not changed.  This clearly can
2875   //  lead to false negatives.
2876   if (EmitWarning) {
2877     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2878       if (FLL->isExact())
2879         EmitWarning = false;
2880     } else
2881       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2882         if (FLR->isExact())
2883           EmitWarning = false;
2884     }
2885   }
2886 
2887   // Check for comparisons with builtin types.
2888   if (EmitWarning)
2889     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2890       if (CL->isBuiltinCall())
2891         EmitWarning = false;
2892 
2893   if (EmitWarning)
2894     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2895       if (CR->isBuiltinCall())
2896         EmitWarning = false;
2897 
2898   // Emit the diagnostic.
2899   if (EmitWarning)
2900     Diag(Loc, diag::warn_floatingpoint_eq)
2901       << LHS->getSourceRange() << RHS->getSourceRange();
2902 }
2903 
2904 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2905 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2906 
2907 namespace {
2908 
2909 /// Structure recording the 'active' range of an integer-valued
2910 /// expression.
2911 struct IntRange {
2912   /// The number of bits active in the int.
2913   unsigned Width;
2914 
2915   /// True if the int is known not to have negative values.
2916   bool NonNegative;
2917 
2918   IntRange(unsigned Width, bool NonNegative)
2919     : Width(Width), NonNegative(NonNegative)
2920   {}
2921 
2922   /// Returns the range of the bool type.
2923   static IntRange forBoolType() {
2924     return IntRange(1, true);
2925   }
2926 
2927   /// Returns the range of an opaque value of the given integral type.
2928   static IntRange forValueOfType(ASTContext &C, QualType T) {
2929     return forValueOfCanonicalType(C,
2930                           T->getCanonicalTypeInternal().getTypePtr());
2931   }
2932 
2933   /// Returns the range of an opaque value of a canonical integral type.
2934   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2935     assert(T->isCanonicalUnqualified());
2936 
2937     if (const VectorType *VT = dyn_cast<VectorType>(T))
2938       T = VT->getElementType().getTypePtr();
2939     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2940       T = CT->getElementType().getTypePtr();
2941 
2942     // For enum types, use the known bit width of the enumerators.
2943     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2944       EnumDecl *Enum = ET->getDecl();
2945       if (!Enum->isCompleteDefinition())
2946         return IntRange(C.getIntWidth(QualType(T, 0)), false);
2947 
2948       unsigned NumPositive = Enum->getNumPositiveBits();
2949       unsigned NumNegative = Enum->getNumNegativeBits();
2950 
2951       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2952     }
2953 
2954     const BuiltinType *BT = cast<BuiltinType>(T);
2955     assert(BT->isInteger());
2956 
2957     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2958   }
2959 
2960   /// Returns the "target" range of a canonical integral type, i.e.
2961   /// the range of values expressible in the type.
2962   ///
2963   /// This matches forValueOfCanonicalType except that enums have the
2964   /// full range of their type, not the range of their enumerators.
2965   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2966     assert(T->isCanonicalUnqualified());
2967 
2968     if (const VectorType *VT = dyn_cast<VectorType>(T))
2969       T = VT->getElementType().getTypePtr();
2970     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2971       T = CT->getElementType().getTypePtr();
2972     if (const EnumType *ET = dyn_cast<EnumType>(T))
2973       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
2974 
2975     const BuiltinType *BT = cast<BuiltinType>(T);
2976     assert(BT->isInteger());
2977 
2978     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2979   }
2980 
2981   /// Returns the supremum of two ranges: i.e. their conservative merge.
2982   static IntRange join(IntRange L, IntRange R) {
2983     return IntRange(std::max(L.Width, R.Width),
2984                     L.NonNegative && R.NonNegative);
2985   }
2986 
2987   /// Returns the infinum of two ranges: i.e. their aggressive merge.
2988   static IntRange meet(IntRange L, IntRange R) {
2989     return IntRange(std::min(L.Width, R.Width),
2990                     L.NonNegative || R.NonNegative);
2991   }
2992 };
2993 
2994 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2995   if (value.isSigned() && value.isNegative())
2996     return IntRange(value.getMinSignedBits(), false);
2997 
2998   if (value.getBitWidth() > MaxWidth)
2999     value = value.trunc(MaxWidth);
3000 
3001   // isNonNegative() just checks the sign bit without considering
3002   // signedness.
3003   return IntRange(value.getActiveBits(), true);
3004 }
3005 
3006 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3007                        unsigned MaxWidth) {
3008   if (result.isInt())
3009     return GetValueRange(C, result.getInt(), MaxWidth);
3010 
3011   if (result.isVector()) {
3012     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3013     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3014       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3015       R = IntRange::join(R, El);
3016     }
3017     return R;
3018   }
3019 
3020   if (result.isComplexInt()) {
3021     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3022     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3023     return IntRange::join(R, I);
3024   }
3025 
3026   // This can happen with lossless casts to intptr_t of "based" lvalues.
3027   // Assume it might use arbitrary bits.
3028   // FIXME: The only reason we need to pass the type in here is to get
3029   // the sign right on this one case.  It would be nice if APValue
3030   // preserved this.
3031   assert(result.isLValue());
3032   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
3033 }
3034 
3035 /// Pseudo-evaluate the given integer expression, estimating the
3036 /// range of values it might take.
3037 ///
3038 /// \param MaxWidth - the width to which the value will be truncated
3039 IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3040   E = E->IgnoreParens();
3041 
3042   // Try a full evaluation first.
3043   Expr::EvalResult result;
3044   if (E->EvaluateAsRValue(result, C))
3045     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
3046 
3047   // I think we only want to look through implicit casts here; if the
3048   // user has an explicit widening cast, we should treat the value as
3049   // being of the new, wider type.
3050   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
3051     if (CE->getCastKind() == CK_NoOp)
3052       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3053 
3054     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
3055 
3056     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
3057 
3058     // Assume that non-integer casts can span the full range of the type.
3059     if (!isIntegerCast)
3060       return OutputTypeRange;
3061 
3062     IntRange SubRange
3063       = GetExprRange(C, CE->getSubExpr(),
3064                      std::min(MaxWidth, OutputTypeRange.Width));
3065 
3066     // Bail out if the subexpr's range is as wide as the cast type.
3067     if (SubRange.Width >= OutputTypeRange.Width)
3068       return OutputTypeRange;
3069 
3070     // Otherwise, we take the smaller width, and we're non-negative if
3071     // either the output type or the subexpr is.
3072     return IntRange(SubRange.Width,
3073                     SubRange.NonNegative || OutputTypeRange.NonNegative);
3074   }
3075 
3076   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3077     // If we can fold the condition, just take that operand.
3078     bool CondResult;
3079     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3080       return GetExprRange(C, CondResult ? CO->getTrueExpr()
3081                                         : CO->getFalseExpr(),
3082                           MaxWidth);
3083 
3084     // Otherwise, conservatively merge.
3085     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3086     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3087     return IntRange::join(L, R);
3088   }
3089 
3090   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3091     switch (BO->getOpcode()) {
3092 
3093     // Boolean-valued operations are single-bit and positive.
3094     case BO_LAnd:
3095     case BO_LOr:
3096     case BO_LT:
3097     case BO_GT:
3098     case BO_LE:
3099     case BO_GE:
3100     case BO_EQ:
3101     case BO_NE:
3102       return IntRange::forBoolType();
3103 
3104     // The type of the assignments is the type of the LHS, so the RHS
3105     // is not necessarily the same type.
3106     case BO_MulAssign:
3107     case BO_DivAssign:
3108     case BO_RemAssign:
3109     case BO_AddAssign:
3110     case BO_SubAssign:
3111     case BO_XorAssign:
3112     case BO_OrAssign:
3113       // TODO: bitfields?
3114       return IntRange::forValueOfType(C, E->getType());
3115 
3116     // Simple assignments just pass through the RHS, which will have
3117     // been coerced to the LHS type.
3118     case BO_Assign:
3119       // TODO: bitfields?
3120       return GetExprRange(C, BO->getRHS(), MaxWidth);
3121 
3122     // Operations with opaque sources are black-listed.
3123     case BO_PtrMemD:
3124     case BO_PtrMemI:
3125       return IntRange::forValueOfType(C, E->getType());
3126 
3127     // Bitwise-and uses the *infinum* of the two source ranges.
3128     case BO_And:
3129     case BO_AndAssign:
3130       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3131                             GetExprRange(C, BO->getRHS(), MaxWidth));
3132 
3133     // Left shift gets black-listed based on a judgement call.
3134     case BO_Shl:
3135       // ...except that we want to treat '1 << (blah)' as logically
3136       // positive.  It's an important idiom.
3137       if (IntegerLiteral *I
3138             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3139         if (I->getValue() == 1) {
3140           IntRange R = IntRange::forValueOfType(C, E->getType());
3141           return IntRange(R.Width, /*NonNegative*/ true);
3142         }
3143       }
3144       // fallthrough
3145 
3146     case BO_ShlAssign:
3147       return IntRange::forValueOfType(C, E->getType());
3148 
3149     // Right shift by a constant can narrow its left argument.
3150     case BO_Shr:
3151     case BO_ShrAssign: {
3152       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3153 
3154       // If the shift amount is a positive constant, drop the width by
3155       // that much.
3156       llvm::APSInt shift;
3157       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3158           shift.isNonNegative()) {
3159         unsigned zext = shift.getZExtValue();
3160         if (zext >= L.Width)
3161           L.Width = (L.NonNegative ? 0 : 1);
3162         else
3163           L.Width -= zext;
3164       }
3165 
3166       return L;
3167     }
3168 
3169     // Comma acts as its right operand.
3170     case BO_Comma:
3171       return GetExprRange(C, BO->getRHS(), MaxWidth);
3172 
3173     // Black-list pointer subtractions.
3174     case BO_Sub:
3175       if (BO->getLHS()->getType()->isPointerType())
3176         return IntRange::forValueOfType(C, E->getType());
3177       break;
3178 
3179     // The width of a division result is mostly determined by the size
3180     // of the LHS.
3181     case BO_Div: {
3182       // Don't 'pre-truncate' the operands.
3183       unsigned opWidth = C.getIntWidth(E->getType());
3184       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3185 
3186       // If the divisor is constant, use that.
3187       llvm::APSInt divisor;
3188       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3189         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3190         if (log2 >= L.Width)
3191           L.Width = (L.NonNegative ? 0 : 1);
3192         else
3193           L.Width = std::min(L.Width - log2, MaxWidth);
3194         return L;
3195       }
3196 
3197       // Otherwise, just use the LHS's width.
3198       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3199       return IntRange(L.Width, L.NonNegative && R.NonNegative);
3200     }
3201 
3202     // The result of a remainder can't be larger than the result of
3203     // either side.
3204     case BO_Rem: {
3205       // Don't 'pre-truncate' the operands.
3206       unsigned opWidth = C.getIntWidth(E->getType());
3207       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3208       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3209 
3210       IntRange meet = IntRange::meet(L, R);
3211       meet.Width = std::min(meet.Width, MaxWidth);
3212       return meet;
3213     }
3214 
3215     // The default behavior is okay for these.
3216     case BO_Mul:
3217     case BO_Add:
3218     case BO_Xor:
3219     case BO_Or:
3220       break;
3221     }
3222 
3223     // The default case is to treat the operation as if it were closed
3224     // on the narrowest type that encompasses both operands.
3225     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3226     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3227     return IntRange::join(L, R);
3228   }
3229 
3230   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3231     switch (UO->getOpcode()) {
3232     // Boolean-valued operations are white-listed.
3233     case UO_LNot:
3234       return IntRange::forBoolType();
3235 
3236     // Operations with opaque sources are black-listed.
3237     case UO_Deref:
3238     case UO_AddrOf: // should be impossible
3239       return IntRange::forValueOfType(C, E->getType());
3240 
3241     default:
3242       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3243     }
3244   }
3245 
3246   if (dyn_cast<OffsetOfExpr>(E)) {
3247     IntRange::forValueOfType(C, E->getType());
3248   }
3249 
3250   if (FieldDecl *BitField = E->getBitField())
3251     return IntRange(BitField->getBitWidthValue(C),
3252                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
3253 
3254   return IntRange::forValueOfType(C, E->getType());
3255 }
3256 
3257 IntRange GetExprRange(ASTContext &C, Expr *E) {
3258   return GetExprRange(C, E, C.getIntWidth(E->getType()));
3259 }
3260 
3261 /// Checks whether the given value, which currently has the given
3262 /// source semantics, has the same value when coerced through the
3263 /// target semantics.
3264 bool IsSameFloatAfterCast(const llvm::APFloat &value,
3265                           const llvm::fltSemantics &Src,
3266                           const llvm::fltSemantics &Tgt) {
3267   llvm::APFloat truncated = value;
3268 
3269   bool ignored;
3270   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3271   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3272 
3273   return truncated.bitwiseIsEqual(value);
3274 }
3275 
3276 /// Checks whether the given value, which currently has the given
3277 /// source semantics, has the same value when coerced through the
3278 /// target semantics.
3279 ///
3280 /// The value might be a vector of floats (or a complex number).
3281 bool IsSameFloatAfterCast(const APValue &value,
3282                           const llvm::fltSemantics &Src,
3283                           const llvm::fltSemantics &Tgt) {
3284   if (value.isFloat())
3285     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3286 
3287   if (value.isVector()) {
3288     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3289       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3290         return false;
3291     return true;
3292   }
3293 
3294   assert(value.isComplexFloat());
3295   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3296           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3297 }
3298 
3299 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3300 
3301 static bool IsZero(Sema &S, Expr *E) {
3302   // Suppress cases where we are comparing against an enum constant.
3303   if (const DeclRefExpr *DR =
3304       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3305     if (isa<EnumConstantDecl>(DR->getDecl()))
3306       return false;
3307 
3308   // Suppress cases where the '0' value is expanded from a macro.
3309   if (E->getLocStart().isMacroID())
3310     return false;
3311 
3312   llvm::APSInt Value;
3313   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3314 }
3315 
3316 static bool HasEnumType(Expr *E) {
3317   // Strip off implicit integral promotions.
3318   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3319     if (ICE->getCastKind() != CK_IntegralCast &&
3320         ICE->getCastKind() != CK_NoOp)
3321       break;
3322     E = ICE->getSubExpr();
3323   }
3324 
3325   return E->getType()->isEnumeralType();
3326 }
3327 
3328 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3329   BinaryOperatorKind op = E->getOpcode();
3330   if (E->isValueDependent())
3331     return;
3332 
3333   if (op == BO_LT && IsZero(S, E->getRHS())) {
3334     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3335       << "< 0" << "false" << HasEnumType(E->getLHS())
3336       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3337   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3338     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3339       << ">= 0" << "true" << HasEnumType(E->getLHS())
3340       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3341   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3342     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3343       << "0 >" << "false" << HasEnumType(E->getRHS())
3344       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3345   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3346     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3347       << "0 <=" << "true" << HasEnumType(E->getRHS())
3348       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3349   }
3350 }
3351 
3352 /// Analyze the operands of the given comparison.  Implements the
3353 /// fallback case from AnalyzeComparison.
3354 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3355   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3356   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3357 }
3358 
3359 /// \brief Implements -Wsign-compare.
3360 ///
3361 /// \param E the binary operator to check for warnings
3362 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3363   // The type the comparison is being performed in.
3364   QualType T = E->getLHS()->getType();
3365   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3366          && "comparison with mismatched types");
3367 
3368   // We don't do anything special if this isn't an unsigned integral
3369   // comparison:  we're only interested in integral comparisons, and
3370   // signed comparisons only happen in cases we don't care to warn about.
3371   //
3372   // We also don't care about value-dependent expressions or expressions
3373   // whose result is a constant.
3374   if (!T->hasUnsignedIntegerRepresentation()
3375       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3376     return AnalyzeImpConvsInComparison(S, E);
3377 
3378   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3379   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3380 
3381   // Check to see if one of the (unmodified) operands is of different
3382   // signedness.
3383   Expr *signedOperand, *unsignedOperand;
3384   if (LHS->getType()->hasSignedIntegerRepresentation()) {
3385     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3386            "unsigned comparison between two signed integer expressions?");
3387     signedOperand = LHS;
3388     unsignedOperand = RHS;
3389   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3390     signedOperand = RHS;
3391     unsignedOperand = LHS;
3392   } else {
3393     CheckTrivialUnsignedComparison(S, E);
3394     return AnalyzeImpConvsInComparison(S, E);
3395   }
3396 
3397   // Otherwise, calculate the effective range of the signed operand.
3398   IntRange signedRange = GetExprRange(S.Context, signedOperand);
3399 
3400   // Go ahead and analyze implicit conversions in the operands.  Note
3401   // that we skip the implicit conversions on both sides.
3402   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3403   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3404 
3405   // If the signed range is non-negative, -Wsign-compare won't fire,
3406   // but we should still check for comparisons which are always true
3407   // or false.
3408   if (signedRange.NonNegative)
3409     return CheckTrivialUnsignedComparison(S, E);
3410 
3411   // For (in)equality comparisons, if the unsigned operand is a
3412   // constant which cannot collide with a overflowed signed operand,
3413   // then reinterpreting the signed operand as unsigned will not
3414   // change the result of the comparison.
3415   if (E->isEqualityOp()) {
3416     unsigned comparisonWidth = S.Context.getIntWidth(T);
3417     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3418 
3419     // We should never be unable to prove that the unsigned operand is
3420     // non-negative.
3421     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3422 
3423     if (unsignedRange.Width < comparisonWidth)
3424       return;
3425   }
3426 
3427   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3428     << LHS->getType() << RHS->getType()
3429     << LHS->getSourceRange() << RHS->getSourceRange();
3430 }
3431 
3432 /// Analyzes an attempt to assign the given value to a bitfield.
3433 ///
3434 /// Returns true if there was something fishy about the attempt.
3435 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3436                                SourceLocation InitLoc) {
3437   assert(Bitfield->isBitField());
3438   if (Bitfield->isInvalidDecl())
3439     return false;
3440 
3441   // White-list bool bitfields.
3442   if (Bitfield->getType()->isBooleanType())
3443     return false;
3444 
3445   // Ignore value- or type-dependent expressions.
3446   if (Bitfield->getBitWidth()->isValueDependent() ||
3447       Bitfield->getBitWidth()->isTypeDependent() ||
3448       Init->isValueDependent() ||
3449       Init->isTypeDependent())
3450     return false;
3451 
3452   Expr *OriginalInit = Init->IgnoreParenImpCasts();
3453 
3454   Expr::EvalResult InitValue;
3455   if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
3456       !InitValue.Val.isInt())
3457     return false;
3458 
3459   const llvm::APSInt &Value = InitValue.Val.getInt();
3460   unsigned OriginalWidth = Value.getBitWidth();
3461   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3462 
3463   if (OriginalWidth <= FieldWidth)
3464     return false;
3465 
3466   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3467 
3468   // It's fairly common to write values into signed bitfields
3469   // that, if sign-extended, would end up becoming a different
3470   // value.  We don't want to warn about that.
3471   if (Value.isSigned() && Value.isNegative())
3472     TruncatedValue = TruncatedValue.sext(OriginalWidth);
3473   else
3474     TruncatedValue = TruncatedValue.zext(OriginalWidth);
3475 
3476   if (Value == TruncatedValue)
3477     return false;
3478 
3479   std::string PrettyValue = Value.toString(10);
3480   std::string PrettyTrunc = TruncatedValue.toString(10);
3481 
3482   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3483     << PrettyValue << PrettyTrunc << OriginalInit->getType()
3484     << Init->getSourceRange();
3485 
3486   return true;
3487 }
3488 
3489 /// Analyze the given simple or compound assignment for warning-worthy
3490 /// operations.
3491 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3492   // Just recurse on the LHS.
3493   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3494 
3495   // We want to recurse on the RHS as normal unless we're assigning to
3496   // a bitfield.
3497   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3498     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3499                                   E->getOperatorLoc())) {
3500       // Recurse, ignoring any implicit conversions on the RHS.
3501       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3502                                         E->getOperatorLoc());
3503     }
3504   }
3505 
3506   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3507 }
3508 
3509 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3510 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3511                      SourceLocation CContext, unsigned diag) {
3512   S.Diag(E->getExprLoc(), diag)
3513     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3514 }
3515 
3516 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3517 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3518                      unsigned diag) {
3519   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3520 }
3521 
3522 /// Diagnose an implicit cast from a literal expression. Does not warn when the
3523 /// cast wouldn't lose information.
3524 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3525                                     SourceLocation CContext) {
3526   // Try to convert the literal exactly to an integer. If we can, don't warn.
3527   bool isExact = false;
3528   const llvm::APFloat &Value = FL->getValue();
3529   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3530                             T->hasUnsignedIntegerRepresentation());
3531   if (Value.convertToInteger(IntegerValue,
3532                              llvm::APFloat::rmTowardZero, &isExact)
3533       == llvm::APFloat::opOK && isExact)
3534     return;
3535 
3536   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3537     << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3538 }
3539 
3540 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3541   if (!Range.Width) return "0";
3542 
3543   llvm::APSInt ValueInRange = Value;
3544   ValueInRange.setIsSigned(!Range.NonNegative);
3545   ValueInRange = ValueInRange.trunc(Range.Width);
3546   return ValueInRange.toString(10);
3547 }
3548 
3549 static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3550   SourceManager &smgr = S.Context.getSourceManager();
3551   return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3552 }
3553 
3554 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3555                              SourceLocation CC, bool *ICContext = 0) {
3556   if (E->isTypeDependent() || E->isValueDependent()) return;
3557 
3558   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3559   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3560   if (Source == Target) return;
3561   if (Target->isDependentType()) return;
3562 
3563   // If the conversion context location is invalid don't complain. We also
3564   // don't want to emit a warning if the issue occurs from the expansion of
3565   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3566   // delay this check as long as possible. Once we detect we are in that
3567   // scenario, we just return.
3568   if (CC.isInvalid())
3569     return;
3570 
3571   // Diagnose implicit casts to bool.
3572   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3573     if (isa<StringLiteral>(E))
3574       // Warn on string literal to bool.  Checks for string literals in logical
3575       // expressions, for instances, assert(0 && "error here"), is prevented
3576       // by a check in AnalyzeImplicitConversions().
3577       return DiagnoseImpCast(S, E, T, CC,
3578                              diag::warn_impcast_string_literal_to_bool);
3579     return; // Other casts to bool are not checked.
3580   }
3581 
3582   // Strip vector types.
3583   if (isa<VectorType>(Source)) {
3584     if (!isa<VectorType>(Target)) {
3585       if (isFromSystemMacro(S, CC))
3586         return;
3587       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3588     }
3589 
3590     // If the vector cast is cast between two vectors of the same size, it is
3591     // a bitcast, not a conversion.
3592     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3593       return;
3594 
3595     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3596     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3597   }
3598 
3599   // Strip complex types.
3600   if (isa<ComplexType>(Source)) {
3601     if (!isa<ComplexType>(Target)) {
3602       if (isFromSystemMacro(S, CC))
3603         return;
3604 
3605       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3606     }
3607 
3608     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3609     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3610   }
3611 
3612   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3613   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3614 
3615   // If the source is floating point...
3616   if (SourceBT && SourceBT->isFloatingPoint()) {
3617     // ...and the target is floating point...
3618     if (TargetBT && TargetBT->isFloatingPoint()) {
3619       // ...then warn if we're dropping FP rank.
3620 
3621       // Builtin FP kinds are ordered by increasing FP rank.
3622       if (SourceBT->getKind() > TargetBT->getKind()) {
3623         // Don't warn about float constants that are precisely
3624         // representable in the target type.
3625         Expr::EvalResult result;
3626         if (E->EvaluateAsRValue(result, S.Context)) {
3627           // Value might be a float, a float vector, or a float complex.
3628           if (IsSameFloatAfterCast(result.Val,
3629                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3630                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3631             return;
3632         }
3633 
3634         if (isFromSystemMacro(S, CC))
3635           return;
3636 
3637         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3638       }
3639       return;
3640     }
3641 
3642     // If the target is integral, always warn.
3643     if ((TargetBT && TargetBT->isInteger())) {
3644       if (isFromSystemMacro(S, CC))
3645         return;
3646 
3647       Expr *InnerE = E->IgnoreParenImpCasts();
3648       // We also want to warn on, e.g., "int i = -1.234"
3649       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3650         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3651           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3652 
3653       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3654         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3655       } else {
3656         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3657       }
3658     }
3659 
3660     return;
3661   }
3662 
3663   if (!Source->isIntegerType() || !Target->isIntegerType())
3664     return;
3665 
3666   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3667            == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3668     S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3669         << E->getSourceRange() << clang::SourceRange(CC);
3670     return;
3671   }
3672 
3673   IntRange SourceRange = GetExprRange(S.Context, E);
3674   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3675 
3676   if (SourceRange.Width > TargetRange.Width) {
3677     // If the source is a constant, use a default-on diagnostic.
3678     // TODO: this should happen for bitfield stores, too.
3679     llvm::APSInt Value(32);
3680     if (E->isIntegerConstantExpr(Value, S.Context)) {
3681       if (isFromSystemMacro(S, CC))
3682         return;
3683 
3684       std::string PrettySourceValue = Value.toString(10);
3685       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3686 
3687       S.DiagRuntimeBehavior(E->getExprLoc(), E,
3688         S.PDiag(diag::warn_impcast_integer_precision_constant)
3689             << PrettySourceValue << PrettyTargetValue
3690             << E->getType() << T << E->getSourceRange()
3691             << clang::SourceRange(CC));
3692       return;
3693     }
3694 
3695     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3696     if (isFromSystemMacro(S, CC))
3697       return;
3698 
3699     if (SourceRange.Width == 64 && TargetRange.Width == 32)
3700       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3701     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3702   }
3703 
3704   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3705       (!TargetRange.NonNegative && SourceRange.NonNegative &&
3706        SourceRange.Width == TargetRange.Width)) {
3707 
3708     if (isFromSystemMacro(S, CC))
3709       return;
3710 
3711     unsigned DiagID = diag::warn_impcast_integer_sign;
3712 
3713     // Traditionally, gcc has warned about this under -Wsign-compare.
3714     // We also want to warn about it in -Wconversion.
3715     // So if -Wconversion is off, use a completely identical diagnostic
3716     // in the sign-compare group.
3717     // The conditional-checking code will
3718     if (ICContext) {
3719       DiagID = diag::warn_impcast_integer_sign_conditional;
3720       *ICContext = true;
3721     }
3722 
3723     return DiagnoseImpCast(S, E, T, CC, DiagID);
3724   }
3725 
3726   // Diagnose conversions between different enumeration types.
3727   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3728   // type, to give us better diagnostics.
3729   QualType SourceType = E->getType();
3730   if (!S.getLangOptions().CPlusPlus) {
3731     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3732       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3733         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3734         SourceType = S.Context.getTypeDeclType(Enum);
3735         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3736       }
3737   }
3738 
3739   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3740     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3741       if ((SourceEnum->getDecl()->getIdentifier() ||
3742            SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3743           (TargetEnum->getDecl()->getIdentifier() ||
3744            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3745           SourceEnum != TargetEnum) {
3746         if (isFromSystemMacro(S, CC))
3747           return;
3748 
3749         return DiagnoseImpCast(S, E, SourceType, T, CC,
3750                                diag::warn_impcast_different_enum_types);
3751       }
3752 
3753   return;
3754 }
3755 
3756 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3757 
3758 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3759                              SourceLocation CC, bool &ICContext) {
3760   E = E->IgnoreParenImpCasts();
3761 
3762   if (isa<ConditionalOperator>(E))
3763     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3764 
3765   AnalyzeImplicitConversions(S, E, CC);
3766   if (E->getType() != T)
3767     return CheckImplicitConversion(S, E, T, CC, &ICContext);
3768   return;
3769 }
3770 
3771 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
3772   SourceLocation CC = E->getQuestionLoc();
3773 
3774   AnalyzeImplicitConversions(S, E->getCond(), CC);
3775 
3776   bool Suspicious = false;
3777   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3778   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
3779 
3780   // If -Wconversion would have warned about either of the candidates
3781   // for a signedness conversion to the context type...
3782   if (!Suspicious) return;
3783 
3784   // ...but it's currently ignored...
3785   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3786                                  CC))
3787     return;
3788 
3789   // ...then check whether it would have warned about either of the
3790   // candidates for a signedness conversion to the condition type.
3791   if (E->getType() == T) return;
3792 
3793   Suspicious = false;
3794   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3795                           E->getType(), CC, &Suspicious);
3796   if (!Suspicious)
3797     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
3798                             E->getType(), CC, &Suspicious);
3799 }
3800 
3801 /// AnalyzeImplicitConversions - Find and report any interesting
3802 /// implicit conversions in the given expression.  There are a couple
3803 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
3804 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3805   QualType T = OrigE->getType();
3806   Expr *E = OrigE->IgnoreParenImpCasts();
3807 
3808   if (E->isTypeDependent() || E->isValueDependent())
3809     return;
3810 
3811   // For conditional operators, we analyze the arguments as if they
3812   // were being fed directly into the output.
3813   if (isa<ConditionalOperator>(E)) {
3814     ConditionalOperator *CO = cast<ConditionalOperator>(E);
3815     CheckConditionalOperator(S, CO, T);
3816     return;
3817   }
3818 
3819   // Go ahead and check any implicit conversions we might have skipped.
3820   // The non-canonical typecheck is just an optimization;
3821   // CheckImplicitConversion will filter out dead implicit conversions.
3822   if (E->getType() != T)
3823     CheckImplicitConversion(S, E, T, CC);
3824 
3825   // Now continue drilling into this expression.
3826 
3827   // Skip past explicit casts.
3828   if (isa<ExplicitCastExpr>(E)) {
3829     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3830     return AnalyzeImplicitConversions(S, E, CC);
3831   }
3832 
3833   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3834     // Do a somewhat different check with comparison operators.
3835     if (BO->isComparisonOp())
3836       return AnalyzeComparison(S, BO);
3837 
3838     // And with assignments and compound assignments.
3839     if (BO->isAssignmentOp())
3840       return AnalyzeAssignment(S, BO);
3841   }
3842 
3843   // These break the otherwise-useful invariant below.  Fortunately,
3844   // we don't really need to recurse into them, because any internal
3845   // expressions should have been analyzed already when they were
3846   // built into statements.
3847   if (isa<StmtExpr>(E)) return;
3848 
3849   // Don't descend into unevaluated contexts.
3850   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3851 
3852   // Now just recurse over the expression's children.
3853   CC = E->getExprLoc();
3854   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3855   bool IsLogicalOperator = BO && BO->isLogicalOp();
3856   for (Stmt::child_range I = E->children(); I; ++I) {
3857     Expr *ChildExpr = cast<Expr>(*I);
3858     if (IsLogicalOperator &&
3859         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3860       // Ignore checking string literals that are in logical operators.
3861       continue;
3862     AnalyzeImplicitConversions(S, ChildExpr, CC);
3863   }
3864 }
3865 
3866 } // end anonymous namespace
3867 
3868 /// Diagnoses "dangerous" implicit conversions within the given
3869 /// expression (which is a full expression).  Implements -Wconversion
3870 /// and -Wsign-compare.
3871 ///
3872 /// \param CC the "context" location of the implicit conversion, i.e.
3873 ///   the most location of the syntactic entity requiring the implicit
3874 ///   conversion
3875 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3876   // Don't diagnose in unevaluated contexts.
3877   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3878     return;
3879 
3880   // Don't diagnose for value- or type-dependent expressions.
3881   if (E->isTypeDependent() || E->isValueDependent())
3882     return;
3883 
3884   // Check for array bounds violations in cases where the check isn't triggered
3885   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3886   // ArraySubscriptExpr is on the RHS of a variable initialization.
3887   CheckArrayAccess(E);
3888 
3889   // This is not the right CC for (e.g.) a variable initialization.
3890   AnalyzeImplicitConversions(*this, E, CC);
3891 }
3892 
3893 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3894                                        FieldDecl *BitField,
3895                                        Expr *Init) {
3896   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3897 }
3898 
3899 /// CheckParmsForFunctionDef - Check that the parameters of the given
3900 /// function are appropriate for the definition of a function. This
3901 /// takes care of any checks that cannot be performed on the
3902 /// declaration itself, e.g., that the types of each of the function
3903 /// parameters are complete.
3904 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3905                                     bool CheckParameterNames) {
3906   bool HasInvalidParm = false;
3907   for (; P != PEnd; ++P) {
3908     ParmVarDecl *Param = *P;
3909 
3910     // C99 6.7.5.3p4: the parameters in a parameter type list in a
3911     // function declarator that is part of a function definition of
3912     // that function shall not have incomplete type.
3913     //
3914     // This is also C++ [dcl.fct]p6.
3915     if (!Param->isInvalidDecl() &&
3916         RequireCompleteType(Param->getLocation(), Param->getType(),
3917                                diag::err_typecheck_decl_incomplete_type)) {
3918       Param->setInvalidDecl();
3919       HasInvalidParm = true;
3920     }
3921 
3922     // C99 6.9.1p5: If the declarator includes a parameter type list, the
3923     // declaration of each parameter shall include an identifier.
3924     if (CheckParameterNames &&
3925         Param->getIdentifier() == 0 &&
3926         !Param->isImplicit() &&
3927         !getLangOptions().CPlusPlus)
3928       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3929 
3930     // C99 6.7.5.3p12:
3931     //   If the function declarator is not part of a definition of that
3932     //   function, parameters may have incomplete type and may use the [*]
3933     //   notation in their sequences of declarator specifiers to specify
3934     //   variable length array types.
3935     QualType PType = Param->getOriginalType();
3936     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3937       if (AT->getSizeModifier() == ArrayType::Star) {
3938         // FIXME: This diagnosic should point the the '[*]' if source-location
3939         // information is added for it.
3940         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3941       }
3942     }
3943   }
3944 
3945   return HasInvalidParm;
3946 }
3947 
3948 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3949 /// pointer cast increases the alignment requirements.
3950 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3951   // This is actually a lot of work to potentially be doing on every
3952   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3953   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3954                                           TRange.getBegin())
3955         == DiagnosticsEngine::Ignored)
3956     return;
3957 
3958   // Ignore dependent types.
3959   if (T->isDependentType() || Op->getType()->isDependentType())
3960     return;
3961 
3962   // Require that the destination be a pointer type.
3963   const PointerType *DestPtr = T->getAs<PointerType>();
3964   if (!DestPtr) return;
3965 
3966   // If the destination has alignment 1, we're done.
3967   QualType DestPointee = DestPtr->getPointeeType();
3968   if (DestPointee->isIncompleteType()) return;
3969   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3970   if (DestAlign.isOne()) return;
3971 
3972   // Require that the source be a pointer type.
3973   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3974   if (!SrcPtr) return;
3975   QualType SrcPointee = SrcPtr->getPointeeType();
3976 
3977   // Whitelist casts from cv void*.  We already implicitly
3978   // whitelisted casts to cv void*, since they have alignment 1.
3979   // Also whitelist casts involving incomplete types, which implicitly
3980   // includes 'void'.
3981   if (SrcPointee->isIncompleteType()) return;
3982 
3983   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3984   if (SrcAlign >= DestAlign) return;
3985 
3986   Diag(TRange.getBegin(), diag::warn_cast_align)
3987     << Op->getType() << T
3988     << static_cast<unsigned>(SrcAlign.getQuantity())
3989     << static_cast<unsigned>(DestAlign.getQuantity())
3990     << TRange << Op->getSourceRange();
3991 }
3992 
3993 static const Type* getElementType(const Expr *BaseExpr) {
3994   const Type* EltType = BaseExpr->getType().getTypePtr();
3995   if (EltType->isAnyPointerType())
3996     return EltType->getPointeeType().getTypePtr();
3997   else if (EltType->isArrayType())
3998     return EltType->getBaseElementTypeUnsafe();
3999   return EltType;
4000 }
4001 
4002 /// \brief Check whether this array fits the idiom of a size-one tail padded
4003 /// array member of a struct.
4004 ///
4005 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
4006 /// commonly used to emulate flexible arrays in C89 code.
4007 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4008                                     const NamedDecl *ND) {
4009   if (Size != 1 || !ND) return false;
4010 
4011   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4012   if (!FD) return false;
4013 
4014   // Don't consider sizes resulting from macro expansions or template argument
4015   // substitution to form C89 tail-padded arrays.
4016   ConstantArrayTypeLoc TL =
4017     cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4018   const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4019   if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4020     return false;
4021 
4022   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4023   if (!RD || !RD->isStruct())
4024     return false;
4025 
4026   // See if this is the last field decl in the record.
4027   const Decl *D = FD;
4028   while ((D = D->getNextDeclInContext()))
4029     if (isa<FieldDecl>(D))
4030       return false;
4031   return true;
4032 }
4033 
4034 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4035                             bool isSubscript, bool AllowOnePastEnd) {
4036   const Type* EffectiveType = getElementType(BaseExpr);
4037   BaseExpr = BaseExpr->IgnoreParenCasts();
4038   IndexExpr = IndexExpr->IgnoreParenCasts();
4039 
4040   const ConstantArrayType *ArrayTy =
4041     Context.getAsConstantArrayType(BaseExpr->getType());
4042   if (!ArrayTy)
4043     return;
4044 
4045   if (IndexExpr->isValueDependent())
4046     return;
4047   llvm::APSInt index;
4048   if (!IndexExpr->isIntegerConstantExpr(index, Context))
4049     return;
4050 
4051   const NamedDecl *ND = NULL;
4052   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4053     ND = dyn_cast<NamedDecl>(DRE->getDecl());
4054   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4055     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4056 
4057   if (index.isUnsigned() || !index.isNegative()) {
4058     llvm::APInt size = ArrayTy->getSize();
4059     if (!size.isStrictlyPositive())
4060       return;
4061 
4062     const Type* BaseType = getElementType(BaseExpr);
4063     if (BaseType != EffectiveType) {
4064       // Make sure we're comparing apples to apples when comparing index to size
4065       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4066       uint64_t array_typesize = Context.getTypeSize(BaseType);
4067       // Handle ptrarith_typesize being zero, such as when casting to void*
4068       if (!ptrarith_typesize) ptrarith_typesize = 1;
4069       if (ptrarith_typesize != array_typesize) {
4070         // There's a cast to a different size type involved
4071         uint64_t ratio = array_typesize / ptrarith_typesize;
4072         // TODO: Be smarter about handling cases where array_typesize is not a
4073         // multiple of ptrarith_typesize
4074         if (ptrarith_typesize * ratio == array_typesize)
4075           size *= llvm::APInt(size.getBitWidth(), ratio);
4076       }
4077     }
4078 
4079     if (size.getBitWidth() > index.getBitWidth())
4080       index = index.sext(size.getBitWidth());
4081     else if (size.getBitWidth() < index.getBitWidth())
4082       size = size.sext(index.getBitWidth());
4083 
4084     // For array subscripting the index must be less than size, but for pointer
4085     // arithmetic also allow the index (offset) to be equal to size since
4086     // computing the next address after the end of the array is legal and
4087     // commonly done e.g. in C++ iterators and range-based for loops.
4088     if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
4089       return;
4090 
4091     // Also don't warn for arrays of size 1 which are members of some
4092     // structure. These are often used to approximate flexible arrays in C89
4093     // code.
4094     if (IsTailPaddedMemberArray(*this, size, ND))
4095       return;
4096 
4097     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4098     if (isSubscript)
4099       DiagID = diag::warn_array_index_exceeds_bounds;
4100 
4101     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4102                         PDiag(DiagID) << index.toString(10, true)
4103                           << size.toString(10, true)
4104                           << (unsigned)size.getLimitedValue(~0U)
4105                           << IndexExpr->getSourceRange());
4106   } else {
4107     unsigned DiagID = diag::warn_array_index_precedes_bounds;
4108     if (!isSubscript) {
4109       DiagID = diag::warn_ptr_arith_precedes_bounds;
4110       if (index.isNegative()) index = -index;
4111     }
4112 
4113     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4114                         PDiag(DiagID) << index.toString(10, true)
4115                           << IndexExpr->getSourceRange());
4116   }
4117 
4118   if (ND)
4119     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4120                         PDiag(diag::note_array_index_out_of_bounds)
4121                           << ND->getDeclName());
4122 }
4123 
4124 void Sema::CheckArrayAccess(const Expr *expr) {
4125   int AllowOnePastEnd = 0;
4126   while (expr) {
4127     expr = expr->IgnoreParenImpCasts();
4128     switch (expr->getStmtClass()) {
4129       case Stmt::ArraySubscriptExprClass: {
4130         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4131         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4132                          AllowOnePastEnd > 0);
4133         return;
4134       }
4135       case Stmt::UnaryOperatorClass: {
4136         // Only unwrap the * and & unary operators
4137         const UnaryOperator *UO = cast<UnaryOperator>(expr);
4138         expr = UO->getSubExpr();
4139         switch (UO->getOpcode()) {
4140           case UO_AddrOf:
4141             AllowOnePastEnd++;
4142             break;
4143           case UO_Deref:
4144             AllowOnePastEnd--;
4145             break;
4146           default:
4147             return;
4148         }
4149         break;
4150       }
4151       case Stmt::ConditionalOperatorClass: {
4152         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4153         if (const Expr *lhs = cond->getLHS())
4154           CheckArrayAccess(lhs);
4155         if (const Expr *rhs = cond->getRHS())
4156           CheckArrayAccess(rhs);
4157         return;
4158       }
4159       default:
4160         return;
4161     }
4162   }
4163 }
4164 
4165 //===--- CHECK: Objective-C retain cycles ----------------------------------//
4166 
4167 namespace {
4168   struct RetainCycleOwner {
4169     RetainCycleOwner() : Variable(0), Indirect(false) {}
4170     VarDecl *Variable;
4171     SourceRange Range;
4172     SourceLocation Loc;
4173     bool Indirect;
4174 
4175     void setLocsFrom(Expr *e) {
4176       Loc = e->getExprLoc();
4177       Range = e->getSourceRange();
4178     }
4179   };
4180 }
4181 
4182 /// Consider whether capturing the given variable can possibly lead to
4183 /// a retain cycle.
4184 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4185   // In ARC, it's captured strongly iff the variable has __strong
4186   // lifetime.  In MRR, it's captured strongly if the variable is
4187   // __block and has an appropriate type.
4188   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4189     return false;
4190 
4191   owner.Variable = var;
4192   owner.setLocsFrom(ref);
4193   return true;
4194 }
4195 
4196 static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4197   while (true) {
4198     e = e->IgnoreParens();
4199     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4200       switch (cast->getCastKind()) {
4201       case CK_BitCast:
4202       case CK_LValueBitCast:
4203       case CK_LValueToRValue:
4204       case CK_ARCReclaimReturnedObject:
4205         e = cast->getSubExpr();
4206         continue;
4207 
4208       default:
4209         return false;
4210       }
4211     }
4212 
4213     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4214       ObjCIvarDecl *ivar = ref->getDecl();
4215       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4216         return false;
4217 
4218       // Try to find a retain cycle in the base.
4219       if (!findRetainCycleOwner(ref->getBase(), owner))
4220         return false;
4221 
4222       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4223       owner.Indirect = true;
4224       return true;
4225     }
4226 
4227     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4228       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4229       if (!var) return false;
4230       return considerVariable(var, ref, owner);
4231     }
4232 
4233     if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4234       owner.Variable = ref->getDecl();
4235       owner.setLocsFrom(ref);
4236       return true;
4237     }
4238 
4239     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4240       if (member->isArrow()) return false;
4241 
4242       // Don't count this as an indirect ownership.
4243       e = member->getBase();
4244       continue;
4245     }
4246 
4247     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4248       // Only pay attention to pseudo-objects on property references.
4249       ObjCPropertyRefExpr *pre
4250         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4251                                               ->IgnoreParens());
4252       if (!pre) return false;
4253       if (pre->isImplicitProperty()) return false;
4254       ObjCPropertyDecl *property = pre->getExplicitProperty();
4255       if (!property->isRetaining() &&
4256           !(property->getPropertyIvarDecl() &&
4257             property->getPropertyIvarDecl()->getType()
4258               .getObjCLifetime() == Qualifiers::OCL_Strong))
4259           return false;
4260 
4261       owner.Indirect = true;
4262       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4263                               ->getSourceExpr());
4264       continue;
4265     }
4266 
4267     // Array ivars?
4268 
4269     return false;
4270   }
4271 }
4272 
4273 namespace {
4274   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4275     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4276       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4277         Variable(variable), Capturer(0) {}
4278 
4279     VarDecl *Variable;
4280     Expr *Capturer;
4281 
4282     void VisitDeclRefExpr(DeclRefExpr *ref) {
4283       if (ref->getDecl() == Variable && !Capturer)
4284         Capturer = ref;
4285     }
4286 
4287     void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4288       if (ref->getDecl() == Variable && !Capturer)
4289         Capturer = ref;
4290     }
4291 
4292     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4293       if (Capturer) return;
4294       Visit(ref->getBase());
4295       if (Capturer && ref->isFreeIvar())
4296         Capturer = ref;
4297     }
4298 
4299     void VisitBlockExpr(BlockExpr *block) {
4300       // Look inside nested blocks
4301       if (block->getBlockDecl()->capturesVariable(Variable))
4302         Visit(block->getBlockDecl()->getBody());
4303     }
4304   };
4305 }
4306 
4307 /// Check whether the given argument is a block which captures a
4308 /// variable.
4309 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4310   assert(owner.Variable && owner.Loc.isValid());
4311 
4312   e = e->IgnoreParenCasts();
4313   BlockExpr *block = dyn_cast<BlockExpr>(e);
4314   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4315     return 0;
4316 
4317   FindCaptureVisitor visitor(S.Context, owner.Variable);
4318   visitor.Visit(block->getBlockDecl()->getBody());
4319   return visitor.Capturer;
4320 }
4321 
4322 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4323                                 RetainCycleOwner &owner) {
4324   assert(capturer);
4325   assert(owner.Variable && owner.Loc.isValid());
4326 
4327   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4328     << owner.Variable << capturer->getSourceRange();
4329   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4330     << owner.Indirect << owner.Range;
4331 }
4332 
4333 /// Check for a keyword selector that starts with the word 'add' or
4334 /// 'set'.
4335 static bool isSetterLikeSelector(Selector sel) {
4336   if (sel.isUnarySelector()) return false;
4337 
4338   StringRef str = sel.getNameForSlot(0);
4339   while (!str.empty() && str.front() == '_') str = str.substr(1);
4340   if (str.startswith("set") || str.startswith("add"))
4341     str = str.substr(3);
4342   else
4343     return false;
4344 
4345   if (str.empty()) return true;
4346   return !islower(str.front());
4347 }
4348 
4349 /// Check a message send to see if it's likely to cause a retain cycle.
4350 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4351   // Only check instance methods whose selector looks like a setter.
4352   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4353     return;
4354 
4355   // Try to find a variable that the receiver is strongly owned by.
4356   RetainCycleOwner owner;
4357   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4358     if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4359       return;
4360   } else {
4361     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4362     owner.Variable = getCurMethodDecl()->getSelfDecl();
4363     owner.Loc = msg->getSuperLoc();
4364     owner.Range = msg->getSuperLoc();
4365   }
4366 
4367   // Check whether the receiver is captured by any of the arguments.
4368   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4369     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4370       return diagnoseRetainCycle(*this, capturer, owner);
4371 }
4372 
4373 /// Check a property assign to see if it's likely to cause a retain cycle.
4374 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4375   RetainCycleOwner owner;
4376   if (!findRetainCycleOwner(receiver, owner))
4377     return;
4378 
4379   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4380     diagnoseRetainCycle(*this, capturer, owner);
4381 }
4382 
4383 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4384                               QualType LHS, Expr *RHS) {
4385   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4386   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4387     return false;
4388   // strip off any implicit cast added to get to the one arc-specific
4389   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4390     if (cast->getCastKind() == CK_ARCConsumeObject) {
4391       Diag(Loc, diag::warn_arc_retained_assign)
4392         << (LT == Qualifiers::OCL_ExplicitNone)
4393         << RHS->getSourceRange();
4394       return true;
4395     }
4396     RHS = cast->getSubExpr();
4397   }
4398   return false;
4399 }
4400 
4401 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4402                               Expr *LHS, Expr *RHS) {
4403   QualType LHSType = LHS->getType();
4404   if (checkUnsafeAssigns(Loc, LHSType, RHS))
4405     return;
4406   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4407   // FIXME. Check for other life times.
4408   if (LT != Qualifiers::OCL_None)
4409     return;
4410 
4411   if (ObjCPropertyRefExpr *PRE
4412         = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
4413     if (PRE->isImplicitProperty())
4414       return;
4415     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4416     if (!PD)
4417       return;
4418 
4419     unsigned Attributes = PD->getPropertyAttributes();
4420     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4421       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4422         if (cast->getCastKind() == CK_ARCConsumeObject) {
4423           Diag(Loc, diag::warn_arc_retained_property_assign)
4424           << RHS->getSourceRange();
4425           return;
4426         }
4427         RHS = cast->getSubExpr();
4428       }
4429   }
4430 }
4431