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