SemaChecking.cpp revision 9498d388810d284d3970aef0d69fa4d069fd6caf
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 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  return false;
617}
618
619/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
620// This is declared to take (...), so we have to check everything.
621Action::OwningExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
622  if (TheCall->getNumArgs() < 3)
623    return ExprError(Diag(TheCall->getLocEnd(),
624                          diag::err_typecheck_call_too_few_args_at_least)
625      << 0 /*function call*/ << 3 << TheCall->getNumArgs()
626      << TheCall->getSourceRange());
627
628  unsigned numElements = std::numeric_limits<unsigned>::max();
629  if (!TheCall->getArg(0)->isTypeDependent() &&
630      !TheCall->getArg(1)->isTypeDependent()) {
631    QualType FAType = TheCall->getArg(0)->getType();
632    QualType SAType = TheCall->getArg(1)->getType();
633
634    if (!FAType->isVectorType() || !SAType->isVectorType()) {
635      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
636        << SourceRange(TheCall->getArg(0)->getLocStart(),
637                       TheCall->getArg(1)->getLocEnd());
638      return ExprError();
639    }
640
641    if (!Context.hasSameUnqualifiedType(FAType, SAType)) {
642      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
643        << SourceRange(TheCall->getArg(0)->getLocStart(),
644                       TheCall->getArg(1)->getLocEnd());
645      return ExprError();
646    }
647
648    numElements = FAType->getAs<VectorType>()->getNumElements();
649    if (TheCall->getNumArgs() != numElements+2) {
650      if (TheCall->getNumArgs() < numElements+2)
651        return ExprError(Diag(TheCall->getLocEnd(),
652                              diag::err_typecheck_call_too_few_args)
653                 << 0 /*function call*/
654                 << numElements+2 << TheCall->getNumArgs()
655                 << TheCall->getSourceRange());
656      return ExprError(Diag(TheCall->getLocEnd(),
657                            diag::err_typecheck_call_too_many_args)
658                 << 0 /*function call*/
659                 << numElements+2 << TheCall->getNumArgs()
660                 << TheCall->getSourceRange());
661    }
662  }
663
664  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
665    if (TheCall->getArg(i)->isTypeDependent() ||
666        TheCall->getArg(i)->isValueDependent())
667      continue;
668
669    llvm::APSInt Result;
670    if (SemaBuiltinConstantArg(TheCall, i, Result))
671      return ExprError();
672
673    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
674      return ExprError(Diag(TheCall->getLocStart(),
675                  diag::err_shufflevector_argument_too_large)
676               << TheCall->getArg(i)->getSourceRange());
677  }
678
679  llvm::SmallVector<Expr*, 32> exprs;
680
681  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
682    exprs.push_back(TheCall->getArg(i));
683    TheCall->setArg(i, 0);
684  }
685
686  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
687                                            exprs.size(), exprs[0]->getType(),
688                                            TheCall->getCallee()->getLocStart(),
689                                            TheCall->getRParenLoc()));
690}
691
692/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
693// This is declared to take (const void*, ...) and can take two
694// optional constant int args.
695bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
696  unsigned NumArgs = TheCall->getNumArgs();
697
698  if (NumArgs > 3)
699    return Diag(TheCall->getLocEnd(),
700             diag::err_typecheck_call_too_many_args_at_most)
701             << 0 /*function call*/ << 3 << NumArgs
702             << TheCall->getSourceRange();
703
704  // Argument 0 is checked for us and the remaining arguments must be
705  // constant integers.
706  for (unsigned i = 1; i != NumArgs; ++i) {
707    Expr *Arg = TheCall->getArg(i);
708
709    llvm::APSInt Result;
710    if (SemaBuiltinConstantArg(TheCall, i, Result))
711      return true;
712
713    // FIXME: gcc issues a warning and rewrites these to 0. These
714    // seems especially odd for the third argument since the default
715    // is 3.
716    if (i == 1) {
717      if (Result.getLimitedValue() > 1)
718        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
719             << "0" << "1" << Arg->getSourceRange();
720    } else {
721      if (Result.getLimitedValue() > 3)
722        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
723            << "0" << "3" << Arg->getSourceRange();
724    }
725  }
726
727  return false;
728}
729
730/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
731/// TheCall is a constant expression.
732bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
733                                  llvm::APSInt &Result) {
734  Expr *Arg = TheCall->getArg(ArgNum);
735  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
736  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
737
738  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
739
740  if (!Arg->isIntegerConstantExpr(Result, Context))
741    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
742                << FDecl->getDeclName() <<  Arg->getSourceRange();
743
744  return false;
745}
746
747/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
748/// int type). This simply type checks that type is one of the defined
749/// constants (0-3).
750// For compatability check 0-3, llvm only handles 0 and 2.
751bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
752  llvm::APSInt Result;
753
754  // Check constant-ness first.
755  if (SemaBuiltinConstantArg(TheCall, 1, Result))
756    return true;
757
758  Expr *Arg = TheCall->getArg(1);
759  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
760    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
761             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
762  }
763
764  return false;
765}
766
767/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
768/// This checks that val is a constant 1.
769bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
770  Expr *Arg = TheCall->getArg(1);
771  llvm::APSInt Result;
772
773  // TODO: This is less than ideal. Overload this to take a value.
774  if (SemaBuiltinConstantArg(TheCall, 1, Result))
775    return true;
776
777  if (Result != 1)
778    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
779             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
780
781  return false;
782}
783
784// Handle i > 1 ? "x" : "y", recursivelly
785bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
786                                  bool HasVAListArg,
787                                  unsigned format_idx, unsigned firstDataArg) {
788  if (E->isTypeDependent() || E->isValueDependent())
789    return false;
790
791  switch (E->getStmtClass()) {
792  case Stmt::ConditionalOperatorClass: {
793    const ConditionalOperator *C = cast<ConditionalOperator>(E);
794    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall,
795                                  HasVAListArg, format_idx, firstDataArg)
796        && SemaCheckStringLiteral(C->getRHS(), TheCall,
797                                  HasVAListArg, format_idx, firstDataArg);
798  }
799
800  case Stmt::ImplicitCastExprClass: {
801    const ImplicitCastExpr *Expr = cast<ImplicitCastExpr>(E);
802    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
803                                  format_idx, firstDataArg);
804  }
805
806  case Stmt::ParenExprClass: {
807    const ParenExpr *Expr = cast<ParenExpr>(E);
808    return SemaCheckStringLiteral(Expr->getSubExpr(), TheCall, HasVAListArg,
809                                  format_idx, firstDataArg);
810  }
811
812  case Stmt::DeclRefExprClass: {
813    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
814
815    // As an exception, do not flag errors for variables binding to
816    // const string literals.
817    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
818      bool isConstant = false;
819      QualType T = DR->getType();
820
821      if (const ArrayType *AT = Context.getAsArrayType(T)) {
822        isConstant = AT->getElementType().isConstant(Context);
823      } else if (const PointerType *PT = T->getAs<PointerType>()) {
824        isConstant = T.isConstant(Context) &&
825                     PT->getPointeeType().isConstant(Context);
826      }
827
828      if (isConstant) {
829        if (const Expr *Init = VD->getAnyInitializer())
830          return SemaCheckStringLiteral(Init, TheCall,
831                                        HasVAListArg, format_idx, firstDataArg);
832      }
833
834      // For vprintf* functions (i.e., HasVAListArg==true), we add a
835      // special check to see if the format string is a function parameter
836      // of the function calling the printf function.  If the function
837      // has an attribute indicating it is a printf-like function, then we
838      // should suppress warnings concerning non-literals being used in a call
839      // to a vprintf function.  For example:
840      //
841      // void
842      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
843      //      va_list ap;
844      //      va_start(ap, fmt);
845      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
846      //      ...
847      //
848      //
849      //  FIXME: We don't have full attribute support yet, so just check to see
850      //    if the argument is a DeclRefExpr that references a parameter.  We'll
851      //    add proper support for checking the attribute later.
852      if (HasVAListArg)
853        if (isa<ParmVarDecl>(VD))
854          return true;
855    }
856
857    return false;
858  }
859
860  case Stmt::CallExprClass: {
861    const CallExpr *CE = cast<CallExpr>(E);
862    if (const ImplicitCastExpr *ICE
863          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
864      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
865        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
866          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
867            unsigned ArgIndex = FA->getFormatIdx();
868            const Expr *Arg = CE->getArg(ArgIndex - 1);
869
870            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
871                                          format_idx, firstDataArg);
872          }
873        }
874      }
875    }
876
877    return false;
878  }
879  case Stmt::ObjCStringLiteralClass:
880  case Stmt::StringLiteralClass: {
881    const StringLiteral *StrE = NULL;
882
883    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
884      StrE = ObjCFExpr->getString();
885    else
886      StrE = cast<StringLiteral>(E);
887
888    if (StrE) {
889      CheckPrintfString(StrE, E, TheCall, HasVAListArg, format_idx,
890                        firstDataArg);
891      return true;
892    }
893
894    return false;
895  }
896
897  default:
898    return false;
899  }
900}
901
902void
903Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
904                            const CallExpr *TheCall) {
905  for (NonNullAttr::iterator i = NonNull->begin(), e = NonNull->end();
906       i != e; ++i) {
907    const Expr *ArgExpr = TheCall->getArg(*i);
908    if (ArgExpr->isNullPointerConstant(Context,
909                                       Expr::NPC_ValueDependentIsNotNull))
910      Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
911        << ArgExpr->getSourceRange();
912  }
913}
914
915/// CheckPrintfArguments - Check calls to printf (and similar functions) for
916/// correct use of format strings.
917///
918///  HasVAListArg - A predicate indicating whether the printf-like
919///    function is passed an explicit va_arg argument (e.g., vprintf)
920///
921///  format_idx - The index into Args for the format string.
922///
923/// Improper format strings to functions in the printf family can be
924/// the source of bizarre bugs and very serious security holes.  A
925/// good source of information is available in the following paper
926/// (which includes additional references):
927///
928///  FormatGuard: Automatic Protection From printf Format String
929///  Vulnerabilities, Proceedings of the 10th USENIX Security Symposium, 2001.
930///
931/// TODO:
932/// Functionality implemented:
933///
934///  We can statically check the following properties for string
935///  literal format strings for non v.*printf functions (where the
936///  arguments are passed directly):
937//
938///  (1) Are the number of format conversions equal to the number of
939///      data arguments?
940///
941///  (2) Does each format conversion correctly match the type of the
942///      corresponding data argument?
943///
944/// Moreover, for all printf functions we can:
945///
946///  (3) Check for a missing format string (when not caught by type checking).
947///
948///  (4) Check for no-operation flags; e.g. using "#" with format
949///      conversion 'c'  (TODO)
950///
951///  (5) Check the use of '%n', a major source of security holes.
952///
953///  (6) Check for malformed format conversions that don't specify anything.
954///
955///  (7) Check for empty format strings.  e.g: printf("");
956///
957///  (8) Check that the format string is a wide literal.
958///
959/// All of these checks can be done by parsing the format string.
960///
961void
962Sema::CheckPrintfArguments(const CallExpr *TheCall, bool HasVAListArg,
963                           unsigned format_idx, unsigned firstDataArg) {
964  const Expr *Fn = TheCall->getCallee();
965
966  // The way the format attribute works in GCC, the implicit this argument
967  // of member functions is counted. However, it doesn't appear in our own
968  // lists, so decrement format_idx in that case.
969  if (isa<CXXMemberCallExpr>(TheCall)) {
970    // Catch a format attribute mistakenly referring to the object argument.
971    if (format_idx == 0)
972      return;
973    --format_idx;
974    if(firstDataArg != 0)
975      --firstDataArg;
976  }
977
978  // CHECK: printf-like function is called with no format string.
979  if (format_idx >= TheCall->getNumArgs()) {
980    Diag(TheCall->getRParenLoc(), diag::warn_printf_missing_format_string)
981      << Fn->getSourceRange();
982    return;
983  }
984
985  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
986
987  // CHECK: format string is not a string literal.
988  //
989  // Dynamically generated format strings are difficult to
990  // automatically vet at compile time.  Requiring that format strings
991  // are string literals: (1) permits the checking of format strings by
992  // the compiler and thereby (2) can practically remove the source of
993  // many format string exploits.
994
995  // Format string can be either ObjC string (e.g. @"%d") or
996  // C string (e.g. "%d")
997  // ObjC string uses the same format specifiers as C string, so we can use
998  // the same format string checking logic for both ObjC and C strings.
999  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1000                             firstDataArg))
1001    return;  // Literal format string found, check done!
1002
1003  // If there are no arguments specified, warn with -Wformat-security, otherwise
1004  // warn only with -Wformat-nonliteral.
1005  if (TheCall->getNumArgs() == format_idx+1)
1006    Diag(TheCall->getArg(format_idx)->getLocStart(),
1007         diag::warn_printf_nonliteral_noargs)
1008      << OrigFormatExpr->getSourceRange();
1009  else
1010    Diag(TheCall->getArg(format_idx)->getLocStart(),
1011         diag::warn_printf_nonliteral)
1012           << OrigFormatExpr->getSourceRange();
1013}
1014
1015namespace {
1016class CheckPrintfHandler : public analyze_printf::FormatStringHandler {
1017  Sema &S;
1018  const StringLiteral *FExpr;
1019  const Expr *OrigFormatExpr;
1020  const unsigned FirstDataArg;
1021  const unsigned NumDataArgs;
1022  const bool IsObjCLiteral;
1023  const char *Beg; // Start of format string.
1024  const bool HasVAListArg;
1025  const CallExpr *TheCall;
1026  unsigned FormatIdx;
1027  llvm::BitVector CoveredArgs;
1028  bool usesPositionalArgs;
1029  bool atFirstArg;
1030public:
1031  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1032                     const Expr *origFormatExpr, unsigned firstDataArg,
1033                     unsigned numDataArgs, bool isObjCLiteral,
1034                     const char *beg, bool hasVAListArg,
1035                     const CallExpr *theCall, unsigned formatIdx)
1036    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1037      FirstDataArg(firstDataArg),
1038      NumDataArgs(numDataArgs),
1039      IsObjCLiteral(isObjCLiteral), Beg(beg),
1040      HasVAListArg(hasVAListArg),
1041      TheCall(theCall), FormatIdx(formatIdx),
1042      usesPositionalArgs(false), atFirstArg(true) {
1043        CoveredArgs.resize(numDataArgs);
1044        CoveredArgs.reset();
1045      }
1046
1047  void DoneProcessing();
1048
1049  void HandleIncompleteFormatSpecifier(const char *startSpecifier,
1050                                       unsigned specifierLen);
1051
1052  bool
1053  HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1054                                   const char *startSpecifier,
1055                                   unsigned specifierLen);
1056
1057  virtual void HandleInvalidPosition(const char *startSpecifier,
1058                                     unsigned specifierLen,
1059                                     analyze_printf::PositionContext p);
1060
1061  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1062
1063  void HandleNullChar(const char *nullCharacter);
1064
1065  bool HandleFormatSpecifier(const analyze_printf::FormatSpecifier &FS,
1066                             const char *startSpecifier,
1067                             unsigned specifierLen);
1068private:
1069  SourceRange getFormatStringRange();
1070  SourceRange getFormatSpecifierRange(const char *startSpecifier,
1071                                      unsigned specifierLen);
1072  SourceLocation getLocationOfByte(const char *x);
1073
1074  bool HandleAmount(const analyze_printf::OptionalAmount &Amt, unsigned k,
1075                    const char *startSpecifier, unsigned specifierLen);
1076  void HandleFlags(const analyze_printf::FormatSpecifier &FS,
1077                   llvm::StringRef flag, llvm::StringRef cspec,
1078                   const char *startSpecifier, unsigned specifierLen);
1079
1080  const Expr *getDataArg(unsigned i) const;
1081};
1082}
1083
1084SourceRange CheckPrintfHandler::getFormatStringRange() {
1085  return OrigFormatExpr->getSourceRange();
1086}
1087
1088SourceRange CheckPrintfHandler::
1089getFormatSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1090  return SourceRange(getLocationOfByte(startSpecifier),
1091                     getLocationOfByte(startSpecifier+specifierLen-1));
1092}
1093
1094SourceLocation CheckPrintfHandler::getLocationOfByte(const char *x) {
1095  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1096}
1097
1098void CheckPrintfHandler::
1099HandleIncompleteFormatSpecifier(const char *startSpecifier,
1100                                unsigned specifierLen) {
1101  SourceLocation Loc = getLocationOfByte(startSpecifier);
1102  S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1103    << getFormatSpecifierRange(startSpecifier, specifierLen);
1104}
1105
1106void
1107CheckPrintfHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1108                                          analyze_printf::PositionContext p) {
1109  SourceLocation Loc = getLocationOfByte(startPos);
1110  S.Diag(Loc, diag::warn_printf_invalid_positional_specifier)
1111    << (unsigned) p << getFormatSpecifierRange(startPos, posLen);
1112}
1113
1114void CheckPrintfHandler::HandleZeroPosition(const char *startPos,
1115                                            unsigned posLen) {
1116  SourceLocation Loc = getLocationOfByte(startPos);
1117  S.Diag(Loc, diag::warn_printf_zero_positional_specifier)
1118    << getFormatSpecifierRange(startPos, posLen);
1119}
1120
1121bool CheckPrintfHandler::
1122HandleInvalidConversionSpecifier(const analyze_printf::FormatSpecifier &FS,
1123                                 const char *startSpecifier,
1124                                 unsigned specifierLen) {
1125
1126  unsigned argIndex = FS.getArgIndex();
1127  bool keepGoing = true;
1128  if (argIndex < NumDataArgs) {
1129    // Consider the argument coverered, even though the specifier doesn't
1130    // make sense.
1131    CoveredArgs.set(argIndex);
1132  }
1133  else {
1134    // If argIndex exceeds the number of data arguments we
1135    // don't issue a warning because that is just a cascade of warnings (and
1136    // they may have intended '%%' anyway). We don't want to continue processing
1137    // the format string after this point, however, as we will like just get
1138    // gibberish when trying to match arguments.
1139    keepGoing = false;
1140  }
1141
1142  const analyze_printf::ConversionSpecifier &CS =
1143    FS.getConversionSpecifier();
1144  SourceLocation Loc = getLocationOfByte(CS.getStart());
1145  S.Diag(Loc, diag::warn_printf_invalid_conversion)
1146      << llvm::StringRef(CS.getStart(), CS.getLength())
1147      << getFormatSpecifierRange(startSpecifier, specifierLen);
1148
1149  return keepGoing;
1150}
1151
1152void CheckPrintfHandler::HandleNullChar(const char *nullCharacter) {
1153  // The presence of a null character is likely an error.
1154  S.Diag(getLocationOfByte(nullCharacter),
1155         diag::warn_printf_format_string_contains_null_char)
1156    << getFormatStringRange();
1157}
1158
1159const Expr *CheckPrintfHandler::getDataArg(unsigned i) const {
1160  return TheCall->getArg(FirstDataArg + i);
1161}
1162
1163void CheckPrintfHandler::HandleFlags(const analyze_printf::FormatSpecifier &FS,
1164                                     llvm::StringRef flag,
1165                                     llvm::StringRef cspec,
1166                                     const char *startSpecifier,
1167                                     unsigned specifierLen) {
1168  const analyze_printf::ConversionSpecifier &CS = FS.getConversionSpecifier();
1169  S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_nonsensical_flag)
1170    << flag << cspec << getFormatSpecifierRange(startSpecifier, specifierLen);
1171}
1172
1173bool
1174CheckPrintfHandler::HandleAmount(const analyze_printf::OptionalAmount &Amt,
1175                                 unsigned k, const char *startSpecifier,
1176                                 unsigned specifierLen) {
1177
1178  if (Amt.hasDataArgument()) {
1179    if (!HasVAListArg) {
1180      unsigned argIndex = Amt.getArgIndex();
1181      if (argIndex >= NumDataArgs) {
1182        S.Diag(getLocationOfByte(Amt.getStart()),
1183               diag::warn_printf_asterisk_missing_arg)
1184          << k << getFormatSpecifierRange(startSpecifier, specifierLen);
1185        // Don't do any more checking.  We will just emit
1186        // spurious errors.
1187        return false;
1188      }
1189
1190      // Type check the data argument.  It should be an 'int'.
1191      // Although not in conformance with C99, we also allow the argument to be
1192      // an 'unsigned int' as that is a reasonably safe case.  GCC also
1193      // doesn't emit a warning for that case.
1194      CoveredArgs.set(argIndex);
1195      const Expr *Arg = getDataArg(argIndex);
1196      QualType T = Arg->getType();
1197
1198      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1199      assert(ATR.isValid());
1200
1201      if (!ATR.matchesType(S.Context, T)) {
1202        S.Diag(getLocationOfByte(Amt.getStart()),
1203               diag::warn_printf_asterisk_wrong_type)
1204          << k
1205          << ATR.getRepresentativeType(S.Context) << T
1206          << getFormatSpecifierRange(startSpecifier, specifierLen)
1207          << Arg->getSourceRange();
1208        // Don't do any more checking.  We will just emit
1209        // spurious errors.
1210        return false;
1211      }
1212    }
1213  }
1214  return true;
1215}
1216
1217bool
1218CheckPrintfHandler::HandleFormatSpecifier(const analyze_printf::FormatSpecifier
1219                                            &FS,
1220                                          const char *startSpecifier,
1221                                          unsigned specifierLen) {
1222
1223  using namespace analyze_printf;
1224  const ConversionSpecifier &CS = FS.getConversionSpecifier();
1225
1226  if (atFirstArg) {
1227    atFirstArg = false;
1228    usesPositionalArgs = FS.usesPositionalArg();
1229  }
1230  else if (usesPositionalArgs != FS.usesPositionalArg()) {
1231    // Cannot mix-and-match positional and non-positional arguments.
1232    S.Diag(getLocationOfByte(CS.getStart()),
1233           diag::warn_printf_mix_positional_nonpositional_args)
1234      << getFormatSpecifierRange(startSpecifier, specifierLen);
1235    return false;
1236  }
1237
1238  // First check if the field width, precision, and conversion specifier
1239  // have matching data arguments.
1240  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1241                    startSpecifier, specifierLen)) {
1242    return false;
1243  }
1244
1245  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1246                    startSpecifier, specifierLen)) {
1247    return false;
1248  }
1249
1250  if (!CS.consumesDataArgument()) {
1251    // FIXME: Technically specifying a precision or field width here
1252    // makes no sense.  Worth issuing a warning at some point.
1253    return true;
1254  }
1255
1256  // Consume the argument.
1257  unsigned argIndex = FS.getArgIndex();
1258  if (argIndex < NumDataArgs) {
1259    // The check to see if the argIndex is valid will come later.
1260    // We set the bit here because we may exit early from this
1261    // function if we encounter some other error.
1262    CoveredArgs.set(argIndex);
1263  }
1264
1265  // Check for using an Objective-C specific conversion specifier
1266  // in a non-ObjC literal.
1267  if (!IsObjCLiteral && CS.isObjCArg()) {
1268    return HandleInvalidConversionSpecifier(FS, startSpecifier, specifierLen);
1269  }
1270
1271  // Are we using '%n'?  Issue a warning about this being
1272  // a possible security issue.
1273  if (CS.getKind() == ConversionSpecifier::OutIntPtrArg) {
1274    S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1275      << getFormatSpecifierRange(startSpecifier, specifierLen);
1276    // Continue checking the other format specifiers.
1277    return true;
1278  }
1279
1280  if (CS.getKind() == ConversionSpecifier::VoidPtrArg) {
1281    if (FS.getPrecision().getHowSpecified() != OptionalAmount::NotSpecified)
1282      S.Diag(getLocationOfByte(CS.getStart()),
1283             diag::warn_printf_nonsensical_precision)
1284        << CS.getCharacters()
1285        << getFormatSpecifierRange(startSpecifier, specifierLen);
1286  }
1287  if (CS.getKind() == ConversionSpecifier::VoidPtrArg ||
1288      CS.getKind() == ConversionSpecifier::CStrArg) {
1289    // FIXME: Instead of using "0", "+", etc., eventually get them from
1290    // the FormatSpecifier.
1291    if (FS.hasLeadingZeros())
1292      HandleFlags(FS, "0", CS.getCharacters(), startSpecifier, specifierLen);
1293    if (FS.hasPlusPrefix())
1294      HandleFlags(FS, "+", CS.getCharacters(), startSpecifier, specifierLen);
1295    if (FS.hasSpacePrefix())
1296      HandleFlags(FS, " ", CS.getCharacters(), startSpecifier, specifierLen);
1297  }
1298
1299  // The remaining checks depend on the data arguments.
1300  if (HasVAListArg)
1301    return true;
1302
1303  if (argIndex >= NumDataArgs) {
1304    if (FS.usesPositionalArg())  {
1305      S.Diag(getLocationOfByte(CS.getStart()),
1306             diag::warn_printf_positional_arg_exceeds_data_args)
1307        << (argIndex+1) << NumDataArgs
1308        << getFormatSpecifierRange(startSpecifier, specifierLen);
1309    }
1310    else {
1311      S.Diag(getLocationOfByte(CS.getStart()),
1312             diag::warn_printf_insufficient_data_args)
1313        << getFormatSpecifierRange(startSpecifier, specifierLen);
1314    }
1315
1316    // Don't do any more checking.
1317    return false;
1318  }
1319
1320  // Now type check the data expression that matches the
1321  // format specifier.
1322  const Expr *Ex = getDataArg(argIndex);
1323  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1324  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1325    // Check if we didn't match because of an implicit cast from a 'char'
1326    // or 'short' to an 'int'.  This is done because printf is a varargs
1327    // function.
1328    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1329      if (ICE->getType() == S.Context.IntTy)
1330        if (ATR.matchesType(S.Context, ICE->getSubExpr()->getType()))
1331          return true;
1332
1333    S.Diag(getLocationOfByte(CS.getStart()),
1334           diag::warn_printf_conversion_argument_type_mismatch)
1335      << ATR.getRepresentativeType(S.Context) << Ex->getType()
1336      << getFormatSpecifierRange(startSpecifier, specifierLen)
1337      << Ex->getSourceRange();
1338  }
1339
1340  return true;
1341}
1342
1343void CheckPrintfHandler::DoneProcessing() {
1344  // Does the number of data arguments exceed the number of
1345  // format conversions in the format string?
1346  if (!HasVAListArg) {
1347    // Find any arguments that weren't covered.
1348    CoveredArgs.flip();
1349    signed notCoveredArg = CoveredArgs.find_first();
1350    if (notCoveredArg >= 0) {
1351      assert((unsigned)notCoveredArg < NumDataArgs);
1352      S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1353             diag::warn_printf_data_arg_not_used)
1354        << getFormatStringRange();
1355    }
1356  }
1357}
1358
1359void Sema::CheckPrintfString(const StringLiteral *FExpr,
1360                             const Expr *OrigFormatExpr,
1361                             const CallExpr *TheCall, bool HasVAListArg,
1362                             unsigned format_idx, unsigned firstDataArg) {
1363
1364  // CHECK: is the format string a wide literal?
1365  if (FExpr->isWide()) {
1366    Diag(FExpr->getLocStart(),
1367         diag::warn_printf_format_string_is_wide_literal)
1368    << OrigFormatExpr->getSourceRange();
1369    return;
1370  }
1371
1372  // Str - The format string.  NOTE: this is NOT null-terminated!
1373  const char *Str = FExpr->getStrData();
1374
1375  // CHECK: empty format string?
1376  unsigned StrLen = FExpr->getByteLength();
1377
1378  if (StrLen == 0) {
1379    Diag(FExpr->getLocStart(), diag::warn_printf_empty_format_string)
1380    << OrigFormatExpr->getSourceRange();
1381    return;
1382  }
1383
1384  CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1385                       TheCall->getNumArgs() - firstDataArg,
1386                       isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1387                       HasVAListArg, TheCall, format_idx);
1388
1389  if (!analyze_printf::ParseFormatString(H, Str, Str + StrLen))
1390    H.DoneProcessing();
1391}
1392
1393//===--- CHECK: Return Address of Stack Variable --------------------------===//
1394
1395static DeclRefExpr* EvalVal(Expr *E);
1396static DeclRefExpr* EvalAddr(Expr* E);
1397
1398/// CheckReturnStackAddr - Check if a return statement returns the address
1399///   of a stack variable.
1400void
1401Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1402                           SourceLocation ReturnLoc) {
1403
1404  // Perform checking for returned stack addresses.
1405  if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
1406    if (DeclRefExpr *DR = EvalAddr(RetValExp))
1407      Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
1408       << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1409
1410    // Skip over implicit cast expressions when checking for block expressions.
1411    RetValExp = RetValExp->IgnoreParenCasts();
1412
1413    if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
1414      if (C->hasBlockDeclRefExprs())
1415        Diag(C->getLocStart(), diag::err_ret_local_block)
1416          << C->getSourceRange();
1417
1418    if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1419      Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1420        << ALE->getSourceRange();
1421
1422  } else if (lhsType->isReferenceType()) {
1423    // Perform checking for stack values returned by reference.
1424    // Check for a reference to the stack
1425    if (DeclRefExpr *DR = EvalVal(RetValExp))
1426      Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
1427        << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
1428  }
1429}
1430
1431/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1432///  check if the expression in a return statement evaluates to an address
1433///  to a location on the stack.  The recursion is used to traverse the
1434///  AST of the return expression, with recursion backtracking when we
1435///  encounter a subexpression that (1) clearly does not lead to the address
1436///  of a stack variable or (2) is something we cannot determine leads to
1437///  the address of a stack variable based on such local checking.
1438///
1439///  EvalAddr processes expressions that are pointers that are used as
1440///  references (and not L-values).  EvalVal handles all other values.
1441///  At the base case of the recursion is a check for a DeclRefExpr* in
1442///  the refers to a stack variable.
1443///
1444///  This implementation handles:
1445///
1446///   * pointer-to-pointer casts
1447///   * implicit conversions from array references to pointers
1448///   * taking the address of fields
1449///   * arbitrary interplay between "&" and "*" operators
1450///   * pointer arithmetic from an address of a stack variable
1451///   * taking the address of an array element where the array is on the stack
1452static DeclRefExpr* EvalAddr(Expr *E) {
1453  // We should only be called for evaluating pointer expressions.
1454  assert((E->getType()->isAnyPointerType() ||
1455          E->getType()->isBlockPointerType() ||
1456          E->getType()->isObjCQualifiedIdType()) &&
1457         "EvalAddr only works on pointers");
1458
1459  // Our "symbolic interpreter" is just a dispatch off the currently
1460  // viewed AST node.  We then recursively traverse the AST by calling
1461  // EvalAddr and EvalVal appropriately.
1462  switch (E->getStmtClass()) {
1463  case Stmt::ParenExprClass:
1464    // Ignore parentheses.
1465    return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
1466
1467  case Stmt::UnaryOperatorClass: {
1468    // The only unary operator that make sense to handle here
1469    // is AddrOf.  All others don't make sense as pointers.
1470    UnaryOperator *U = cast<UnaryOperator>(E);
1471
1472    if (U->getOpcode() == UnaryOperator::AddrOf)
1473      return EvalVal(U->getSubExpr());
1474    else
1475      return NULL;
1476  }
1477
1478  case Stmt::BinaryOperatorClass: {
1479    // Handle pointer arithmetic.  All other binary operators are not valid
1480    // in this context.
1481    BinaryOperator *B = cast<BinaryOperator>(E);
1482    BinaryOperator::Opcode op = B->getOpcode();
1483
1484    if (op != BinaryOperator::Add && op != BinaryOperator::Sub)
1485      return NULL;
1486
1487    Expr *Base = B->getLHS();
1488
1489    // Determine which argument is the real pointer base.  It could be
1490    // the RHS argument instead of the LHS.
1491    if (!Base->getType()->isPointerType()) Base = B->getRHS();
1492
1493    assert (Base->getType()->isPointerType());
1494    return EvalAddr(Base);
1495  }
1496
1497  // For conditional operators we need to see if either the LHS or RHS are
1498  // valid DeclRefExpr*s.  If one of them is valid, we return it.
1499  case Stmt::ConditionalOperatorClass: {
1500    ConditionalOperator *C = cast<ConditionalOperator>(E);
1501
1502    // Handle the GNU extension for missing LHS.
1503    if (Expr *lhsExpr = C->getLHS())
1504      if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1505        return LHS;
1506
1507     return EvalAddr(C->getRHS());
1508  }
1509
1510  // For casts, we need to handle conversions from arrays to
1511  // pointer values, and pointer-to-pointer conversions.
1512  case Stmt::ImplicitCastExprClass:
1513  case Stmt::CStyleCastExprClass:
1514  case Stmt::CXXFunctionalCastExprClass: {
1515    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1516    QualType T = SubExpr->getType();
1517
1518    if (SubExpr->getType()->isPointerType() ||
1519        SubExpr->getType()->isBlockPointerType() ||
1520        SubExpr->getType()->isObjCQualifiedIdType())
1521      return EvalAddr(SubExpr);
1522    else if (T->isArrayType())
1523      return EvalVal(SubExpr);
1524    else
1525      return 0;
1526  }
1527
1528  // C++ casts.  For dynamic casts, static casts, and const casts, we
1529  // are always converting from a pointer-to-pointer, so we just blow
1530  // through the cast.  In the case the dynamic cast doesn't fail (and
1531  // return NULL), we take the conservative route and report cases
1532  // where we return the address of a stack variable.  For Reinterpre
1533  // FIXME: The comment about is wrong; we're not always converting
1534  // from pointer to pointer. I'm guessing that this code should also
1535  // handle references to objects.
1536  case Stmt::CXXStaticCastExprClass:
1537  case Stmt::CXXDynamicCastExprClass:
1538  case Stmt::CXXConstCastExprClass:
1539  case Stmt::CXXReinterpretCastExprClass: {
1540      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
1541      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
1542        return EvalAddr(S);
1543      else
1544        return NULL;
1545  }
1546
1547  // Everything else: we simply don't reason about them.
1548  default:
1549    return NULL;
1550  }
1551}
1552
1553
1554///  EvalVal - This function is complements EvalAddr in the mutual recursion.
1555///   See the comments for EvalAddr for more details.
1556static DeclRefExpr* EvalVal(Expr *E) {
1557
1558  // We should only be called for evaluating non-pointer expressions, or
1559  // expressions with a pointer type that are not used as references but instead
1560  // are l-values (e.g., DeclRefExpr with a pointer type).
1561
1562  // Our "symbolic interpreter" is just a dispatch off the currently
1563  // viewed AST node.  We then recursively traverse the AST by calling
1564  // EvalAddr and EvalVal appropriately.
1565  switch (E->getStmtClass()) {
1566  case Stmt::DeclRefExprClass: {
1567    // DeclRefExpr: the base case.  When we hit a DeclRefExpr we are looking
1568    //  at code that refers to a variable's name.  We check if it has local
1569    //  storage within the function, and if so, return the expression.
1570    DeclRefExpr *DR = cast<DeclRefExpr>(E);
1571
1572    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1573      if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1574
1575    return NULL;
1576  }
1577
1578  case Stmt::ParenExprClass:
1579    // Ignore parentheses.
1580    return EvalVal(cast<ParenExpr>(E)->getSubExpr());
1581
1582  case Stmt::UnaryOperatorClass: {
1583    // The only unary operator that make sense to handle here
1584    // is Deref.  All others don't resolve to a "name."  This includes
1585    // handling all sorts of rvalues passed to a unary operator.
1586    UnaryOperator *U = cast<UnaryOperator>(E);
1587
1588    if (U->getOpcode() == UnaryOperator::Deref)
1589      return EvalAddr(U->getSubExpr());
1590
1591    return NULL;
1592  }
1593
1594  case Stmt::ArraySubscriptExprClass: {
1595    // Array subscripts are potential references to data on the stack.  We
1596    // retrieve the DeclRefExpr* for the array variable if it indeed
1597    // has local storage.
1598    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
1599  }
1600
1601  case Stmt::ConditionalOperatorClass: {
1602    // For conditional operators we need to see if either the LHS or RHS are
1603    // non-NULL DeclRefExpr's.  If one is non-NULL, we return it.
1604    ConditionalOperator *C = cast<ConditionalOperator>(E);
1605
1606    // Handle the GNU extension for missing LHS.
1607    if (Expr *lhsExpr = C->getLHS())
1608      if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1609        return LHS;
1610
1611    return EvalVal(C->getRHS());
1612  }
1613
1614  // Accesses to members are potential references to data on the stack.
1615  case Stmt::MemberExprClass: {
1616    MemberExpr *M = cast<MemberExpr>(E);
1617
1618    // Check for indirect access.  We only want direct field accesses.
1619    if (!M->isArrow())
1620      return EvalVal(M->getBase());
1621    else
1622      return NULL;
1623  }
1624
1625  // Everything else: we simply don't reason about them.
1626  default:
1627    return NULL;
1628  }
1629}
1630
1631//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
1632
1633/// Check for comparisons of floating point operands using != and ==.
1634/// Issue a warning if these are no self-comparisons, as they are not likely
1635/// to do what the programmer intended.
1636void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
1637  bool EmitWarning = true;
1638
1639  Expr* LeftExprSansParen = lex->IgnoreParens();
1640  Expr* RightExprSansParen = rex->IgnoreParens();
1641
1642  // Special case: check for x == x (which is OK).
1643  // Do not emit warnings for such cases.
1644  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
1645    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
1646      if (DRL->getDecl() == DRR->getDecl())
1647        EmitWarning = false;
1648
1649
1650  // Special case: check for comparisons against literals that can be exactly
1651  //  represented by APFloat.  In such cases, do not emit a warning.  This
1652  //  is a heuristic: often comparison against such literals are used to
1653  //  detect if a value in a variable has not changed.  This clearly can
1654  //  lead to false negatives.
1655  if (EmitWarning) {
1656    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
1657      if (FLL->isExact())
1658        EmitWarning = false;
1659    } else
1660      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
1661        if (FLR->isExact())
1662          EmitWarning = false;
1663    }
1664  }
1665
1666  // Check for comparisons with builtin types.
1667  if (EmitWarning)
1668    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
1669      if (CL->isBuiltinCall(Context))
1670        EmitWarning = false;
1671
1672  if (EmitWarning)
1673    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
1674      if (CR->isBuiltinCall(Context))
1675        EmitWarning = false;
1676
1677  // Emit the diagnostic.
1678  if (EmitWarning)
1679    Diag(loc, diag::warn_floatingpoint_eq)
1680      << lex->getSourceRange() << rex->getSourceRange();
1681}
1682
1683//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
1684//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
1685
1686namespace {
1687
1688/// Structure recording the 'active' range of an integer-valued
1689/// expression.
1690struct IntRange {
1691  /// The number of bits active in the int.
1692  unsigned Width;
1693
1694  /// True if the int is known not to have negative values.
1695  bool NonNegative;
1696
1697  IntRange() {}
1698  IntRange(unsigned Width, bool NonNegative)
1699    : Width(Width), NonNegative(NonNegative)
1700  {}
1701
1702  // Returns the range of the bool type.
1703  static IntRange forBoolType() {
1704    return IntRange(1, true);
1705  }
1706
1707  // Returns the range of an integral type.
1708  static IntRange forType(ASTContext &C, QualType T) {
1709    return forCanonicalType(C, T->getCanonicalTypeInternal().getTypePtr());
1710  }
1711
1712  // Returns the range of an integeral type based on its canonical
1713  // representation.
1714  static IntRange forCanonicalType(ASTContext &C, const Type *T) {
1715    assert(T->isCanonicalUnqualified());
1716
1717    if (const VectorType *VT = dyn_cast<VectorType>(T))
1718      T = VT->getElementType().getTypePtr();
1719    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
1720      T = CT->getElementType().getTypePtr();
1721    if (const EnumType *ET = dyn_cast<EnumType>(T))
1722      T = ET->getDecl()->getIntegerType().getTypePtr();
1723
1724    const BuiltinType *BT = cast<BuiltinType>(T);
1725    assert(BT->isInteger());
1726
1727    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
1728  }
1729
1730  // Returns the supremum of two ranges: i.e. their conservative merge.
1731  static IntRange join(IntRange L, IntRange R) {
1732    return IntRange(std::max(L.Width, R.Width),
1733                    L.NonNegative && R.NonNegative);
1734  }
1735
1736  // Returns the infinum of two ranges: i.e. their aggressive merge.
1737  static IntRange meet(IntRange L, IntRange R) {
1738    return IntRange(std::min(L.Width, R.Width),
1739                    L.NonNegative || R.NonNegative);
1740  }
1741};
1742
1743IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
1744  if (value.isSigned() && value.isNegative())
1745    return IntRange(value.getMinSignedBits(), false);
1746
1747  if (value.getBitWidth() > MaxWidth)
1748    value.trunc(MaxWidth);
1749
1750  // isNonNegative() just checks the sign bit without considering
1751  // signedness.
1752  return IntRange(value.getActiveBits(), true);
1753}
1754
1755IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
1756                       unsigned MaxWidth) {
1757  if (result.isInt())
1758    return GetValueRange(C, result.getInt(), MaxWidth);
1759
1760  if (result.isVector()) {
1761    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
1762    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
1763      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
1764      R = IntRange::join(R, El);
1765    }
1766    return R;
1767  }
1768
1769  if (result.isComplexInt()) {
1770    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
1771    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
1772    return IntRange::join(R, I);
1773  }
1774
1775  // This can happen with lossless casts to intptr_t of "based" lvalues.
1776  // Assume it might use arbitrary bits.
1777  // FIXME: The only reason we need to pass the type in here is to get
1778  // the sign right on this one case.  It would be nice if APValue
1779  // preserved this.
1780  assert(result.isLValue());
1781  return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
1782}
1783
1784/// Pseudo-evaluate the given integer expression, estimating the
1785/// range of values it might take.
1786///
1787/// \param MaxWidth - the width to which the value will be truncated
1788IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
1789  E = E->IgnoreParens();
1790
1791  // Try a full evaluation first.
1792  Expr::EvalResult result;
1793  if (E->Evaluate(result, C))
1794    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
1795
1796  // I think we only want to look through implicit casts here; if the
1797  // user has an explicit widening cast, we should treat the value as
1798  // being of the new, wider type.
1799  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
1800    if (CE->getCastKind() == CastExpr::CK_NoOp)
1801      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
1802
1803    IntRange OutputTypeRange = IntRange::forType(C, CE->getType());
1804
1805    bool isIntegerCast = (CE->getCastKind() == CastExpr::CK_IntegralCast);
1806    if (!isIntegerCast && CE->getCastKind() == CastExpr::CK_Unknown)
1807      isIntegerCast = CE->getSubExpr()->getType()->isIntegerType();
1808
1809    // Assume that non-integer casts can span the full range of the type.
1810    if (!isIntegerCast)
1811      return OutputTypeRange;
1812
1813    IntRange SubRange
1814      = GetExprRange(C, CE->getSubExpr(),
1815                     std::min(MaxWidth, OutputTypeRange.Width));
1816
1817    // Bail out if the subexpr's range is as wide as the cast type.
1818    if (SubRange.Width >= OutputTypeRange.Width)
1819      return OutputTypeRange;
1820
1821    // Otherwise, we take the smaller width, and we're non-negative if
1822    // either the output type or the subexpr is.
1823    return IntRange(SubRange.Width,
1824                    SubRange.NonNegative || OutputTypeRange.NonNegative);
1825  }
1826
1827  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
1828    // If we can fold the condition, just take that operand.
1829    bool CondResult;
1830    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
1831      return GetExprRange(C, CondResult ? CO->getTrueExpr()
1832                                        : CO->getFalseExpr(),
1833                          MaxWidth);
1834
1835    // Otherwise, conservatively merge.
1836    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
1837    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
1838    return IntRange::join(L, R);
1839  }
1840
1841  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
1842    switch (BO->getOpcode()) {
1843
1844    // Boolean-valued operations are single-bit and positive.
1845    case BinaryOperator::LAnd:
1846    case BinaryOperator::LOr:
1847    case BinaryOperator::LT:
1848    case BinaryOperator::GT:
1849    case BinaryOperator::LE:
1850    case BinaryOperator::GE:
1851    case BinaryOperator::EQ:
1852    case BinaryOperator::NE:
1853      return IntRange::forBoolType();
1854
1855    // The type of these compound assignments is the type of the LHS,
1856    // so the RHS is not necessarily an integer.
1857    case BinaryOperator::MulAssign:
1858    case BinaryOperator::DivAssign:
1859    case BinaryOperator::RemAssign:
1860    case BinaryOperator::AddAssign:
1861    case BinaryOperator::SubAssign:
1862      return IntRange::forType(C, E->getType());
1863
1864    // Operations with opaque sources are black-listed.
1865    case BinaryOperator::PtrMemD:
1866    case BinaryOperator::PtrMemI:
1867      return IntRange::forType(C, E->getType());
1868
1869    // Bitwise-and uses the *infinum* of the two source ranges.
1870    case BinaryOperator::And:
1871    case BinaryOperator::AndAssign:
1872      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
1873                            GetExprRange(C, BO->getRHS(), MaxWidth));
1874
1875    // Left shift gets black-listed based on a judgement call.
1876    case BinaryOperator::Shl:
1877      // ...except that we want to treat '1 << (blah)' as logically
1878      // positive.  It's an important idiom.
1879      if (IntegerLiteral *I
1880            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
1881        if (I->getValue() == 1) {
1882          IntRange R = IntRange::forType(C, E->getType());
1883          return IntRange(R.Width, /*NonNegative*/ true);
1884        }
1885      }
1886      // fallthrough
1887
1888    case BinaryOperator::ShlAssign:
1889      return IntRange::forType(C, E->getType());
1890
1891    // Right shift by a constant can narrow its left argument.
1892    case BinaryOperator::Shr:
1893    case BinaryOperator::ShrAssign: {
1894      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1895
1896      // If the shift amount is a positive constant, drop the width by
1897      // that much.
1898      llvm::APSInt shift;
1899      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
1900          shift.isNonNegative()) {
1901        unsigned zext = shift.getZExtValue();
1902        if (zext >= L.Width)
1903          L.Width = (L.NonNegative ? 0 : 1);
1904        else
1905          L.Width -= zext;
1906      }
1907
1908      return L;
1909    }
1910
1911    // Comma acts as its right operand.
1912    case BinaryOperator::Comma:
1913      return GetExprRange(C, BO->getRHS(), MaxWidth);
1914
1915    // Black-list pointer subtractions.
1916    case BinaryOperator::Sub:
1917      if (BO->getLHS()->getType()->isPointerType())
1918        return IntRange::forType(C, E->getType());
1919      // fallthrough
1920
1921    default:
1922      break;
1923    }
1924
1925    // Treat every other operator as if it were closed on the
1926    // narrowest type that encompasses both operands.
1927    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
1928    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
1929    return IntRange::join(L, R);
1930  }
1931
1932  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1933    switch (UO->getOpcode()) {
1934    // Boolean-valued operations are white-listed.
1935    case UnaryOperator::LNot:
1936      return IntRange::forBoolType();
1937
1938    // Operations with opaque sources are black-listed.
1939    case UnaryOperator::Deref:
1940    case UnaryOperator::AddrOf: // should be impossible
1941    case UnaryOperator::OffsetOf:
1942      return IntRange::forType(C, E->getType());
1943
1944    default:
1945      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
1946    }
1947  }
1948
1949  if (dyn_cast<OffsetOfExpr>(E)) {
1950    IntRange::forType(C, E->getType());
1951  }
1952
1953  FieldDecl *BitField = E->getBitField();
1954  if (BitField) {
1955    llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
1956    unsigned BitWidth = BitWidthAP.getZExtValue();
1957
1958    return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
1959  }
1960
1961  return IntRange::forType(C, E->getType());
1962}
1963
1964/// Checks whether the given value, which currently has the given
1965/// source semantics, has the same value when coerced through the
1966/// target semantics.
1967bool IsSameFloatAfterCast(const llvm::APFloat &value,
1968                          const llvm::fltSemantics &Src,
1969                          const llvm::fltSemantics &Tgt) {
1970  llvm::APFloat truncated = value;
1971
1972  bool ignored;
1973  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
1974  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
1975
1976  return truncated.bitwiseIsEqual(value);
1977}
1978
1979/// Checks whether the given value, which currently has the given
1980/// source semantics, has the same value when coerced through the
1981/// target semantics.
1982///
1983/// The value might be a vector of floats (or a complex number).
1984bool IsSameFloatAfterCast(const APValue &value,
1985                          const llvm::fltSemantics &Src,
1986                          const llvm::fltSemantics &Tgt) {
1987  if (value.isFloat())
1988    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
1989
1990  if (value.isVector()) {
1991    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
1992      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
1993        return false;
1994    return true;
1995  }
1996
1997  assert(value.isComplexFloat());
1998  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
1999          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2000}
2001
2002} // end anonymous namespace
2003
2004/// \brief Implements -Wsign-compare.
2005///
2006/// \param lex the left-hand expression
2007/// \param rex the right-hand expression
2008/// \param OpLoc the location of the joining operator
2009/// \param BinOpc binary opcode or 0
2010void Sema::CheckSignCompare(Expr *lex, Expr *rex, SourceLocation OpLoc,
2011                            const BinaryOperator::Opcode* BinOpc) {
2012  // Don't warn if we're in an unevaluated context.
2013  if (ExprEvalContexts.back().Context == Unevaluated)
2014    return;
2015
2016  // If either expression is value-dependent, don't warn. We'll get another
2017  // chance at instantiation time.
2018  if (lex->isValueDependent() || rex->isValueDependent())
2019    return;
2020
2021  QualType lt = lex->getType(), rt = rex->getType();
2022
2023  // Only warn if both operands are integral.
2024  if (!lt->isIntegerType() || !rt->isIntegerType())
2025    return;
2026
2027  // In C, the width of a bitfield determines its type, and the
2028  // declared type only contributes the signedness.  This duplicates
2029  // the work that will later be done by UsualUnaryConversions.
2030  // Eventually, this check will be reorganized in a way that avoids
2031  // this duplication.
2032  if (!getLangOptions().CPlusPlus) {
2033    QualType tmp;
2034    tmp = Context.isPromotableBitField(lex);
2035    if (!tmp.isNull()) lt = tmp;
2036    tmp = Context.isPromotableBitField(rex);
2037    if (!tmp.isNull()) rt = tmp;
2038  }
2039
2040  if (const EnumType *E = lt->getAs<EnumType>())
2041    lt = E->getDecl()->getPromotionType();
2042  if (const EnumType *E = rt->getAs<EnumType>())
2043    rt = E->getDecl()->getPromotionType();
2044
2045  // The rule is that the signed operand becomes unsigned, so isolate the
2046  // signed operand.
2047  Expr *signedOperand = lex, *unsignedOperand = rex;
2048  QualType signedType = lt, unsignedType = rt;
2049  if (lt->isSignedIntegerType()) {
2050    if (rt->isSignedIntegerType()) return;
2051  } else {
2052    if (!rt->isSignedIntegerType()) return;
2053    std::swap(signedOperand, unsignedOperand);
2054    std::swap(signedType, unsignedType);
2055  }
2056
2057  unsigned unsignedWidth = Context.getIntWidth(unsignedType);
2058  unsigned signedWidth = Context.getIntWidth(signedType);
2059
2060  // If the unsigned type is strictly smaller than the signed type,
2061  // then (1) the result type will be signed and (2) the unsigned
2062  // value will fit fully within the signed type, and thus the result
2063  // of the comparison will be exact.
2064  if (signedWidth > unsignedWidth)
2065    return;
2066
2067  // Otherwise, calculate the effective ranges.
2068  IntRange signedRange = GetExprRange(Context, signedOperand, signedWidth);
2069  IntRange unsignedRange = GetExprRange(Context, unsignedOperand, unsignedWidth);
2070
2071  // We should never be unable to prove that the unsigned operand is
2072  // non-negative.
2073  assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2074
2075  // If the signed operand is non-negative, then the signed->unsigned
2076  // conversion won't change it.
2077  if (signedRange.NonNegative) {
2078    // Emit warnings for comparisons of unsigned to integer constant 0.
2079    //   always false: x < 0  (or 0 > x)
2080    //   always true:  x >= 0 (or 0 <= x)
2081    llvm::APSInt X;
2082    if (BinOpc && signedOperand->isIntegerConstantExpr(X, Context) && X == 0) {
2083      if (signedOperand != lex) {
2084        if (*BinOpc == BinaryOperator::LT) {
2085          Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2086            << "< 0" << "false"
2087            << lex->getSourceRange() << rex->getSourceRange();
2088        }
2089        else if (*BinOpc == BinaryOperator::GE) {
2090          Diag(OpLoc, diag::warn_lunsigned_always_true_comparison)
2091            << ">= 0" << "true"
2092            << lex->getSourceRange() << rex->getSourceRange();
2093        }
2094      }
2095      else {
2096        if (*BinOpc == BinaryOperator::GT) {
2097          Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2098            << "0 >" << "false"
2099            << lex->getSourceRange() << rex->getSourceRange();
2100        }
2101        else if (*BinOpc == BinaryOperator::LE) {
2102          Diag(OpLoc, diag::warn_runsigned_always_true_comparison)
2103            << "0 <=" << "true"
2104            << lex->getSourceRange() << rex->getSourceRange();
2105        }
2106      }
2107    }
2108    return;
2109  }
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 (BinOpc &&
2116      (*BinOpc == BinaryOperator::EQ || *BinOpc == BinaryOperator::NE) &&
2117      unsignedRange.Width < unsignedWidth)
2118    return;
2119
2120  Diag(OpLoc, BinOpc ? diag::warn_mixed_sign_comparison
2121                     : diag::warn_mixed_sign_conditional)
2122    << lt << rt << lex->getSourceRange() << rex->getSourceRange();
2123}
2124
2125/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
2126static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, unsigned diag) {
2127  S.Diag(E->getExprLoc(), diag) << E->getType() << T << E->getSourceRange();
2128}
2129
2130/// Implements -Wconversion.
2131void Sema::CheckImplicitConversion(Expr *E, QualType T) {
2132  // Don't diagnose in unevaluated contexts.
2133  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2134    return;
2135
2136  // Don't diagnose for value-dependent expressions.
2137  if (E->isValueDependent())
2138    return;
2139
2140  const Type *Source = Context.getCanonicalType(E->getType()).getTypePtr();
2141  const Type *Target = Context.getCanonicalType(T).getTypePtr();
2142
2143  // Never diagnose implicit casts to bool.
2144  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2145    return;
2146
2147  // Strip vector types.
2148  if (isa<VectorType>(Source)) {
2149    if (!isa<VectorType>(Target))
2150      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_vector_scalar);
2151
2152    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2153    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2154  }
2155
2156  // Strip complex types.
2157  if (isa<ComplexType>(Source)) {
2158    if (!isa<ComplexType>(Target))
2159      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_complex_scalar);
2160
2161    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2162    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2163  }
2164
2165  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2166  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2167
2168  // If the source is floating point...
2169  if (SourceBT && SourceBT->isFloatingPoint()) {
2170    // ...and the target is floating point...
2171    if (TargetBT && TargetBT->isFloatingPoint()) {
2172      // ...then warn if we're dropping FP rank.
2173
2174      // Builtin FP kinds are ordered by increasing FP rank.
2175      if (SourceBT->getKind() > TargetBT->getKind()) {
2176        // Don't warn about float constants that are precisely
2177        // representable in the target type.
2178        Expr::EvalResult result;
2179        if (E->Evaluate(result, Context)) {
2180          // Value might be a float, a float vector, or a float complex.
2181          if (IsSameFloatAfterCast(result.Val,
2182                     Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2183                     Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
2184            return;
2185        }
2186
2187        DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_precision);
2188      }
2189      return;
2190    }
2191
2192    // If the target is integral, always warn.
2193    if ((TargetBT && TargetBT->isInteger()))
2194      // TODO: don't warn for integer values?
2195      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_float_integer);
2196
2197    return;
2198  }
2199
2200  if (!Source->isIntegerType() || !Target->isIntegerType())
2201    return;
2202
2203  IntRange SourceRange = GetExprRange(Context, E, Context.getIntWidth(E->getType()));
2204  IntRange TargetRange = IntRange::forCanonicalType(Context, Target);
2205
2206  // FIXME: also signed<->unsigned?
2207
2208  if (SourceRange.Width > TargetRange.Width) {
2209    // People want to build with -Wshorten-64-to-32 and not -Wconversion
2210    // and by god we'll let them.
2211    if (SourceRange.Width == 64 && TargetRange.Width == 32)
2212      return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_64_32);
2213    return DiagnoseImpCast(*this, E, T, diag::warn_impcast_integer_precision);
2214  }
2215
2216  return;
2217}
2218
2219/// CheckParmsForFunctionDef - Check that the parameters of the given
2220/// function are appropriate for the definition of a function. This
2221/// takes care of any checks that cannot be performed on the
2222/// declaration itself, e.g., that the types of each of the function
2223/// parameters are complete.
2224bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
2225  bool HasInvalidParm = false;
2226  for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2227    ParmVarDecl *Param = FD->getParamDecl(p);
2228
2229    // C99 6.7.5.3p4: the parameters in a parameter type list in a
2230    // function declarator that is part of a function definition of
2231    // that function shall not have incomplete type.
2232    //
2233    // This is also C++ [dcl.fct]p6.
2234    if (!Param->isInvalidDecl() &&
2235        RequireCompleteType(Param->getLocation(), Param->getType(),
2236                               diag::err_typecheck_decl_incomplete_type)) {
2237      Param->setInvalidDecl();
2238      HasInvalidParm = true;
2239    }
2240
2241    // C99 6.9.1p5: If the declarator includes a parameter type list, the
2242    // declaration of each parameter shall include an identifier.
2243    if (Param->getIdentifier() == 0 &&
2244        !Param->isImplicit() &&
2245        !getLangOptions().CPlusPlus)
2246      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
2247
2248    // C99 6.7.5.3p12:
2249    //   If the function declarator is not part of a definition of that
2250    //   function, parameters may have incomplete type and may use the [*]
2251    //   notation in their sequences of declarator specifiers to specify
2252    //   variable length array types.
2253    QualType PType = Param->getOriginalType();
2254    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2255      if (AT->getSizeModifier() == ArrayType::Star) {
2256        // FIXME: This diagnosic should point the the '[*]' if source-location
2257        // information is added for it.
2258        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2259      }
2260    }
2261  }
2262
2263  return HasInvalidParm;
2264}
2265