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