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