SemaChecking.cpp revision 323ed74658bc8375278eabf074b4777458376540
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 "Sema.h"
16#include "clang/Analysis/Analyses/PrintfFormatString.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/StmtCXX.h"
24#include "clang/AST/StmtObjC.h"
25#include "clang/Lex/LiteralSupport.h"
26#include "clang/Lex/Preprocessor.h"
27#include "llvm/ADT/BitVector.h"
28#include "llvm/ADT/STLExtras.h"
29#include "clang/Basic/TargetBuiltins.h"
30#include <limits>
31using namespace clang;
32
33/// getLocationOfStringLiteralByte - Return a source location that points to the
34/// specified byte of the specified string literal.
35///
36/// Strings are amazingly complex.  They can be formed from multiple tokens and
37/// can have escape sequences in them in addition to the usual trigraph and
38/// escaped newline business.  This routine handles this complexity.
39///
40SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
41                                                    unsigned ByteNo) const {
42  assert(!SL->isWide() && "This doesn't work for wide strings yet");
43
44  // Loop over all of the tokens in this string until we find the one that
45  // contains the byte we're looking for.
46  unsigned TokNo = 0;
47  while (1) {
48    assert(TokNo < SL->getNumConcatenated() && "Invalid byte number!");
49    SourceLocation StrTokLoc = SL->getStrTokenLoc(TokNo);
50
51    // Get the spelling of the string so that we can get the data that makes up
52    // the string literal, not the identifier for the macro it is potentially
53    // expanded through.
54    SourceLocation StrTokSpellingLoc = SourceMgr.getSpellingLoc(StrTokLoc);
55
56    // Re-lex the token to get its length and original spelling.
57    std::pair<FileID, unsigned> LocInfo =
58      SourceMgr.getDecomposedLoc(StrTokSpellingLoc);
59    bool Invalid = false;
60    llvm::StringRef Buffer = SourceMgr.getBufferData(LocInfo.first, &Invalid);
61    if (Invalid)
62      return StrTokSpellingLoc;
63
64    const char *StrData = Buffer.data()+LocInfo.second;
65
66    // Create a langops struct and enable trigraphs.  This is sufficient for
67    // relexing tokens.
68    LangOptions LangOpts;
69    LangOpts.Trigraphs = true;
70
71    // Create a lexer starting at the beginning of this token.
72    Lexer TheLexer(StrTokSpellingLoc, LangOpts, Buffer.begin(), StrData,
73                   Buffer.end());
74    Token TheTok;
75    TheLexer.LexFromRawLexer(TheTok);
76
77    // Use the StringLiteralParser to compute the length of the string in bytes.
78    StringLiteralParser SLP(&TheTok, 1, PP);
79    unsigned TokNumBytes = SLP.GetStringLength();
80
81    // If the byte is in this token, return the location of the byte.
82    if (ByteNo < TokNumBytes ||
83        (ByteNo == TokNumBytes && TokNo == SL->getNumConcatenated())) {
84      unsigned Offset =
85        StringLiteralParser::getOffsetOfStringByte(TheTok, ByteNo, PP);
86
87      // Now that we know the offset of the token in the spelling, use the
88      // preprocessor to get the offset in the original source.
89      return PP.AdvanceToTokenCharacter(StrTokLoc, Offset);
90    }
91
92    // Move to the next string token.
93    ++TokNo;
94    ByteNo -= TokNumBytes;
95  }
96}
97
98/// CheckablePrintfAttr - does a function call have a "printf" attribute
99/// and arguments that merit checking?
100bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
101  if (Format->getType() == "printf") return true;
102  if (Format->getType() == "printf0") {
103    // printf0 allows null "format" string; if so don't check format/args
104    unsigned format_idx = Format->getFormatIdx() - 1;
105    // Does the index refer to the implicit object argument?
106    if (isa<CXXMemberCallExpr>(TheCall)) {
107      if (format_idx == 0)
108        return false;
109      --format_idx;
110    }
111    if (format_idx < TheCall->getNumArgs()) {
112      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
113      if (!Format->isNullPointerConstant(Context,
114                                         Expr::NPC_ValueDependentIsNull))
115        return true;
116    }
117  }
118  return false;
119}
120
121Action::OwningExprResult
122Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
123  OwningExprResult TheCallResult(Owned(TheCall));
124
125  switch (BuiltinID) {
126  case Builtin::BI__builtin___CFStringMakeConstantString:
127    assert(TheCall->getNumArgs() == 1 &&
128           "Wrong # arguments to builtin CFStringMakeConstantString");
129    if (CheckObjCString(TheCall->getArg(0)))
130      return ExprError();
131    break;
132  case Builtin::BI__builtin_stdarg_start:
133  case Builtin::BI__builtin_va_start:
134    if (SemaBuiltinVAStart(TheCall))
135      return ExprError();
136    break;
137  case Builtin::BI__builtin_isgreater:
138  case Builtin::BI__builtin_isgreaterequal:
139  case Builtin::BI__builtin_isless:
140  case Builtin::BI__builtin_islessequal:
141  case Builtin::BI__builtin_islessgreater:
142  case Builtin::BI__builtin_isunordered:
143    if (SemaBuiltinUnorderedCompare(TheCall))
144      return ExprError();
145    break;
146  case Builtin::BI__builtin_fpclassify:
147    if (SemaBuiltinFPClassification(TheCall, 6))
148      return ExprError();
149    break;
150  case Builtin::BI__builtin_isfinite:
151  case Builtin::BI__builtin_isinf:
152  case Builtin::BI__builtin_isinf_sign:
153  case Builtin::BI__builtin_isnan:
154  case Builtin::BI__builtin_isnormal:
155    if (SemaBuiltinFPClassification(TheCall, 1))
156      return ExprError();
157    break;
158  case Builtin::BI__builtin_return_address:
159  case Builtin::BI__builtin_frame_address: {
160    llvm::APSInt Result;
161    if (SemaBuiltinConstantArg(TheCall, 0, Result))
162      return ExprError();
163    break;
164  }
165  case Builtin::BI__builtin_eh_return_data_regno: {
166    llvm::APSInt Result;
167    if (SemaBuiltinConstantArg(TheCall, 0, Result))
168      return ExprError();
169    break;
170  }
171  case Builtin::BI__builtin_shufflevector:
172    return SemaBuiltinShuffleVector(TheCall);
173    // TheCall will be freed by the smart pointer here, but that's fine, since
174    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
175  case Builtin::BI__builtin_prefetch:
176    if (SemaBuiltinPrefetch(TheCall))
177      return ExprError();
178    break;
179  case Builtin::BI__builtin_object_size:
180    if (SemaBuiltinObjectSize(TheCall))
181      return ExprError();
182    break;
183  case Builtin::BI__builtin_longjmp:
184    if (SemaBuiltinLongjmp(TheCall))
185      return ExprError();
186    break;
187  case Builtin::BI__sync_fetch_and_add:
188  case Builtin::BI__sync_fetch_and_sub:
189  case Builtin::BI__sync_fetch_and_or:
190  case Builtin::BI__sync_fetch_and_and:
191  case Builtin::BI__sync_fetch_and_xor:
192  case Builtin::BI__sync_add_and_fetch:
193  case Builtin::BI__sync_sub_and_fetch:
194  case Builtin::BI__sync_and_and_fetch:
195  case Builtin::BI__sync_or_and_fetch:
196  case Builtin::BI__sync_xor_and_fetch:
197  case Builtin::BI__sync_val_compare_and_swap:
198  case Builtin::BI__sync_bool_compare_and_swap:
199  case Builtin::BI__sync_lock_test_and_set:
200  case Builtin::BI__sync_lock_release:
201    if (SemaBuiltinAtomicOverloaded(TheCall))
202      return ExprError();
203    break;
204
205  // Target specific builtins start here.
206  case X86::BI__builtin_ia32_palignr128:
207  case X86::BI__builtin_ia32_palignr: {
208    llvm::APSInt Result;
209    if (SemaBuiltinConstantArg(TheCall, 2, Result))
210      return ExprError();
211    break;
212  }
213  }
214
215  return move(TheCallResult);
216}
217
218/// CheckFunctionCall - Check a direct function call for various correctness
219/// and safety properties not strictly enforced by the C type system.
220bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
221  // Get the IdentifierInfo* for the called function.
222  IdentifierInfo *FnInfo = FDecl->getIdentifier();
223
224  // None of the checks below are needed for functions that don't have
225  // simple names (e.g., C++ conversion functions).
226  if (!FnInfo)
227    return false;
228
229  // FIXME: This mechanism should be abstracted to be less fragile and
230  // more efficient. For example, just map function ids to custom
231  // handlers.
232
233  // Printf checking.
234  if (const FormatAttr *Format = FDecl->getAttr<FormatAttr>()) {
235    if (CheckablePrintfAttr(Format, TheCall)) {
236      bool HasVAListArg = Format->getFirstArg() == 0;
237      CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
238                           HasVAListArg ? 0 : Format->getFirstArg() - 1);
239    }
240  }
241
242  for (const NonNullAttr *NonNull = FDecl->getAttr<NonNullAttr>(); NonNull;
243       NonNull = NonNull->getNext<NonNullAttr>())
244    CheckNonNullArguments(NonNull, TheCall);
245
246  return false;
247}
248
249bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
250  // Printf checking.
251  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
252  if (!Format)
253    return false;
254
255  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
256  if (!V)
257    return false;
258
259  QualType Ty = V->getType();
260  if (!Ty->isBlockPointerType())
261    return false;
262
263  if (!CheckablePrintfAttr(Format, TheCall))
264    return false;
265
266  bool HasVAListArg = Format->getFirstArg() == 0;
267  CheckPrintfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
268                       HasVAListArg ? 0 : Format->getFirstArg() - 1);
269
270  return false;
271}
272
273/// SemaBuiltinAtomicOverloaded - We have a call to a function like
274/// __sync_fetch_and_add, which is an overloaded function based on the pointer
275/// type of its first argument.  The main ActOnCallExpr routines have already
276/// promoted the types of arguments because all of these calls are prototyped as
277/// void(...).
278///
279/// This function goes through and does final semantic checking for these
280/// builtins,
281bool Sema::SemaBuiltinAtomicOverloaded(CallExpr *TheCall) {
282  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
283  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
284
285  // Ensure that we have at least one argument to do type inference from.
286  if (TheCall->getNumArgs() < 1)
287    return Diag(TheCall->getLocEnd(),
288              diag::err_typecheck_call_too_few_args_at_least)
289              << 0 << 1 << TheCall->getNumArgs()
290              << TheCall->getCallee()->getSourceRange();
291
292  // Inspect the first argument of the atomic builtin.  This should always be
293  // a pointer type, whose element is an integral scalar or pointer type.
294  // Because it is a pointer type, we don't have to worry about any implicit
295  // casts here.
296  Expr *FirstArg = TheCall->getArg(0);
297  if (!FirstArg->getType()->isPointerType())
298    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
299             << FirstArg->getType() << FirstArg->getSourceRange();
300
301  QualType ValType = FirstArg->getType()->getAs<PointerType>()->getPointeeType();
302  if (!ValType->isIntegerType() && !ValType->isPointerType() &&
303      !ValType->isBlockPointerType())
304    return Diag(DRE->getLocStart(),
305                diag::err_atomic_builtin_must_be_pointer_intptr)
306             << FirstArg->getType() << FirstArg->getSourceRange();
307
308  // We need to figure out which concrete builtin this maps onto.  For example,
309  // __sync_fetch_and_add with a 2 byte object turns into
310  // __sync_fetch_and_add_2.
311#define BUILTIN_ROW(x) \
312  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
313    Builtin::BI##x##_8, Builtin::BI##x##_16 }
314
315  static const unsigned BuiltinIndices[][5] = {
316    BUILTIN_ROW(__sync_fetch_and_add),
317    BUILTIN_ROW(__sync_fetch_and_sub),
318    BUILTIN_ROW(__sync_fetch_and_or),
319    BUILTIN_ROW(__sync_fetch_and_and),
320    BUILTIN_ROW(__sync_fetch_and_xor),
321
322    BUILTIN_ROW(__sync_add_and_fetch),
323    BUILTIN_ROW(__sync_sub_and_fetch),
324    BUILTIN_ROW(__sync_and_and_fetch),
325    BUILTIN_ROW(__sync_or_and_fetch),
326    BUILTIN_ROW(__sync_xor_and_fetch),
327
328    BUILTIN_ROW(__sync_val_compare_and_swap),
329    BUILTIN_ROW(__sync_bool_compare_and_swap),
330    BUILTIN_ROW(__sync_lock_test_and_set),
331    BUILTIN_ROW(__sync_lock_release)
332  };
333#undef BUILTIN_ROW
334
335  // Determine the index of the size.
336  unsigned SizeIndex;
337  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
338  case 1: SizeIndex = 0; break;
339  case 2: SizeIndex = 1; break;
340  case 4: SizeIndex = 2; break;
341  case 8: SizeIndex = 3; break;
342  case 16: SizeIndex = 4; break;
343  default:
344    return Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
345             << FirstArg->getType() << FirstArg->getSourceRange();
346  }
347
348  // Each of these builtins has one pointer argument, followed by some number of
349  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
350  // that we ignore.  Find out which row of BuiltinIndices to read from as well
351  // as the number of fixed args.
352  unsigned BuiltinID = FDecl->getBuiltinID();
353  unsigned BuiltinIndex, NumFixed = 1;
354  switch (BuiltinID) {
355  default: assert(0 && "Unknown overloaded atomic builtin!");
356  case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
357  case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
358  case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
359  case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
360  case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
361
362  case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
363  case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
364  case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
365  case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
366  case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
367
368  case Builtin::BI__sync_val_compare_and_swap:
369    BuiltinIndex = 10;
370    NumFixed = 2;
371    break;
372  case Builtin::BI__sync_bool_compare_and_swap:
373    BuiltinIndex = 11;
374    NumFixed = 2;
375    break;
376  case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
377  case Builtin::BI__sync_lock_release:
378    BuiltinIndex = 13;
379    NumFixed = 0;
380    break;
381  }
382
383  // Now that we know how many fixed arguments we expect, first check that we
384  // have at least that many.
385  if (TheCall->getNumArgs() < 1+NumFixed)
386    return Diag(TheCall->getLocEnd(),
387            diag::err_typecheck_call_too_few_args_at_least)
388            << 0 << 1+NumFixed << TheCall->getNumArgs()
389            << TheCall->getCallee()->getSourceRange();
390
391
392  // Get the decl for the concrete builtin from this, we can tell what the
393  // concrete integer type we should convert to is.
394  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
395  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
396  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
397  FunctionDecl *NewBuiltinDecl =
398    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
399                                           TUScope, false, DRE->getLocStart()));
400  const FunctionProtoType *BuiltinFT =
401    NewBuiltinDecl->getType()->getAs<FunctionProtoType>();
402  ValType = BuiltinFT->getArgType(0)->getAs<PointerType>()->getPointeeType();
403
404  // If the first type needs to be converted (e.g. void** -> int*), do it now.
405  if (BuiltinFT->getArgType(0) != FirstArg->getType()) {
406    ImpCastExprToType(FirstArg, BuiltinFT->getArgType(0), CastExpr::CK_BitCast);
407    TheCall->setArg(0, FirstArg);
408  }
409
410  // Next, walk the valid ones promoting to the right type.
411  for (unsigned i = 0; i != NumFixed; ++i) {
412    Expr *Arg = TheCall->getArg(i+1);
413
414    // If the argument is an implicit cast, then there was a promotion due to
415    // "...", just remove it now.
416    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
417      Arg = ICE->getSubExpr();
418      ICE->setSubExpr(0);
419      ICE->Destroy(Context);
420      TheCall->setArg(i+1, Arg);
421    }
422
423    // GCC does an implicit conversion to the pointer or integer ValType.  This
424    // can fail in some cases (1i -> int**), check for this error case now.
425    CastExpr::CastKind Kind = CastExpr::CK_Unknown;
426    CXXBaseSpecifierArray BasePath;
427    if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
428      return true;
429
430    // Okay, we have something that *can* be converted to the right type.  Check
431    // to see if there is a potentially weird extension going on here.  This can
432    // happen when you do an atomic operation on something like an char* and
433    // pass in 42.  The 42 gets converted to char.  This is even more strange
434    // for things like 45.123 -> char, etc.
435    // FIXME: Do this check.
436    ImpCastExprToType(Arg, ValType, Kind);
437    TheCall->setArg(i+1, Arg);
438  }
439
440  // Switch the DeclRefExpr to refer to the new decl.
441  DRE->setDecl(NewBuiltinDecl);
442  DRE->setType(NewBuiltinDecl->getType());
443
444  // Set the callee in the CallExpr.
445  // FIXME: This leaks the original parens and implicit casts.
446  Expr *PromotedCall = DRE;
447  UsualUnaryConversions(PromotedCall);
448  TheCall->setCallee(PromotedCall);
449
450
451  // Change the result type of the call to match the result type of the decl.
452  TheCall->setType(NewBuiltinDecl->getResultType());
453  return false;
454}
455
456
457/// CheckObjCString - Checks that the argument to the builtin
458/// CFString constructor is correct
459/// FIXME: GCC currently emits the following warning:
460/// "warning: input conversion stopped due to an input byte that does not
461///           belong to the input codeset UTF-8"
462/// Note: It might also make sense to do the UTF-16 conversion here (would
463/// simplify the backend).
464bool Sema::CheckObjCString(Expr *Arg) {
465  Arg = Arg->IgnoreParenCasts();
466  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
467
468  if (!Literal || Literal->isWide()) {
469    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
470      << Arg->getSourceRange();
471    return true;
472  }
473
474  const char *Data = Literal->getStrData();
475  unsigned Length = Literal->getByteLength();
476
477  for (unsigned i = 0; i < Length; ++i) {
478    if (!Data[i]) {
479      Diag(getLocationOfStringLiteralByte(Literal, i),
480           diag::warn_cfstring_literal_contains_nul_character)
481        << Arg->getSourceRange();
482      break;
483    }
484  }
485
486  return false;
487}
488
489/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
490/// Emit an error and return true on failure, return false on success.
491bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
492  Expr *Fn = TheCall->getCallee();
493  if (TheCall->getNumArgs() > 2) {
494    Diag(TheCall->getArg(2)->getLocStart(),
495         diag::err_typecheck_call_too_many_args)
496      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
497      << Fn->getSourceRange()
498      << SourceRange(TheCall->getArg(2)->getLocStart(),
499                     (*(TheCall->arg_end()-1))->getLocEnd());
500    return true;
501  }
502
503  if (TheCall->getNumArgs() < 2) {
504    return Diag(TheCall->getLocEnd(),
505      diag::err_typecheck_call_too_few_args_at_least)
506      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
507  }
508
509  // Determine whether the current function is variadic or not.
510  BlockScopeInfo *CurBlock = getCurBlock();
511  bool isVariadic;
512  if (CurBlock)
513    isVariadic = CurBlock->isVariadic;
514  else if (FunctionDecl *FD = getCurFunctionDecl())
515    isVariadic = FD->isVariadic();
516  else
517    isVariadic = getCurMethodDecl()->isVariadic();
518
519  if (!isVariadic) {
520    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
521    return true;
522  }
523
524  // Verify that the second argument to the builtin is the last argument of the
525  // current function or method.
526  bool SecondArgIsLastNamedArgument = false;
527  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
528
529  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
530    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
531      // FIXME: This isn't correct for methods (results in bogus warning).
532      // Get the last formal in the current function.
533      const ParmVarDecl *LastArg;
534      if (CurBlock)
535        LastArg = *(CurBlock->TheDecl->param_end()-1);
536      else if (FunctionDecl *FD = getCurFunctionDecl())
537        LastArg = *(FD->param_end()-1);
538      else
539        LastArg = *(getCurMethodDecl()->param_end()-1);
540      SecondArgIsLastNamedArgument = PV == LastArg;
541    }
542  }
543
544  if (!SecondArgIsLastNamedArgument)
545    Diag(TheCall->getArg(1)->getLocStart(),
546         diag::warn_second_parameter_of_va_start_not_last_named_argument);
547  return false;
548}
549
550/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
551/// friends.  This is declared to take (...), so we have to check everything.
552bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
553  if (TheCall->getNumArgs() < 2)
554    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
555      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
556  if (TheCall->getNumArgs() > 2)
557    return Diag(TheCall->getArg(2)->getLocStart(),
558                diag::err_typecheck_call_too_many_args)
559      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
560      << SourceRange(TheCall->getArg(2)->getLocStart(),
561                     (*(TheCall->arg_end()-1))->getLocEnd());
562
563  Expr *OrigArg0 = TheCall->getArg(0);
564  Expr *OrigArg1 = TheCall->getArg(1);
565
566  // Do standard promotions between the two arguments, returning their common
567  // type.
568  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
569
570  // Make sure any conversions are pushed back into the call; this is
571  // type safe since unordered compare builtins are declared as "_Bool
572  // foo(...)".
573  TheCall->setArg(0, OrigArg0);
574  TheCall->setArg(1, OrigArg1);
575
576  if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
577    return false;
578
579  // If the common type isn't a real floating type, then the arguments were
580  // invalid for this operation.
581  if (!Res->isRealFloatingType())
582    return Diag(OrigArg0->getLocStart(),
583                diag::err_typecheck_call_invalid_ordered_compare)
584      << OrigArg0->getType() << OrigArg1->getType()
585      << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
586
587  return false;
588}
589
590/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
591/// __builtin_isnan and friends.  This is declared to take (...), so we have
592/// to check everything. We expect the last argument to be a floating point
593/// value.
594bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
595  if (TheCall->getNumArgs() < NumArgs)
596    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
597      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
598  if (TheCall->getNumArgs() > NumArgs)
599    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
600                diag::err_typecheck_call_too_many_args)
601      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
602      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
603                     (*(TheCall->arg_end()-1))->getLocEnd());
604
605  Expr *OrigArg = TheCall->getArg(NumArgs-1);
606
607  if (OrigArg->isTypeDependent())
608    return false;
609
610  // This operation requires a non-_Complex floating-point number.
611  if (!OrigArg->getType()->isRealFloatingType())
612    return Diag(OrigArg->getLocStart(),
613                diag::err_typecheck_call_invalid_unary_fp)
614      << OrigArg->getType() << OrigArg->getSourceRange();
615
616  // If this is an implicit conversion from float -> double, remove it.
617  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
618    Expr *CastArg = Cast->getSubExpr();
619    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
620      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
621             "promotion from float to double is the only expected cast here");
622      Cast->setSubExpr(0);
623      Cast->Destroy(Context);
624      TheCall->setArg(NumArgs-1, CastArg);
625      OrigArg = CastArg;
626    }
627  }
628
629  return false;
630}
631
632/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
633// This is declared to take (...), so we have to check everything.
634Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
635  if (TheCall->getNumArgs() < 3)
636    return ExprError(Diag(TheCall->getLocEnd(),
637                          diag::err_typecheck_call_too_few_args_at_least)
638      << 0 /*function call*/ << 3 << TheCall->getNumArgs()
639      << TheCall->getSourceRange());
640
641  unsigned numElements = std::numeric_limits<unsigned>::max();
642  if (!TheCall->getArg(0)->isTypeDependent() &&
643      !TheCall->getArg(1)->isTypeDependent()) {
644    QualType FAType = TheCall->getArg(0)->getType();
645    QualType SAType = TheCall->getArg(1)->getType();
646
647    if (!FAType->isVectorType() || !SAType->isVectorType()) {
648      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
649        << SourceRange(TheCall->getArg(0)->getLocStart(),
650                       TheCall->getArg(1)->getLocEnd());
651      return ExprError();
652    }
653
654    if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
655      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
656        << SourceRange(TheCall->getArg(0)->getLocStart(),
657                       TheCall->getArg(1)->getLocEnd());
658      return ExprError();
659    }
660
661    numElements = FAType->getAs<VectorType>()->getNumElements();
662    if (TheCall->getNumArgs() != numElements+2) {
663      if (TheCall->getNumArgs() < numElements+2)
664        return ExprError(Diag(TheCall->getLocEnd(),
665                              diag::err_typecheck_call_too_few_args)
666                 << 0 /*function call*/
667                 << numElements+2 << TheCall->getNumArgs()
668                 << TheCall->getSourceRange());
669      return ExprError(Diag(TheCall->getLocEnd(),
670                            diag::err_typecheck_call_too_many_args)
671                 << 0 /*function call*/
672                 << numElements+2 << TheCall->getNumArgs()
673                 << TheCall->getSourceRange());
674    }
675  }
676
677  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
678    if (TheCall->getArg(i)->isTypeDependent() ||
679        TheCall->getArg(i)->isValueDependent())
680      continue;
681
682    llvm::APSInt Result;
683    if (SemaBuiltinConstantArg(TheCall, i, Result))
684      return ExprError();
685
686    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
687      return ExprError(Diag(TheCall->getLocStart(),
688                  diag::err_shufflevector_argument_too_large)
689               << TheCall->getArg(i)->getSourceRange());
690  }
691
692  llvm::SmallVector<Expr*, 32> exprs;
693
694  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
695    exprs.push_back(TheCall->getArg(i));
696    TheCall->setArg(i, 0);
697  }
698
699  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
700                                            exprs.size(), exprs[0]->getType(),
701                                            TheCall->getCallee()->getLocStart(),
702                                            TheCall->getRParenLoc()));
703}
704
705/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
706// This is declared to take (const void*, ...) and can take two
707// optional constant int args.
708bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
709  unsigned NumArgs = TheCall->getNumArgs();
710
711  if (NumArgs > 3)
712    return Diag(TheCall->getLocEnd(),
713             diag::err_typecheck_call_too_many_args_at_most)
714             << 0 /*function call*/ << 3 << NumArgs
715             << TheCall->getSourceRange();
716
717  // Argument 0 is checked for us and the remaining arguments must be
718  // constant integers.
719  for (unsigned i = 1; i != NumArgs; ++i) {
720    Expr *Arg = TheCall->getArg(i);
721
722    llvm::APSInt Result;
723    if (SemaBuiltinConstantArg(TheCall, i, Result))
724      return true;
725
726    // FIXME: gcc issues a warning and rewrites these to 0. These
727    // seems especially odd for the third argument since the default
728    // is 3.
729    if (i == 1) {
730      if (Result.getLimitedValue() > 1)
731        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
732             << "0" << "1" << Arg->getSourceRange();
733    } else {
734      if (Result.getLimitedValue() > 3)
735        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
736            << "0" << "3" << Arg->getSourceRange();
737    }
738  }
739
740  return false;
741}
742
743/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
744/// TheCall is a constant expression.
745bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
746                                  llvm::APSInt &Result) {
747  Expr *Arg = TheCall->getArg(ArgNum);
748  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
749  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
750
751  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
752
753  if (!Arg->isIntegerConstantExpr(Result, Context))
754    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
755                << FDecl->getDeclName() <<  Arg->getSourceRange();
756
757  return false;
758}
759
760/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
761/// int type). This simply type checks that type is one of the defined
762/// constants (0-3).
763// For compatability check 0-3, llvm only handles 0 and 2.
764bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
765  llvm::APSInt Result;
766
767  // Check constant-ness first.
768  if (SemaBuiltinConstantArg(TheCall, 1, Result))
769    return true;
770
771  Expr *Arg = TheCall->getArg(1);
772  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
773    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
774             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
775  }
776
777  return false;
778}
779
780/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
781/// This checks that val is a constant 1.
782bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
783  Expr *Arg = TheCall->getArg(1);
784  llvm::APSInt Result;
785
786  // TODO: This is less than ideal. Overload this to take a value.
787  if (SemaBuiltinConstantArg(TheCall, 1, Result))
788    return true;
789
790  if (Result != 1)
791    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
792             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
793
794  return false;
795}
796
797// Handle i > 1 ? "x" : "y", recursivelly
798bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
799                                  bool HasVAListArg,
800                                  unsigned format_idx, unsigned firstDataArg) {
801  if (E->isTypeDependent() || E->isValueDependent())
802    return false;
803
804  switch (E->getStmtClass()) {
805  case Stmt::ConditionalOperatorClass: {
806    const ConditionalOperator *C = cast<ConditionalOperator>(E);
807    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
808                                  HasVAListArg, format_idx, firstDataArg)
809        && SemaCheckStringLiteral(C->getRHS(), TheCall,
810                                  HasVAListArg, format_idx, firstDataArg);
811  }
812
813  case Stmt::ImplicitCastExprClass: {
814    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
815    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
816                                  format_idx, firstDataArg);
817  }
818
819  case Stmt::ParenExprClass: {
820    const ParenExpr *Expr = cast<ParenExpr>(E);
821    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
822                                  format_idx, firstDataArg);
823  }
824
825  case Stmt::DeclRefExprClass: {
826    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
827
828    // As an exception, do not flag errors for variables binding to
829    // const string literals.
830    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
831      bool isConstant = false;
832      QualType T = DR->getType();
833
834      if (const ArrayType *AT = Context.getAsArrayType(T)) {
835        isConstant = AT->getElementType().isConstant(Context);
836      } else if (const PointerType *PT = T->getAs<PointerType>()) {
837        isConstant = T.isConstant(Context) &&
838                     PT->getPointeeType().isConstant(Context);
839      }
840
841      if (isConstant) {
842        if (const Expr *Init = VD->getAnyInitializer())
843          return SemaCheckStringLiteral(Init, TheCall,
844                                        HasVAListArg, format_idx, firstDataArg);
845      }
846
847      // For vprintf* functions (i.e., HasVAListArg==true), we add a
848      // special check to see if the format string is a function parameter
849      // of the function calling the printf function.  If the function
850      // has an attribute indicating it is a printf-like function, then we
851      // should suppress warnings concerning non-literals being used in a call
852      // to a vprintf function.  For example:
853      //
854      // void
855      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
856      //      va_list ap;
857      //      va_start(ap, fmt);
858      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
859      //      ...
860      //
861      //
862      //  FIXME: We don't have full attribute support yet, so just check to see
863      //    if the argument is a DeclRefExpr that references a parameter.  We'll
864      //    add proper support for checking the attribute later.
865      if (HasVAListArg)
866        if (isa<ParmVarDecl>(VD))
867          return true;
868    }
869
870    return false;
871  }
872
873  case Stmt::CallExprClass: {
874    const CallExpr *CE = cast<CallExpr>(E);
875    if (const ImplicitCastExpr *ICE
876          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
877      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
878        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
879          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
880            unsigned ArgIndex = FA->getFormatIdx();
881            const Expr *Arg = CE->getArg(ArgIndex - 1);
882
883            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
884                                          format_idx, firstDataArg);
885          }
886        }
887      }
888    }
889
890    return false;
891  }
892  case Stmt::ObjCStringLiteralClass:
893  case Stmt::StringLiteralClass: {
894    const StringLiteral *StrE = NULL;
895
896    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
897      StrE = ObjCFExpr->getString();
898    else
899      StrE = cast<StringLiteral>(E);
900
901    if (StrE) {
902      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
903                        firstDataArg);
904      return true;
905    }
906
907    return false;
908  }
909
910  default:
911    return false;
912  }
913}
914
915void
916Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
917                            const CallExpr *TheCall) {
918  for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
919       i != e; ++i) {
920    const Expr *ArgExpr = TheCall->getArg(*i);
921    if (ArgExpr->isNullPointerConstant(Context,
922                                       Expr::NPC_ValueDependentIsNotNull))
923      Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
924        << ArgExpr->getSourceRange();
925  }
926}
927
928/// CheckPrintfArguments - Check calls to printf (and similar functions) for
929/// correct use of format strings.
930///
931///  HasVAListArg - A predicate indicating whether the printf-like
932///    function is passed an explicit va_arg argument (e.g., vprintf)
933///
934///  format_idx - The index into Args for the format string.
935///
936/// Improper format strings to functions in the printf family can be
937/// the source of bizarre bugs and very serious security holes.  A
938/// good source of information is available in the following paper
939/// (which includes additional references):
940///
941///  FormatGuard: Automatic Protection From printf Format String
942///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
943///
944/// TODO:
945/// Functionality implemented:
946///
947///  We can statically check the following properties for string
948///  literal format strings for non v.*printf functions (where the
949///  arguments are passed directly):
950//
951///  (1) Are the number of format conversions equal to the number of
952///      data arguments?
953///
954///  (2) Does each format conversion correctly match the type of the
955///      corresponding data argument?
956///
957/// Moreover, for all printf functions we can:
958///
959///  (3) Check for a missing format string (when not caught by type checking).
960///
961///  (4) Check for no-operation flags; e.g. using "#" with format
962///      conversion 'c'  (TODO)
963///
964///  (5) Check the use of '%n', a major source of security holes.
965///
966///  (6) Check for malformed format conversions that don't specify anything.
967///
968///  (7) Check for empty format strings.  e.g: printf("");
969///
970///  (8) Check that the format string is a wide literal.
971///
972/// All of these checks can be done by parsing the format string.
973///
974void
975Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
976                           unsigned format_idx, unsigned firstDataArg) {
977  const Expr *Fn = TheCall->getCallee();
978
979  // The way the format attribute works in GCC, the implicit this argument
980  // of member functions is counted. However, it doesn't appear in our own
981  // lists, so decrement format_idx in that case.
982  if (isa<CXXMemberCallExpr>(TheCall)) {
983    // Catch a format attribute mistakenly referring to the object argument.
984    if (format_idx == 0)
985      return;
986    --format_idx;
987    if(firstDataArg != 0)
988      --firstDataArg;
989  }
990
991  // CHECK: printf-like function is called with no format string.
992  if (format_idx >= TheCall->getNumArgs()) {
993    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
994      << Fn->getSourceRange();
995    return;
996  }
997
998  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
999
1000  // CHECK: format string is not a string literal.
1001  //
1002  // Dynamically generated format strings are difficult to
1003  // automatically vet at compile time.  Requiring that format strings
1004  // are string literals: (1) permits the checking of format strings by
1005  // the compiler and thereby (2) can practically remove the source of
1006  // many format string exploits.
1007
1008  // Format string can be either ObjC string (e.g. @"%d") or
1009  // C string (e.g. "%d")
1010  // ObjC string uses the same format specifiers as C string, so we can use
1011  // the same format string checking logic for both ObjC and C strings.
1012  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1013                             firstDataArg))
1014    return;  // Literal format string found, check done!
1015
1016  // If there are no arguments specified, warn with -Wformat-security, otherwise
1017  // warn only with -Wformat-nonliteral.
1018  if (TheCall->getNumArgs() == format_idx+1)
1019    Diag(TheCall->getArg(format_idx)->getLocStart(),
1020         diag::warn_printf_nonliteral_noargs)
1021      << OrigFormatExpr->getSourceRange();
1022  else
1023    Diag(TheCall->getArg(format_idx)->getLocStart(),
1024         diag::warn_printf_nonliteral)
1025           << OrigFormatExpr->getSourceRange();
1026}
1027
1028namespace {
1029class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
1030  Sema &S;
1031  const StringLiteral *FExpr;
1032  const Expr *OrigFormatExpr;
1033  const unsigned FirstDataArg;
1034  const unsigned NumDataArgs;
1035  const bool IsObjCLiteral;
1036  const char *Beg; // Start of format string.
1037  const bool HasVAListArg;
1038  const CallExpr *TheCall;
1039  unsigned FormatIdx;
1040  llvm::BitVector CoveredArgs;
1041  bool usesPositionalArgs;
1042  bool atFirstArg;
1043public:
1044  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1045                     const Expr *origFormatExpr, unsigned firstDataArg,
1046                     unsigned numDataArgs, bool isObjCLiteral,
1047                     const char *beg, bool hasVAListArg,
1048                     const CallExpr *theCall, unsigned formatIdx)
1049    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1050      FirstDataArg(firstDataArg),
1051      NumDataArgs(numDataArgs),
1052      IsObjCLiteral(isObjCLiteral), Beg(beg),
1053      HasVAListArg(hasVAListArg),
1054      TheCall(theCall), FormatIdx(formatIdx),
1055      usesPositionalArgs(false), atFirstArg(true) {
1056        CoveredArgs.resize(numDataArgs);
1057        CoveredArgs.reset();
1058      }
1059
1060  void DoneProcessing();
1061
1062  void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1063                                       unsigned specifierLen);
1064
1065  bool
1066  HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1067                                   const char *startSpecifier,
1068                                   unsigned specifierLen);
1069
1070  virtual void HandleInvalidPosition(const char *startSpecifier,
1071                                     unsigned specifierLen,
1072                                     analyze_printf::PositionContext p);
1073
1074  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1075
1076  void HandleNullChar(const char *nullCharacter);
1077
1078  bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1079                             const char *startSpecifier,
1080                             unsigned specifierLen);
1081private:
1082  SourceRange getFormatStringRange();
1083  SourceRange getFormatSpecifierRange(const char *startSpecifier,
1084                                      unsigned specifierLen);
1085  SourceLocation getLocationOfByte(const char *x);
1086
1087  bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1088                    const char *startSpecifier, unsigned specifierLen);
1089  void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1090                   llvm::StringRef flag, llvm::StringRef cspec,
1091                   const char *startSpecifier, unsigned specifierLen);
1092
1093  const Expr *getDataArg(unsigned i) const;
1094};
1095}
1096
1097SourceRange CheckPrintfHandler::getFormatStringRange() {
1098  return OrigFormatExpr->getSourceRange();
1099}
1100
1101SourceRange CheckPrintfHandler::
1102getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1103  return SourceRange(getLocationOfByte(startSpecifier),
1104                     getLocationOfByte(startSpecifier+specifierLen-1));
1105}
1106
1107SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
1108  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1109}
1110
1111void CheckPrintfHandler::
1112HandleIncompleteFormatSpecifier(const char *startSpecifier,
1113                                unsigned specifierLen) {
1114  SourceLocation Loc = getLocationOfByte(startSpecifier);
1115  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1116    << getFormatSpecifierRange(startSpecifier, specifierLen);
1117}
1118
1119void
1120CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1121                                          analyze_printf::PositionContext p) {
1122  SourceLocation Loc = getLocationOfByte(startPos);
1123  S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1124    << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1125}
1126
1127void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1128                                            unsigned posLen) {
1129  SourceLocation Loc = getLocationOfByte(startPos);
1130  S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1131    << getFormatSpecifierRange(startPos, posLen);
1132}
1133
1134bool CheckPrintfHandler::
1135HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1136                                 const char *startSpecifier,
1137                                 unsigned specifierLen) {
1138
1139  unsigned argIndex = FS.getArgIndex();
1140  bool keepGoing = true;
1141  if (argIndex < NumDataArgs) {
1142    // Consider the argument coverered, even though the specifier doesn't
1143    // make sense.
1144    CoveredArgs.set(argIndex);
1145  }
1146  else {
1147    // If argIndex exceeds the number of data arguments we
1148    // don't issue a warning because that is just a cascade of warnings (and
1149    // they may have intended '%%' anyway). We don't want to continue processing
1150    // the format string after this point, however, as we will like just get
1151    // gibberish when trying to match arguments.
1152    keepGoing = false;
1153  }
1154
1155  const analyze_printf::ConversionSpecifier &CS =
1156    FS.getConversionSpecifier();
1157  SourceLocation Loc = getLocationOfByte(CS.getStart());
1158  S.Diag(Loc, diag::warn_printf_invalid_conversion)
1159      << llvm::StringRef(CS.getStart(), CS.getLength())
1160      << getFormatSpecifierRange(startSpecifier, specifierLen);
1161
1162  return keepGoing;
1163}
1164
1165void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1166  // The presence of a null character is likely an error.
1167  S.Diag(getLocationOfByte(nullCharacter),
1168         diag::warn_printf_format_string_contains_null_char)
1169    << getFormatStringRange();
1170}
1171
1172const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
1173  return TheCall->getArg(FirstDataArg + i);
1174}
1175
1176void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1177                                     llvm::StringRef flag,
1178                                     llvm::StringRef cspec,
1179                                     const char *startSpecifier,
1180                                     unsigned specifierLen) {
1181  const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1182  S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1183    << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1184}
1185
1186bool
1187CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1188                                 unsigned k, const char *startSpecifier,
1189                                 unsigned specifierLen) {
1190
1191  if (Amt.hasDataArgument()) {
1192    if (!HasVAListArg) {
1193      unsigned argIndex = Amt.getArgIndex();
1194      if (argIndex >= NumDataArgs) {
1195        S.Diag(getLocationOfByte(Amt.getStart()),
1196               diag::warn_printf_asterisk_missing_arg)
1197          << k << getFormatSpecifierRange(startSpecifier, specifierLen);
1198        // Don't do any more checking.  We will just emit
1199        // spurious errors.
1200        return false;
1201      }
1202
1203      // Type check the data argument.  It should be an 'int'.
1204      // Although not in conformance with C99, we also allow the argument to be
1205      // an 'unsigned int' as that is a reasonably safe case.  GCC also
1206      // doesn't emit a warning for that case.
1207      CoveredArgs.set(argIndex);
1208      const Expr *Arg = getDataArg(argIndex);
1209      QualType T = Arg->getType();
1210
1211      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1212      assert(ATR.isValid());
1213
1214      if (!ATR.matchesType(S.Context, T)) {
1215        S.Diag(getLocationOfByte(Amt.getStart()),
1216               diag::warn_printf_asterisk_wrong_type)
1217          << k
1218          << ATR.getRepresentativeType(S.Context) << T
1219          << getFormatSpecifierRange(startSpecifier, specifierLen)
1220          << Arg->getSourceRange();
1221        // Don't do any more checking.  We will just emit
1222        // spurious errors.
1223        return false;
1224      }
1225    }
1226  }
1227  return true;
1228}
1229
1230bool
1231CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1232                                            &FS,
1233                                          const char *startSpecifier,
1234                                          unsigned specifierLen) {
1235
1236  using namespace analyze_printf;
1237  const ConversionSpecifier &CS = FS.getConversionSpecifier();
1238
1239  if (atFirstArg) {
1240    atFirstArg = false;
1241    usesPositionalArgs = FS.usesPositionalArg();
1242  }
1243  else if (usesPositionalArgs != FS.usesPositionalArg()) {
1244    // Cannot mix-and-match positional and non-positional arguments.
1245    S.Diag(getLocationOfByte(CS.getStart()),
1246           diag::warn_printf_mix_positional_nonpositional_args)
1247      << getFormatSpecifierRange(startSpecifier, specifierLen);
1248    return false;
1249  }
1250
1251  // First check if the field width, precision, and conversion specifier
1252  // have matching data arguments.
1253  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1254                    startSpecifier, specifierLen)) {
1255    return false;
1256  }
1257
1258  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1259                    startSpecifier, specifierLen)) {
1260    return false;
1261  }
1262
1263  if (!CS.consumesDataArgument()) {
1264    // FIXME: Technically specifying a precision or field width here
1265    // makes no sense.  Worth issuing a warning at some point.
1266    return true;
1267  }
1268
1269  // Consume the argument.
1270  unsigned argIndex = FS.getArgIndex();
1271  if (argIndex < NumDataArgs) {
1272    // The check to see if the argIndex is valid will come later.
1273    // We set the bit here because we may exit early from this
1274    // function if we encounter some other error.
1275    CoveredArgs.set(argIndex);
1276  }
1277
1278  // Check for using an Objective-C specific conversion specifier
1279  // in a non-ObjC literal.
1280  if (!IsObjCLiteral && CS.isObjCArg()) {
1281    return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1282  }
1283
1284  // Are we using '%n'?  Issue a warning about this being
1285  // a possible security issue.
1286  if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1287    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1288      << getFormatSpecifierRange(startSpecifier, specifierLen);
1289    // Continue checking the other format specifiers.
1290    return true;
1291  }
1292
1293  if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1294    if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
1295      S.Diag(getLocationOfByte(CS.getStart()),
1296             diag::warn_printf_nonsensical_precision)
1297        << CS.getCharacters()
1298        << getFormatSpecifierRange(startSpecifier, specifierLen);
1299  }
1300  if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1301      CS.getKind() == ConversionSpecifier::CStrArg) {
1302    // FIXME: Instead of using "0", "+", etc., eventually get them from
1303    // the FormatSpecifier.
1304    if (FS.hasLeadingZeros())
1305      HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1306    if (FS.hasPlusPrefix())
1307      HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1308    if (FS.hasSpacePrefix())
1309      HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
1310  }
1311
1312  // The remaining checks depend on the data arguments.
1313  if (HasVAListArg)
1314    return true;
1315
1316  if (argIndex >= NumDataArgs) {
1317    if (FS.usesPositionalArg())  {
1318      S.Diag(getLocationOfByte(CS.getStart()),
1319             diag::warn_printf_positional_arg_exceeds_data_args)
1320        << (argIndex+1) << NumDataArgs
1321        << getFormatSpecifierRange(startSpecifier, specifierLen);
1322    }
1323    else {
1324      S.Diag(getLocationOfByte(CS.getStart()),
1325             diag::warn_printf_insufficient_data_args)
1326        << getFormatSpecifierRange(startSpecifier, specifierLen);
1327    }
1328
1329    // Don't do any more checking.
1330    return false;
1331  }
1332
1333  // Now type check the data expression that matches the
1334  // format specifier.
1335  const Expr *Ex = getDataArg(argIndex);
1336  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1337  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1338    // Check if we didn't match because of an implicit cast from a 'char'
1339    // or 'short' to an 'int'.  This is done because printf is a varargs
1340    // function.
1341    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1342      if (ICE->getType() == S.Context.IntTy)
1343        if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1344          return true;
1345
1346    S.Diag(getLocationOfByte(CS.getStart()),
1347           diag::warn_printf_conversion_argument_type_mismatch)
1348      << ATR.getRepresentativeType(S.Context) << Ex->getType()
1349      << getFormatSpecifierRange(startSpecifier, specifierLen)
1350      << Ex->getSourceRange();
1351  }
1352
1353  return true;
1354}
1355
1356void CheckPrintfHandler::DoneProcessing() {
1357  // Does the number of data arguments exceed the number of
1358  // format conversions in the format string?
1359  if (!HasVAListArg) {
1360    // Find any arguments that weren't covered.
1361    CoveredArgs.flip();
1362    signed notCoveredArg = CoveredArgs.find_first();
1363    if (notCoveredArg >= 0) {
1364      assert((unsigned)notCoveredArg < NumDataArgs);
1365      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1366             diag::warn_printf_data_arg_not_used)
1367        << getFormatStringRange();
1368    }
1369  }
1370}
1371
1372void Sema::CheckPrintfString(const StringLiteral *FExpr,
1373                             const Expr *OrigFormatExpr,
1374                             const CallExpr *TheCall, bool HasVAListArg,
1375                             unsigned format_idx, unsigned firstDataArg) {
1376
1377  // CHECK: is the format string a wide literal?
1378  if (FExpr->isWide()) {
1379    Diag(FExpr->getLocStart(),
1380         diag::warn_printf_format_string_is_wide_literal)
1381    << OrigFormatExpr->getSourceRange();
1382    return;
1383  }
1384
1385  // Str - The format string.  NOTE: this is NOT null-terminated!
1386  const char *Str = FExpr->getStrData();
1387
1388  // CHECK: empty format string?
1389  unsigned StrLen = FExpr->getByteLength();
1390
1391  if (StrLen == 0) {
1392    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1393    << OrigFormatExpr->getSourceRange();
1394    return;
1395  }
1396
1397  CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1398                       TheCall->getNumArgs() - firstDataArg,
1399                       isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1400                       HasVAListArg, TheCall, format_idx);
1401
1402  if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
1403    H.DoneProcessing();
1404}
1405
1406//===--- CHECK: Return Address of Stack Variable --------------------------===//
1407
1408static DeclRefExpr* EvalVal(Expr *E);
1409static DeclRefExpr* EvalAddr(Expr* E);
1410
1411/// CheckReturnStackAddr - Check if a return statement returns the address
1412///   of a stack variable.
1413void
1414Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1415                           SourceLocation ReturnLoc) {
1416
1417  // Perform checking for returned stack addresses.
1418  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1419    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1420      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1421       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1422
1423    // Skip over implicit cast expressions when checking for block expressions.
1424    RetValExp = RetValExp->IgnoreParenCasts();
1425
1426    if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
1427      if (C->hasBlockDeclRefExprs())
1428        Diag(C->getLocStart(), diag::err_ret_local_block)
1429          << C->getSourceRange();
1430
1431    if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1432      Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1433        << ALE->getSourceRange();
1434
1435  } else if (lhsType->isReferenceType()) {
1436    // Perform checking for stack values returned by reference.
1437    // Check for a reference to the stack
1438    if (DeclRefExpr *DR = EvalVal(RetValExp))
1439      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1440        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1441  }
1442}
1443
1444/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1445///  check if the expression in a return statement evaluates to an address
1446///  to a location on the stack.  The recursion is used to traverse the
1447///  AST of the return expression, with recursion backtracking when we
1448///  encounter a subexpression that (1) clearly does not lead to the address
1449///  of a stack variable or (2) is something we cannot determine leads to
1450///  the address of a stack variable based on such local checking.
1451///
1452///  EvalAddr processes expressions that are pointers that are used as
1453///  references (and not L-values).  EvalVal handles all other values.
1454///  At the base case of the recursion is a check for a DeclRefExpr* in
1455///  the refers to a stack variable.
1456///
1457///  This implementation handles:
1458///
1459///   * pointer-to-pointer casts
1460///   * implicit conversions from array references to pointers
1461///   * taking the address of fields
1462///   * arbitrary interplay between "&" and "*" operators
1463///   * pointer arithmetic from an address of a stack variable
1464///   * taking the address of an array element where the array is on the stack
1465static DeclRefExpr* EvalAddr(Expr *E) {
1466  // We should only be called for evaluating pointer expressions.
1467  assert((E->getType()->isAnyPointerType() ||
1468          E->getType()->isBlockPointerType() ||
1469          E->getType()->isObjCQualifiedIdType()) &&
1470         "EvalAddr only works on pointers");
1471
1472  // Our "symbolic interpreter" is just a dispatch off the currently
1473  // viewed AST node.  We then recursively traverse the AST by calling
1474  // EvalAddr and EvalVal appropriately.
1475  switch (E->getStmtClass()) {
1476  case Stmt::ParenExprClass:
1477    // Ignore parentheses.
1478    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1479
1480  case Stmt::UnaryOperatorClass: {
1481    // The only unary operator that make sense to handle here
1482    // is AddrOf.  All others don't make sense as pointers.
1483    UnaryOperator *U = cast<UnaryOperator>(E);
1484
1485    if (U->getOpcode() == UnaryOperator::AddrOf)
1486      return EvalVal(U->getSubExpr());
1487    else
1488      return NULL;
1489  }
1490
1491  case Stmt::BinaryOperatorClass: {
1492    // Handle pointer arithmetic.  All other binary operators are not valid
1493    // in this context.
1494    BinaryOperator *B = cast<BinaryOperator>(E);
1495    BinaryOperator::Opcode op = B->getOpcode();
1496
1497    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1498      return NULL;
1499
1500    Expr *Base = B->getLHS();
1501
1502    // Determine which argument is the real pointer base.  It could be
1503    // the RHS argument instead of the LHS.
1504    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1505
1506    assert (Base->getType()->isPointerType());
1507    return EvalAddr(Base);
1508  }
1509
1510  // For conditional operators we need to see if either the LHS or RHS are
1511  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1512  case Stmt::ConditionalOperatorClass: {
1513    ConditionalOperator *C = cast<ConditionalOperator>(E);
1514
1515    // Handle the GNU extension for missing LHS.
1516    if (Expr *lhsExpr = C->getLHS())
1517      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1518        return LHS;
1519
1520     return EvalAddr(C->getRHS());
1521  }
1522
1523  // For casts, we need to handle conversions from arrays to
1524  // pointer values, and pointer-to-pointer conversions.
1525  case Stmt::ImplicitCastExprClass:
1526  case Stmt::CStyleCastExprClass:
1527  case Stmt::CXXFunctionalCastExprClass: {
1528    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1529    QualType T = SubExpr->getType();
1530
1531    if (SubExpr->getType()->isPointerType() ||
1532        SubExpr->getType()->isBlockPointerType() ||
1533        SubExpr->getType()->isObjCQualifiedIdType())
1534      return EvalAddr(SubExpr);
1535    else if (T->isArrayType())
1536      return EvalVal(SubExpr);
1537    else
1538      return 0;
1539  }
1540
1541  // C++ casts.  For dynamic casts, static casts, and const casts, we
1542  // are always converting from a pointer-to-pointer, so we just blow
1543  // through the cast.  In the case the dynamic cast doesn't fail (and
1544  // return NULL), we take the conservative route and report cases
1545  // where we return the address of a stack variable.  For Reinterpre
1546  // FIXME: The comment about is wrong; we're not always converting
1547  // from pointer to pointer. I'm guessing that this code should also
1548  // handle references to objects.
1549  case Stmt::CXXStaticCastExprClass:
1550  case Stmt::CXXDynamicCastExprClass:
1551  case Stmt::CXXConstCastExprClass:
1552  case Stmt::CXXReinterpretCastExprClass: {
1553      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1554      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1555        return EvalAddr(S);
1556      else
1557        return NULL;
1558  }
1559
1560  // Everything else: we simply don't reason about them.
1561  default:
1562    return NULL;
1563  }
1564}
1565
1566
1567///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1568///   See the comments for EvalAddr for more details.
1569static DeclRefExpr* EvalVal(Expr *E) {
1570
1571  // We should only be called for evaluating non-pointer expressions, or
1572  // expressions with a pointer type that are not used as references but instead
1573  // are l-values (e.g., DeclRefExpr with a pointer type).
1574
1575  // Our "symbolic interpreter" is just a dispatch off the currently
1576  // viewed AST node.  We then recursively traverse the AST by calling
1577  // EvalAddr and EvalVal appropriately.
1578  switch (E->getStmtClass()) {
1579  case Stmt::DeclRefExprClass: {
1580    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1581    //  at code that refers to a variable's name.  We check if it has local
1582    //  storage within the function, and if so, return the expression.
1583    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1584
1585    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1586      if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1587
1588    return NULL;
1589  }
1590
1591  case Stmt::ParenExprClass:
1592    // Ignore parentheses.
1593    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1594
1595  case Stmt::UnaryOperatorClass: {
1596    // The only unary operator that make sense to handle here
1597    // is Deref.  All others don't resolve to a "name."  This includes
1598    // handling all sorts of rvalues passed to a unary operator.
1599    UnaryOperator *U = cast<UnaryOperator>(E);
1600
1601    if (U->getOpcode() == UnaryOperator::Deref)
1602      return EvalAddr(U->getSubExpr());
1603
1604    return NULL;
1605  }
1606
1607  case Stmt::ArraySubscriptExprClass: {
1608    // Array subscripts are potential references to data on the stack.  We
1609    // retrieve the DeclRefExpr* for the array variable if it indeed
1610    // has local storage.
1611    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1612  }
1613
1614  case Stmt::ConditionalOperatorClass: {
1615    // For conditional operators we need to see if either the LHS or RHS are
1616    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1617    ConditionalOperator *C = cast<ConditionalOperator>(E);
1618
1619    // Handle the GNU extension for missing LHS.
1620    if (Expr *lhsExpr = C->getLHS())
1621      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1622        return LHS;
1623
1624    return EvalVal(C->getRHS());
1625  }
1626
1627  // Accesses to members are potential references to data on the stack.
1628  case Stmt::MemberExprClass: {
1629    MemberExpr *M = cast<MemberExpr>(E);
1630
1631    // Check for indirect access.  We only want direct field accesses.
1632    if (!M->isArrow())
1633      return EvalVal(M->getBase());
1634    else
1635      return NULL;
1636  }
1637
1638  // Everything else: we simply don't reason about them.
1639  default:
1640    return NULL;
1641  }
1642}
1643
1644//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1645
1646/// Check for comparisons of floating point operands using != and ==.
1647/// Issue a warning if these are no self-comparisons, as they are not likely
1648/// to do what the programmer intended.
1649void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1650  bool EmitWarning = true;
1651
1652  Expr* LeftExprSansParen = lex->IgnoreParens();
1653  Expr* RightExprSansParen = rex->IgnoreParens();
1654
1655  // Special case: check for x == x (which is OK).
1656  // Do not emit warnings for such cases.
1657  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1658    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1659      if (DRL->getDecl() == DRR->getDecl())
1660        EmitWarning = false;
1661
1662
1663  // Special case: check for comparisons against literals that can be exactly
1664  //  represented by APFloat.  In such cases, do not emit a warning.  This
1665  //  is a heuristic: often comparison against such literals are used to
1666  //  detect if a value in a variable has not changed.  This clearly can
1667  //  lead to false negatives.
1668  if (EmitWarning) {
1669    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1670      if (FLL->isExact())
1671        EmitWarning = false;
1672    } else
1673      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1674        if (FLR->isExact())
1675          EmitWarning = false;
1676    }
1677  }
1678
1679  // Check for comparisons with builtin types.
1680  if (EmitWarning)
1681    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1682      if (CL->isBuiltinCall(Context))
1683        EmitWarning = false;
1684
1685  if (EmitWarning)
1686    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1687      if (CR->isBuiltinCall(Context))
1688        EmitWarning = false;
1689
1690  // Emit the diagnostic.
1691  if (EmitWarning)
1692    Diag(loc, diag::warn_floatingpoint_eq)
1693      << lex->getSourceRange() << rex->getSourceRange();
1694}
1695
1696//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1697//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
1698
1699namespace {
1700
1701/// Structure recording the 'active' range of an integer-valued
1702/// expression.
1703struct IntRange {
1704  /// The number of bits active in the int.
1705  unsigned Width;
1706
1707  /// True if the int is known not to have negative values.
1708  bool NonNegative;
1709
1710  IntRange() {}
1711  IntRange(unsigned Width, bool NonNegative)
1712    : Width(Width), NonNegative(NonNegative)
1713  {}
1714
1715  // Returns the range of the bool type.
1716  static IntRange forBoolType() {
1717    return IntRange(1, true);
1718  }
1719
1720  // Returns the range of an integral type.
1721  static IntRange forType(ASTContext &C, QualType T) {
1722    return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
1723  }
1724
1725  // Returns the range of an integeral type based on its canonical
1726  // representation.
1727  static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1728    assert(T->isCanonicalUnqualified());
1729
1730    if (const VectorType *VT = dyn_cast<VectorType>(T))
1731      T = VT->getElementType().getTypePtr();
1732    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1733      T = CT->getElementType().getTypePtr();
1734
1735    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
1736      EnumDecl *Enum = ET->getDecl();
1737      unsigned NumPositive = Enum->getNumPositiveBits();
1738      unsigned NumNegative = Enum->getNumNegativeBits();
1739
1740      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
1741    }
1742
1743    const BuiltinType *BT = cast<BuiltinType>(T);
1744    assert(BT->isInteger());
1745
1746    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1747  }
1748
1749  // Returns the supremum of two ranges: i.e. their conservative merge.
1750  static IntRange join(IntRange L, IntRange R) {
1751    return IntRange(std::max(L.Width, R.Width),
1752                    L.NonNegative && R.NonNegative);
1753  }
1754
1755  // Returns the infinum of two ranges: i.e. their aggressive merge.
1756  static IntRange meet(IntRange L, IntRange R) {
1757    return IntRange(std::min(L.Width, R.Width),
1758                    L.NonNegative || R.NonNegative);
1759  }
1760};
1761
1762IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1763  if (value.isSigned() && value.isNegative())
1764    return IntRange(value.getMinSignedBits(), false);
1765
1766  if (value.getBitWidth() > MaxWidth)
1767    value.trunc(MaxWidth);
1768
1769  // isNonNegative() just checks the sign bit without considering
1770  // signedness.
1771  return IntRange(value.getActiveBits(), true);
1772}
1773
1774IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
1775                       unsigned MaxWidth) {
1776  if (result.isInt())
1777    return GetValueRange(C, result.getInt(), MaxWidth);
1778
1779  if (result.isVector()) {
1780    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1781    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1782      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1783      R = IntRange::join(R, El);
1784    }
1785    return R;
1786  }
1787
1788  if (result.isComplexInt()) {
1789    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1790    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1791    return IntRange::join(R, I);
1792  }
1793
1794  // This can happen with lossless casts to intptr_t of "based" lvalues.
1795  // Assume it might use arbitrary bits.
1796  // FIXME: The only reason we need to pass the type in here is to get
1797  // the sign right on this one case.  It would be nice if APValue
1798  // preserved this.
1799  assert(result.isLValue());
1800  return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
1801}
1802
1803/// Pseudo-evaluate the given integer expression, estimating the
1804/// range of values it might take.
1805///
1806/// \param MaxWidth - the width to which the value will be truncated
1807IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1808  E = E->IgnoreParens();
1809
1810  // Try a full evaluation first.
1811  Expr::EvalResult result;
1812  if (E->Evaluate(result, C))
1813    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
1814
1815  // I think we only want to look through implicit casts here; if the
1816  // user has an explicit widening cast, we should treat the value as
1817  // being of the new, wider type.
1818  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1819    if (CE->getCastKind() == CastExpr::CK_NoOp)
1820      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1821
1822    IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1823
1824    bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1825    if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1826      isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1827
1828    // Assume that non-integer casts can span the full range of the type.
1829    if (!isIntegerCast)
1830      return OutputTypeRange;
1831
1832    IntRange SubRange
1833      = GetExprRange(C, CE->getSubExpr(),
1834                     std::min(MaxWidth, OutputTypeRange.Width));
1835
1836    // Bail out if the subexpr's range is as wide as the cast type.
1837    if (SubRange.Width >= OutputTypeRange.Width)
1838      return OutputTypeRange;
1839
1840    // Otherwise, we take the smaller width, and we're non-negative if
1841    // either the output type or the subexpr is.
1842    return IntRange(SubRange.Width,
1843                    SubRange.NonNegative || OutputTypeRange.NonNegative);
1844  }
1845
1846  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1847    // If we can fold the condition, just take that operand.
1848    bool CondResult;
1849    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1850      return GetExprRange(C, CondResult ? CO->getTrueExpr()
1851                                        : CO->getFalseExpr(),
1852                          MaxWidth);
1853
1854    // Otherwise, conservatively merge.
1855    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1856    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1857    return IntRange::join(L, R);
1858  }
1859
1860  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1861    switch (BO->getOpcode()) {
1862
1863    // Boolean-valued operations are single-bit and positive.
1864    case BinaryOperator::LAnd:
1865    case BinaryOperator::LOr:
1866    case BinaryOperator::LT:
1867    case BinaryOperator::GT:
1868    case BinaryOperator::LE:
1869    case BinaryOperator::GE:
1870    case BinaryOperator::EQ:
1871    case BinaryOperator::NE:
1872      return IntRange::forBoolType();
1873
1874    // The type of these compound assignments is the type of the LHS,
1875    // so the RHS is not necessarily an integer.
1876    case BinaryOperator::MulAssign:
1877    case BinaryOperator::DivAssign:
1878    case BinaryOperator::RemAssign:
1879    case BinaryOperator::AddAssign:
1880    case BinaryOperator::SubAssign:
1881      return IntRange::forType(C, E->getType());
1882
1883    // Operations with opaque sources are black-listed.
1884    case BinaryOperator::PtrMemD:
1885    case BinaryOperator::PtrMemI:
1886      return IntRange::forType(C, E->getType());
1887
1888    // Bitwise-and uses the *infinum* of the two source ranges.
1889    case BinaryOperator::And:
1890    case BinaryOperator::AndAssign:
1891      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1892                            GetExprRange(C, BO->getRHS(), MaxWidth));
1893
1894    // Left shift gets black-listed based on a judgement call.
1895    case BinaryOperator::Shl:
1896      // ...except that we want to treat '1 << (blah)' as logically
1897      // positive.  It's an important idiom.
1898      if (IntegerLiteral *I
1899            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1900        if (I->getValue() == 1) {
1901          IntRange R = IntRange::forType(C, E->getType());
1902          return IntRange(R.Width, /*NonNegative*/ true);
1903        }
1904      }
1905      // fallthrough
1906
1907    case BinaryOperator::ShlAssign:
1908      return IntRange::forType(C, E->getType());
1909
1910    // Right shift by a constant can narrow its left argument.
1911    case BinaryOperator::Shr:
1912    case BinaryOperator::ShrAssign: {
1913      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1914
1915      // If the shift amount is a positive constant, drop the width by
1916      // that much.
1917      llvm::APSInt shift;
1918      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1919          shift.isNonNegative()) {
1920        unsigned zext = shift.getZExtValue();
1921        if (zext >= L.Width)
1922          L.Width = (L.NonNegative ? 0 : 1);
1923        else
1924          L.Width -= zext;
1925      }
1926
1927      return L;
1928    }
1929
1930    // Comma acts as its right operand.
1931    case BinaryOperator::Comma:
1932      return GetExprRange(C, BO->getRHS(), MaxWidth);
1933
1934    // Black-list pointer subtractions.
1935    case BinaryOperator::Sub:
1936      if (BO->getLHS()->getType()->isPointerType())
1937        return IntRange::forType(C, E->getType());
1938      // fallthrough
1939
1940    default:
1941      break;
1942    }
1943
1944    // Treat every other operator as if it were closed on the
1945    // narrowest type that encompasses both operands.
1946    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1947    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1948    return IntRange::join(L, R);
1949  }
1950
1951  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1952    switch (UO->getOpcode()) {
1953    // Boolean-valued operations are white-listed.
1954    case UnaryOperator::LNot:
1955      return IntRange::forBoolType();
1956
1957    // Operations with opaque sources are black-listed.
1958    case UnaryOperator::Deref:
1959    case UnaryOperator::AddrOf: // should be impossible
1960    case UnaryOperator::OffsetOf:
1961      return IntRange::forType(C, E->getType());
1962
1963    default:
1964      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1965    }
1966  }
1967
1968  if (dyn_cast<OffsetOfExpr>(E)) {
1969    IntRange::forType(C, E->getType());
1970  }
1971
1972  FieldDecl *BitField = E->getBitField();
1973  if (BitField) {
1974    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1975    unsigned BitWidth = BitWidthAP.getZExtValue();
1976
1977    return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1978  }
1979
1980  return IntRange::forType(C, E->getType());
1981}
1982
1983IntRange GetExprRange(ASTContext &C, Expr *E) {
1984  return GetExprRange(C, E, C.getIntWidth(E->getType()));
1985}
1986
1987/// Checks whether the given value, which currently has the given
1988/// source semantics, has the same value when coerced through the
1989/// target semantics.
1990bool IsSameFloatAfterCast(const llvm::APFloat &value,
1991                          const llvm::fltSemantics &Src,
1992                          const llvm::fltSemantics &Tgt) {
1993  llvm::APFloat truncated = value;
1994
1995  bool ignored;
1996  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1997  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1998
1999  return truncated.bitwiseIsEqual(value);
2000}
2001
2002/// Checks whether the given value, which currently has the given
2003/// source semantics, has the same value when coerced through the
2004/// target semantics.
2005///
2006/// The value might be a vector of floats (or a complex number).
2007bool IsSameFloatAfterCast(const APValue &value,
2008                          const llvm::fltSemantics &Src,
2009                          const llvm::fltSemantics &Tgt) {
2010  if (value.isFloat())
2011    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2012
2013  if (value.isVector()) {
2014    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2015      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2016        return false;
2017    return true;
2018  }
2019
2020  assert(value.isComplexFloat());
2021  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2022          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2023}
2024
2025void AnalyzeImplicitConversions(Sema &S, Expr *E);
2026
2027bool IsZero(Sema &S, Expr *E) {
2028  llvm::APSInt Value;
2029  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2030}
2031
2032void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
2033  BinaryOperator::Opcode op = E->getOpcode();
2034  if (op == BinaryOperator::LT && IsZero(S, E->getRHS())) {
2035    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2036      << "< 0" << "false"
2037      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2038  } else if (op == BinaryOperator::GE && IsZero(S, E->getRHS())) {
2039    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
2040      << ">= 0" << "true"
2041      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2042  } else if (op == BinaryOperator::GT && IsZero(S, E->getLHS())) {
2043    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2044      << "0 >" << "false"
2045      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2046  } else if (op == BinaryOperator::LE && IsZero(S, E->getLHS())) {
2047    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
2048      << "0 <=" << "true"
2049      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2050  }
2051}
2052
2053/// Analyze the operands of the given comparison.  Implements the
2054/// fallback case from AnalyzeComparison.
2055void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
2056  AnalyzeImplicitConversions(S, E->getLHS());
2057  AnalyzeImplicitConversions(S, E->getRHS());
2058}
2059
2060/// \brief Implements -Wsign-compare.
2061///
2062/// \param lex the left-hand expression
2063/// \param rex the right-hand expression
2064/// \param OpLoc the location of the joining operator
2065/// \param BinOpc binary opcode or 0
2066void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2067  // The type the comparison is being performed in.
2068  QualType T = E->getLHS()->getType();
2069  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2070         && "comparison with mismatched types");
2071
2072  // We don't do anything special if this isn't an unsigned integral
2073  // comparison:  we're only interested in integral comparisons, and
2074  // signed comparisons only happen in cases we don't care to warn about.
2075  if (!T->isUnsignedIntegerType())
2076    return AnalyzeImpConvsInComparison(S, E);
2077
2078  Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2079  Expr *rex = E->getRHS()->IgnoreParenImpCasts();
2080
2081  // Check to see if one of the (unmodified) operands is of different
2082  // signedness.
2083  Expr *signedOperand, *unsignedOperand;
2084  if (lex->getType()->isSignedIntegerType()) {
2085    assert(!rex->getType()->isSignedIntegerType() &&
2086           "unsigned comparison between two signed integer expressions?");
2087    signedOperand = lex;
2088    unsignedOperand = rex;
2089  } else if (rex->getType()->isSignedIntegerType()) {
2090    signedOperand = rex;
2091    unsignedOperand = lex;
2092  } else {
2093    CheckTrivialUnsignedComparison(S, E);
2094    return AnalyzeImpConvsInComparison(S, E);
2095  }
2096
2097  // Otherwise, calculate the effective range of the signed operand.
2098  IntRange signedRange = GetExprRange(S.Context, signedOperand);
2099
2100  // Go ahead and analyze implicit conversions in the operands.  Note
2101  // that we skip the implicit conversions on both sides.
2102  AnalyzeImplicitConversions(S, lex);
2103  AnalyzeImplicitConversions(S, rex);
2104
2105  // If the signed range is non-negative, -Wsign-compare won't fire,
2106  // but we should still check for comparisons which are always true
2107  // or false.
2108  if (signedRange.NonNegative)
2109    return CheckTrivialUnsignedComparison(S, E);
2110
2111  // For (in)equality comparisons, if the unsigned operand is a
2112  // constant which cannot collide with a overflowed signed operand,
2113  // then reinterpreting the signed operand as unsigned will not
2114  // change the result of the comparison.
2115  if (E->isEqualityOp()) {
2116    unsigned comparisonWidth = S.Context.getIntWidth(T);
2117    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
2118
2119    // We should never be unable to prove that the unsigned operand is
2120    // non-negative.
2121    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2122
2123    if (unsignedRange.Width < comparisonWidth)
2124      return;
2125  }
2126
2127  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2128    << lex->getType() << rex->getType()
2129    << lex->getSourceRange() << rex->getSourceRange();
2130}
2131
2132/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2133void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2134  S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2135}
2136
2137void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
2138                             bool *ICContext = 0) {
2139  if (E->isTypeDependent() || E->isValueDependent()) return;
2140
2141  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2142  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2143  if (Source == Target) return;
2144  if (Target->isDependentType()) return;
2145
2146  // Never diagnose implicit casts to bool.
2147  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2148    return;
2149
2150  // Strip vector types.
2151  if (isa<VectorType>(Source)) {
2152    if (!isa<VectorType>(Target))
2153      return DiagnoseImpCast(S, E, T, diag::warn_impcast_vector_scalar);
2154
2155    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2156    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2157  }
2158
2159  // Strip complex types.
2160  if (isa<ComplexType>(Source)) {
2161    if (!isa<ComplexType>(Target))
2162      return DiagnoseImpCast(S, E, T, diag::warn_impcast_complex_scalar);
2163
2164    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2165    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2166  }
2167
2168  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2169  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2170
2171  // If the source is floating point...
2172  if (SourceBT && SourceBT->isFloatingPoint()) {
2173    // ...and the target is floating point...
2174    if (TargetBT && TargetBT->isFloatingPoint()) {
2175      // ...then warn if we're dropping FP rank.
2176
2177      // Builtin FP kinds are ordered by increasing FP rank.
2178      if (SourceBT->getKind() > TargetBT->getKind()) {
2179        // Don't warn about float constants that are precisely
2180        // representable in the target type.
2181        Expr::EvalResult result;
2182        if (E->Evaluate(result, S.Context)) {
2183          // Value might be a float, a float vector, or a float complex.
2184          if (IsSameFloatAfterCast(result.Val,
2185                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2186                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2187            return;
2188        }
2189
2190        DiagnoseImpCast(S, E, T, diag::warn_impcast_float_precision);
2191      }
2192      return;
2193    }
2194
2195    // If the target is integral, always warn.
2196    if ((TargetBT && TargetBT->isInteger()))
2197      // TODO: don't warn for integer values?
2198      DiagnoseImpCast(S, E, T, diag::warn_impcast_float_integer);
2199
2200    return;
2201  }
2202
2203  if (!Source->isIntegerType() || !Target->isIntegerType())
2204    return;
2205
2206  IntRange SourceRange = GetExprRange(S.Context, E);
2207  IntRange TargetRange = IntRange::forCanonicalType(S.Context, Target);
2208
2209  if (SourceRange.Width > TargetRange.Width) {
2210    // People want to build with -Wshorten-64-to-32 and not -Wconversion
2211    // and by god we'll let them.
2212    if (SourceRange.Width == 64 && TargetRange.Width == 32)
2213      return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_64_32);
2214    return DiagnoseImpCast(S, E, T, diag::warn_impcast_integer_precision);
2215  }
2216
2217  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2218      (!TargetRange.NonNegative && SourceRange.NonNegative &&
2219       SourceRange.Width == TargetRange.Width)) {
2220    unsigned DiagID = diag::warn_impcast_integer_sign;
2221
2222    // Traditionally, gcc has warned about this under -Wsign-compare.
2223    // We also want to warn about it in -Wconversion.
2224    // So if -Wconversion is off, use a completely identical diagnostic
2225    // in the sign-compare group.
2226    // The conditional-checking code will
2227    if (ICContext) {
2228      DiagID = diag::warn_impcast_integer_sign_conditional;
2229      *ICContext = true;
2230    }
2231
2232    return DiagnoseImpCast(S, E, T, DiagID);
2233  }
2234
2235  return;
2236}
2237
2238void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2239
2240void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
2241                             bool &ICContext) {
2242  E = E->IgnoreParenImpCasts();
2243
2244  if (isa<ConditionalOperator>(E))
2245    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2246
2247  AnalyzeImplicitConversions(S, E);
2248  if (E->getType() != T)
2249    return CheckImplicitConversion(S, E, T, &ICContext);
2250  return;
2251}
2252
2253void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
2254  AnalyzeImplicitConversions(S, E->getCond());
2255
2256  bool Suspicious = false;
2257  CheckConditionalOperand(S, E->getTrueExpr(), T, Suspicious);
2258  CheckConditionalOperand(S, E->getFalseExpr(), T, Suspicious);
2259
2260  // If -Wconversion would have warned about either of the candidates
2261  // for a signedness conversion to the context type...
2262  if (!Suspicious) return;
2263
2264  // ...but it's currently ignored...
2265  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2266    return;
2267
2268  // ...and -Wsign-compare isn't...
2269  if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2270    return;
2271
2272  // ...then check whether it would have warned about either of the
2273  // candidates for a signedness conversion to the condition type.
2274  if (E->getType() != T) {
2275    Suspicious = false;
2276    CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
2277                            E->getType(), &Suspicious);
2278    if (!Suspicious)
2279      CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
2280                              E->getType(), &Suspicious);
2281    if (!Suspicious)
2282      return;
2283  }
2284
2285  // If so, emit a diagnostic under -Wsign-compare.
2286  Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2287  Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2288  S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2289    << lex->getType() << rex->getType()
2290    << lex->getSourceRange() << rex->getSourceRange();
2291}
2292
2293/// AnalyzeImplicitConversions - Find and report any interesting
2294/// implicit conversions in the given expression.  There are a couple
2295/// of competing diagnostics here, -Wconversion and -Wsign-compare.
2296void AnalyzeImplicitConversions(Sema &S, Expr *OrigE) {
2297  QualType T = OrigE->getType();
2298  Expr *E = OrigE->IgnoreParenImpCasts();
2299
2300  // For conditional operators, we analyze the arguments as if they
2301  // were being fed directly into the output.
2302  if (isa<ConditionalOperator>(E)) {
2303    ConditionalOperator *CO = cast<ConditionalOperator>(E);
2304    CheckConditionalOperator(S, CO, T);
2305    return;
2306  }
2307
2308  // Go ahead and check any implicit conversions we might have skipped.
2309  // The non-canonical typecheck is just an optimization;
2310  // CheckImplicitConversion will filter out dead implicit conversions.
2311  if (E->getType() != T)
2312    CheckImplicitConversion(S, E, T);
2313
2314  // Now continue drilling into this expression.
2315
2316  // Skip past explicit casts.
2317  if (isa<ExplicitCastExpr>(E)) {
2318    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
2319    return AnalyzeImplicitConversions(S, E);
2320  }
2321
2322  // Do a somewhat different check with comparison operators.
2323  if (isa<BinaryOperator>(E) && cast<BinaryOperator>(E)->isComparisonOp())
2324    return AnalyzeComparison(S, cast<BinaryOperator>(E));
2325
2326  // These break the otherwise-useful invariant below.  Fortunately,
2327  // we don't really need to recurse into them, because any internal
2328  // expressions should have been analyzed already when they were
2329  // built into statements.
2330  if (isa<StmtExpr>(E)) return;
2331
2332  // Don't descend into unevaluated contexts.
2333  if (isa<SizeOfAlignOfExpr>(E)) return;
2334
2335  // Now just recurse over the expression's children.
2336  for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2337         I != IE; ++I)
2338    AnalyzeImplicitConversions(S, cast<Expr>(*I));
2339}
2340
2341} // end anonymous namespace
2342
2343/// Diagnoses "dangerous" implicit conversions within the given
2344/// expression (which is a full expression).  Implements -Wconversion
2345/// and -Wsign-compare.
2346void Sema::CheckImplicitConversions(Expr *E) {
2347  // Don't diagnose in unevaluated contexts.
2348  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2349    return;
2350
2351  // Don't diagnose for value- or type-dependent expressions.
2352  if (E->isTypeDependent() || E->isValueDependent())
2353    return;
2354
2355  AnalyzeImplicitConversions(*this, E);
2356}
2357
2358/// CheckParmsForFunctionDef - Check that the parameters of the given
2359/// function are appropriate for the definition of a function. This
2360/// takes care of any checks that cannot be performed on the
2361/// declaration itself, e.g., that the types of each of the function
2362/// parameters are complete.
2363bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2364  bool HasInvalidParm = false;
2365  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2366    ParmVarDecl *Param = FD->getParamDecl(p);
2367
2368    // C99 6.7.5.3p4: the parameters in a parameter type list in a
2369    // function declarator that is part of a function definition of
2370    // that function shall not have incomplete type.
2371    //
2372    // This is also C++ [dcl.fct]p6.
2373    if (!Param->isInvalidDecl() &&
2374        RequireCompleteType(Param->getLocation(), Param->getType(),
2375                               diag::err_typecheck_decl_incomplete_type)) {
2376      Param->setInvalidDecl();
2377      HasInvalidParm = true;
2378    }
2379
2380    // C99 6.9.1p5: If the declarator includes a parameter type list, the
2381    // declaration of each parameter shall include an identifier.
2382    if (Param->getIdentifier() == 0 &&
2383        !Param->isImplicit() &&
2384        !getLangOptions().CPlusPlus)
2385      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
2386
2387    // C99 6.7.5.3p12:
2388    //   If the function declarator is not part of a definition of that
2389    //   function, parameters may have incomplete type and may use the [*]
2390    //   notation in their sequences of declarator specifiers to specify
2391    //   variable length array types.
2392    QualType PType = Param->getOriginalType();
2393    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2394      if (AT->getSizeModifier() == ArrayType::Star) {
2395        // FIXME: This diagnosic should point the the '[*]' if source-location
2396        // information is added for it.
2397        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2398      }
2399    }
2400  }
2401
2402  return HasInvalidParm;
2403}
2404