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