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