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