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