SemaChecking.cpp revision 92b670e1ee0b11d7e558ec659795ddf452e583ed
105436638acc7c010349a69c3395f1a57c642dc62Ying Wang//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
205436638acc7c010349a69c3395f1a57c642dc62Ying Wang//
305436638acc7c010349a69c3395f1a57c642dc62Ying Wang//                     The LLVM Compiler Infrastructure
405436638acc7c010349a69c3395f1a57c642dc62Ying Wang//
505436638acc7c010349a69c3395f1a57c642dc62Ying Wang// This file is distributed under the University of Illinois Open Source
605436638acc7c010349a69c3395f1a57c642dc62Ying Wang// License. See LICENSE.TXT for details.
705436638acc7c010349a69c3395f1a57c642dc62Ying Wang//
805436638acc7c010349a69c3395f1a57c642dc62Ying Wang//===----------------------------------------------------------------------===//
905436638acc7c010349a69c3395f1a57c642dc62Ying Wang//
1005436638acc7c010349a69c3395f1a57c642dc62Ying Wang//  This file implements extra semantic analysis beyond what is enforced
1105436638acc7c010349a69c3395f1a57c642dc62Ying Wang//  by the C type system.
1205436638acc7c010349a69c3395f1a57c642dc62Ying Wang//
1305436638acc7c010349a69c3395f1a57c642dc62Ying Wang//===----------------------------------------------------------------------===//
1405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
1505436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Sema/Initialization.h"
1605436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Sema/Sema.h"
1705436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Sema/SemaInternal.h"
1805436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Sema/Initialization.h"
1905436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Sema/ScopeInfo.h"
2005436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Analysis/Analyses/FormatString.h"
2105436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/ASTContext.h"
2205436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/CharUnits.h"
2305436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/DeclCXX.h"
2405436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/DeclObjC.h"
2505436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/ExprCXX.h"
2605436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/ExprObjC.h"
2705436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/EvaluatedExprVisitor.h"
2805436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/DeclObjC.h"
2905436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/StmtCXX.h"
3005436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/AST/StmtObjC.h"
3105436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Lex/Preprocessor.h"
3205436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "llvm/ADT/BitVector.h"
3305436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "llvm/ADT/SmallString.h"
3405436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "llvm/ADT/STLExtras.h"
3505436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "llvm/Support/raw_ostream.h"
3605436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Basic/TargetBuiltins.h"
3705436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Basic/TargetInfo.h"
3805436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Basic/ConvertUTF.h"
3905436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include <limits>
4005436638acc7c010349a69c3395f1a57c642dc62Ying Wangusing namespace clang;
4105436638acc7c010349a69c3395f1a57c642dc62Ying Wangusing namespace sema;
4205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
4305436638acc7c010349a69c3395f1a57c642dc62Ying WangSourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
4405436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                                    unsigned ByteNo) const {
4505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
4605436638acc7c010349a69c3395f1a57c642dc62Ying Wang                               PP.getLangOptions(), PP.getTargetInfo());
4705436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
4805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
4905436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// Checks that a call expression's argument count is the desired number.
5005436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// This is useful when doing custom type-checking.  Returns true on error.
5105436638acc7c010349a69c3395f1a57c642dc62Ying Wangstatic bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
5205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned argCount = call->getNumArgs();
5305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (argCount == desiredArgCount) return false;
5405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
5505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (argCount < desiredArgCount)
5605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
5705436638acc7c010349a69c3395f1a57c642dc62Ying Wang        << 0 /*function call*/ << desiredArgCount << argCount
5805436638acc7c010349a69c3395f1a57c642dc62Ying Wang        << call->getSourceRange();
5905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
6005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Highlight all the excess arguments.
6105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
6205436638acc7c010349a69c3395f1a57c642dc62Ying Wang                    call->getArg(argCount - 1)->getLocEnd());
6305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
6405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
6505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    << 0 /*function call*/ << desiredArgCount << argCount
6605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    << call->getArg(1)->getSourceRange();
6705436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
6805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
6905436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
7005436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// annotation is a non wide string literal.
7105436638acc7c010349a69c3395f1a57c642dc62Ying Wangstatic bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
7205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Arg = Arg->IgnoreParenCasts();
7305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
7405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!Literal || !Literal->isAscii()) {
7505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
7605436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << Arg->getSourceRange();
7705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return true;
7805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
7905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
8005436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
8105436638acc7c010349a69c3395f1a57c642dc62Ying Wang
8205436638acc7c010349a69c3395f1a57c642dc62Ying WangExprResult
8305436638acc7c010349a69c3395f1a57c642dc62Ying WangSema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
8405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  ExprResult TheCallResult(Owned(TheCall));
8505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
8605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Find out if any arguments are required to be integer constant expressions.
8705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned ICEArguments = 0;
8805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  ASTContext::GetBuiltinTypeError Error;
8905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
9005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Error != ASTContext::GE_None)
9105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
9205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
9305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // If any arguments are required to be ICE's, check and diagnose.
9405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
9505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // Skip arguments not required to be ICE's.
9605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
9705436638acc7c010349a69c3395f1a57c642dc62Ying Wang
9805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    llvm::APSInt Result;
9905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
10005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return true;
10105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ICEArguments &= ~(1 << ArgNo);
10205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
10305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
10405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (BuiltinID) {
10505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin___CFStringMakeConstantString:
10605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    assert(TheCall->getNumArgs() == 1 &&
10705436638acc7c010349a69c3395f1a57c642dc62Ying Wang           "Wrong # arguments to builtin CFStringMakeConstantString");
10805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (CheckObjCString(TheCall->getArg(0)))
10905436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
11005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
11105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_stdarg_start:
11205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_va_start:
11305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinVAStart(TheCall))
11405436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
11505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
11605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isgreater:
11705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isgreaterequal:
11805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isless:
11905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_islessequal:
12005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_islessgreater:
12105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isunordered:
12205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinUnorderedCompare(TheCall))
12305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
12405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
12505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_fpclassify:
12605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinFPClassification(TheCall, 6))
12705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
12805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
12905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isfinite:
13005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isinf:
13105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isinf_sign:
13205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isnan:
13305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_isnormal:
13405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinFPClassification(TheCall, 1))
13505436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
13605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
13705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_shufflevector:
13805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaBuiltinShuffleVector(TheCall);
13905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // TheCall will be freed by the smart pointer here, but that's fine, since
14005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
14105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_prefetch:
14205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinPrefetch(TheCall))
14305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
14405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
14505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_object_size:
14605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinObjectSize(TheCall))
14705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
14805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
14905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_longjmp:
15005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinLongjmp(TheCall))
15105436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
15205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
15305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
15405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_classify_type:
15505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (checkArgCount(*this, TheCall, 1)) return true;
15605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    TheCall->setType(Context.IntTy);
15705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
15805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_constant_p:
15905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (checkArgCount(*this, TheCall, 1)) return true;
16005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    TheCall->setType(Context.IntTy);
16105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
16205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add:
16305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add_1:
16405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add_2:
16505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add_4:
16605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add_8:
16705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_add_16:
16805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub:
16905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub_1:
17005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub_2:
17105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub_4:
17205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub_8:
17305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_sub_16:
17405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or:
17505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or_1:
17605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or_2:
17705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or_4:
17805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or_8:
17905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_or_16:
18005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and:
18105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and_1:
18205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and_2:
18305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and_4:
18405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and_8:
18505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_and_16:
18605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor:
18705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor_1:
18805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor_2:
18905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor_4:
19005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor_8:
19105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_fetch_and_xor_16:
19205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch:
19305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch_1:
19405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch_2:
19505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch_4:
19605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch_8:
19705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_add_and_fetch_16:
19805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch:
19905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch_1:
20005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch_2:
20105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch_4:
20205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch_8:
20305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_sub_and_fetch_16:
20405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch:
20505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch_1:
20605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch_2:
20705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch_4:
20805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch_8:
20905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_and_and_fetch_16:
21005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch:
21105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch_1:
21205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch_2:
21305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch_4:
21405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch_8:
21505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_or_and_fetch_16:
21605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch:
21705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch_1:
21805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch_2:
21905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch_4:
22005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch_8:
22105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_xor_and_fetch_16:
22205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap:
22305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap_1:
22405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap_2:
22505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap_4:
22605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap_8:
22705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_val_compare_and_swap_16:
22805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap:
22905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap_1:
23005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap_2:
23105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap_4:
23205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap_8:
23305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_bool_compare_and_swap_16:
23405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set:
23505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set_1:
23605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set_2:
23705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set_4:
23805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set_8:
23905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_test_and_set_16:
24005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release:
24105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release_1:
24205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release_2:
24305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release_4:
24405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release_8:
24505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_lock_release_16:
24605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap:
24705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap_1:
24805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap_2:
24905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap_4:
25005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap_8:
25105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__sync_swap_16:
25205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaBuiltinAtomicOverloaded(move(TheCallResult));
25305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_load:
25405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
25505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_store:
25605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
25705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_init:
25805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Init);
25905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_exchange:
26005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
26105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_compare_exchange_strong:
26205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult),
26305436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                   AtomicExpr::CmpXchgStrong);
26405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_compare_exchange_weak:
26505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult),
26605436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                   AtomicExpr::CmpXchgWeak);
26705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_fetch_add:
26805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
26905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_fetch_sub:
27005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
27105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_fetch_and:
27205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
27305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_fetch_or:
27405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
27505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__atomic_fetch_xor:
27605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
27705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Builtin::BI__builtin_annotation:
27805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
27905436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return ExprError();
28005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
28105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
28205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
28305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Since the target specific builtins for each arch overlap, only check those
28405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // of the arch we are compiling for.
28505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (BuiltinID >= Builtin::FirstTSBuiltin) {
28605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    switch (Context.getTargetInfo().getTriple().getArch()) {
28705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      case llvm::Triple::arm:
28805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      case llvm::Triple::thumb:
28905436638acc7c010349a69c3395f1a57c642dc62Ying Wang        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
29005436638acc7c010349a69c3395f1a57c642dc62Ying Wang          return ExprError();
29105436638acc7c010349a69c3395f1a57c642dc62Ying Wang        break;
29205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      default:
29305436638acc7c010349a69c3395f1a57c642dc62Ying Wang        break;
29405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    }
29505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
29605436638acc7c010349a69c3395f1a57c642dc62Ying Wang
29705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return move(TheCallResult);
29805436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
29905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
30005436638acc7c010349a69c3395f1a57c642dc62Ying Wang// Get the valid immediate range for the specified NEON type code.
30105436638acc7c010349a69c3395f1a57c642dc62Ying Wangstatic unsigned RFT(unsigned t, bool shift = false) {
30205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  NeonTypeFlags Type(t);
30305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  int IsQuad = Type.isQuad();
30405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (Type.getEltType()) {
30505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int8:
30605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Poly8:
30705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return shift ? 7 : (8 << IsQuad) - 1;
30805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int16:
30905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Poly16:
31005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return shift ? 15 : (4 << IsQuad) - 1;
31105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int32:
31205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return shift ? 31 : (2 << IsQuad) - 1;
31305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int64:
31405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return shift ? 63 : (1 << IsQuad) - 1;
31505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Float16:
31605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    assert(!shift && "cannot shift float types!");
31705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return (4 << IsQuad) - 1;
31805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Float32:
31905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    assert(!shift && "cannot shift float types!");
32005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return (2 << IsQuad) - 1;
32105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
32205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  llvm_unreachable("Invalid NeonTypeFlag!");
32305436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
32405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
32505436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// getNeonEltType - Return the QualType corresponding to the elements of
32605436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// the vector type specified by the NeonTypeFlags.  This is used to check
32705436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// the pointer arguments for Neon load/store intrinsics.
32805436638acc7c010349a69c3395f1a57c642dc62Ying Wangstatic QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
32905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (Flags.getEltType()) {
33005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int8:
33105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
33205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int16:
33305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
33405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int32:
33505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
33605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Int64:
33705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
33805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Poly8:
33905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Context.SignedCharTy;
34005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Poly16:
34105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Context.ShortTy;
34205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Float16:
34305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Context.UnsignedShortTy;
34405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case NeonTypeFlags::Float32:
34505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Context.FloatTy;
34605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
34705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  llvm_unreachable("Invalid NeonTypeFlag!");
34805436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
34905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
35005436638acc7c010349a69c3395f1a57c642dc62Ying Wangbool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
35105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  llvm::APSInt Result;
35205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
35305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned mask = 0;
35405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned TV = 0;
35505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  int PtrArgNum = -1;
35605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  bool HasConstPtr = false;
35705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (BuiltinID) {
35805436638acc7c010349a69c3395f1a57c642dc62Ying Wang#define GET_NEON_OVERLOAD_CHECK
35905436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Basic/arm_neon.inc"
36005436638acc7c010349a69c3395f1a57c642dc62Ying Wang#undef GET_NEON_OVERLOAD_CHECK
36105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
36205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
36305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // For NEON intrinsics which are overloaded on vector element type, validate
36405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // the immediate which specifies which variant to emit.
36505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned ImmArg = TheCall->getNumArgs()-1;
36605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (mask) {
36705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
36805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return true;
36905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
37005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    TV = Result.getLimitedValue(64);
37105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if ((TV > 63) || (mask & (1 << TV)) == 0)
37205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
37305436638acc7c010349a69c3395f1a57c642dc62Ying Wang        << TheCall->getArg(ImmArg)->getSourceRange();
37405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
37505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
37605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (PtrArgNum >= 0) {
37705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // Check that pointer arguments have the specified type.
37805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Expr *Arg = TheCall->getArg(PtrArgNum);
37905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
38005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      Arg = ICE->getSubExpr();
38105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
38205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    QualType RHSTy = RHS.get()->getType();
38305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
38405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (HasConstPtr)
38505436638acc7c010349a69c3395f1a57c642dc62Ying Wang      EltTy = EltTy.withConst();
38605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    QualType LHSTy = Context.getPointerType(EltTy);
38705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    AssignConvertType ConvTy;
38805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
38905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (RHS.isInvalid())
39005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return true;
39105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
39205436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                 RHS.get(), AA_Assigning))
39305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return true;
39405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
39505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
39605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // For NEON intrinsics which take an immediate value as part of the
39705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // instruction, range check them here.
39805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned i = 0, l = 0, u = 0;
39905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (BuiltinID) {
40005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  default: return false;
40105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
40205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
40305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case ARM::BI__builtin_arm_vcvtr_f:
40405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
40505436638acc7c010349a69c3395f1a57c642dc62Ying Wang#define GET_NEON_IMMEDIATE_CHECK
40605436638acc7c010349a69c3395f1a57c642dc62Ying Wang#include "clang/Basic/arm_neon.inc"
40705436638acc7c010349a69c3395f1a57c642dc62Ying Wang#undef GET_NEON_IMMEDIATE_CHECK
40805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  };
40905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
41005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Check that the immediate argument is actually a constant.
41105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (SemaBuiltinConstantArg(TheCall, i, Result))
41205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return true;
41305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
41405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Range check against the upper/lower values for this isntruction.
41505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned Val = Result.getZExtValue();
41605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Val < l || Val > (u + l))
41705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
41805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << l << u+l << TheCall->getArg(i)->getSourceRange();
41905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
42005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // FIXME: VFP Intrinsics should error if VFP not present.
42105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
42205436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
42305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
42405436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// CheckFunctionCall - Check a direct function call for various correctness
42505436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// and safety properties not strictly enforced by the C type system.
42605436638acc7c010349a69c3395f1a57c642dc62Ying Wangbool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
42705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Get the IdentifierInfo* for the called function.
42805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  IdentifierInfo *FnInfo = FDecl->getIdentifier();
42905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
43005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // None of the checks below are needed for functions that don't have
43105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // simple names (e.g., C++ conversion functions).
43205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!FnInfo)
43305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return false;
43405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
43505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // FIXME: This mechanism should be abstracted to be less fragile and
43605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // more efficient. For example, just map function ids to custom
43705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // handlers.
43805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
43905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Printf and scanf checking.
44005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (specific_attr_iterator<FormatAttr>
44105436638acc7c010349a69c3395f1a57c642dc62Ying Wang         i = FDecl->specific_attr_begin<FormatAttr>(),
44205436638acc7c010349a69c3395f1a57c642dc62Ying Wang         e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
44305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckFormatArguments(*i, TheCall);
44405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
44505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
44605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (specific_attr_iterator<NonNullAttr>
44705436638acc7c010349a69c3395f1a57c642dc62Ying Wang         i = FDecl->specific_attr_begin<NonNullAttr>(),
44805436638acc7c010349a69c3395f1a57c642dc62Ying Wang         e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
44905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckNonNullArguments(*i, TheCall->getArgs(),
45005436638acc7c010349a69c3395f1a57c642dc62Ying Wang                          TheCall->getCallee()->getLocStart());
45105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
45205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
45305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned CMId = FDecl->getMemoryFunctionKind();
45405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (CMId == 0)
45505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return false;
45605436638acc7c010349a69c3395f1a57c642dc62Ying Wang
45705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Handle memory setting and copying functions.
45805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
45905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckStrlcpycatArguments(TheCall, FnInfo);
46005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  else if (CMId == Builtin::BIstrncat)
46105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckStrncatArguments(TheCall, FnInfo);
46205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  else
46305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckMemaccessArguments(TheCall, CMId, FnInfo);
46405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
46505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
46605436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
46705436638acc7c010349a69c3395f1a57c642dc62Ying Wang
46805436638acc7c010349a69c3395f1a57c642dc62Ying Wangbool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
46905436638acc7c010349a69c3395f1a57c642dc62Ying Wang                               Expr **Args, unsigned NumArgs) {
47005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (specific_attr_iterator<FormatAttr>
47105436638acc7c010349a69c3395f1a57c642dc62Ying Wang       i = Method->specific_attr_begin<FormatAttr>(),
47205436638acc7c010349a69c3395f1a57c642dc62Ying Wang       e = Method->specific_attr_end<FormatAttr>(); i != e ; ++i) {
47305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
47405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckFormatArguments(*i, Args, NumArgs, false, lbrac,
47505436638acc7c010349a69c3395f1a57c642dc62Ying Wang                         Method->getSourceRange());
47605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
47705436638acc7c010349a69c3395f1a57c642dc62Ying Wang
47805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // diagnose nonnull arguments.
47905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (specific_attr_iterator<NonNullAttr>
48005436638acc7c010349a69c3395f1a57c642dc62Ying Wang       i = Method->specific_attr_begin<NonNullAttr>(),
48105436638acc7c010349a69c3395f1a57c642dc62Ying Wang       e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
48205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckNonNullArguments(*i, Args, lbrac);
48305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
48405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
48505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
48605436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
48705436638acc7c010349a69c3395f1a57c642dc62Ying Wang
48805436638acc7c010349a69c3395f1a57c642dc62Ying Wangbool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
48905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
49005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!V)
49105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return false;
49205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
49305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  QualType Ty = V->getType();
49405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!Ty->isBlockPointerType())
49505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return false;
49605436638acc7c010349a69c3395f1a57c642dc62Ying Wang
49705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // format string checking.
49805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (specific_attr_iterator<FormatAttr>
49905436638acc7c010349a69c3395f1a57c642dc62Ying Wang       i = NDecl->specific_attr_begin<FormatAttr>(),
50005436638acc7c010349a69c3395f1a57c642dc62Ying Wang       e = NDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
50105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    CheckFormatArguments(*i, TheCall);
50205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
50305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
50405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
50505436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
50605436638acc7c010349a69c3395f1a57c642dc62Ying Wang
50705436638acc7c010349a69c3395f1a57c642dc62Ying WangExprResult
50805436638acc7c010349a69c3395f1a57c642dc62Ying WangSema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
50905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
51005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
51105436638acc7c010349a69c3395f1a57c642dc62Ying Wang
51205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // All these operations take one of the following four forms:
51305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // T   __atomic_load(_Atomic(T)*, int)                              (loads)
51405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
51505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
51605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  //                                                                (cmpxchg)
51705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
51805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // where T is an appropriate type, and the int paremeterss are for orderings.
51905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned NumVals = 1;
52005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  unsigned NumOrders = 1;
52105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Op == AtomicExpr::Load) {
52205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    NumVals = 0;
52305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
52405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    NumVals = 2;
52505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    NumOrders = 2;
52605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
52705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Op == AtomicExpr::Init)
52805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    NumOrders = 0;
52905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
53005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
53105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
53205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
53305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << TheCall->getCallee()->getSourceRange();
53405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
53505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
53605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
53705436638acc7c010349a69c3395f1a57c642dc62Ying Wang         diag::err_typecheck_call_too_many_args)
53805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
53905436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << TheCall->getCallee()->getSourceRange();
54005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
54105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
54205436638acc7c010349a69c3395f1a57c642dc62Ying Wang
54305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Inspect the first argument of the atomic operation.  This should always be
54405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // a pointer to an _Atomic type.
54505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Expr *Ptr = TheCall->getArg(0);
54605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
54705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
54805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!pointerType) {
54905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
55005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << Ptr->getType() << Ptr->getSourceRange();
55105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
55205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
55305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
55405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  QualType AtomTy = pointerType->getPointeeType();
55505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!AtomTy->isAtomicType()) {
55605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
55705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << Ptr->getType() << Ptr->getSourceRange();
55805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
55905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
56005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
56105436638acc7c010349a69c3395f1a57c642dc62Ying Wang
56205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
56305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      !ValType->isIntegerType() && !ValType->isPointerType()) {
56405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
56505436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << Ptr->getType() << Ptr->getSourceRange();
56605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
56705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
56805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
56905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!ValType->isIntegerType() &&
57005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
57105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
57205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << Ptr->getType() << Ptr->getSourceRange();
57305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
57405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
57505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
57605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (ValType.getObjCLifetime()) {
57705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_None:
57805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_ExplicitNone:
57905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // okay
58005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
58105436638acc7c010349a69c3395f1a57c642dc62Ying Wang
58205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_Weak:
58305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_Strong:
58405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_Autoreleasing:
58505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
58605436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << ValType << Ptr->getSourceRange();
58705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
58805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
58905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
59005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  QualType ResultType = ValType;
59105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Op == AtomicExpr::Store || Op == AtomicExpr::Init)
59205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ResultType = Context.VoidTy;
59305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
59405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ResultType = Context.BoolTy;
59505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
59605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // The first argument --- the pointer --- has a fixed type; we
59705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // deduce the types of the rest of the arguments accordingly.  Walk
59805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // the remaining arguments, converting them to the deduced value type.
59905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
60005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    ExprResult Arg = TheCall->getArg(i);
60105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    QualType Ty;
60205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (i < NumVals+1) {
60305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // The second argument to a cmpxchg is a pointer to the data which will
60405436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // be exchanged. The second argument to a pointer add/subtract is the
60505436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // amount to add/subtract, which must be a ptrdiff_t.  The third
60605436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // argument to a cmpxchg and the second argument in all other cases
60705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // is the type of the value.
60805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
60905436638acc7c010349a69c3395f1a57c642dc62Ying Wang                     Op == AtomicExpr::CmpXchgStrong))
61005436638acc7c010349a69c3395f1a57c642dc62Ying Wang         Ty = Context.getPointerType(ValType.getUnqualifiedType());
61105436638acc7c010349a69c3395f1a57c642dc62Ying Wang      else if (!ValType->isIntegerType() &&
61205436638acc7c010349a69c3395f1a57c642dc62Ying Wang               (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
61305436638acc7c010349a69c3395f1a57c642dc62Ying Wang        Ty = Context.getPointerDiffType();
61405436638acc7c010349a69c3395f1a57c642dc62Ying Wang      else
61505436638acc7c010349a69c3395f1a57c642dc62Ying Wang        Ty = ValType;
61605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    } else {
61705436638acc7c010349a69c3395f1a57c642dc62Ying Wang      // The order(s) are always converted to int.
61805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      Ty = Context.IntTy;
61905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    }
62005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    InitializedEntity Entity =
62105436638acc7c010349a69c3395f1a57c642dc62Ying Wang        InitializedEntity::InitializeParameter(Context, Ty, false);
62205436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
62305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    if (Arg.isInvalid())
62405436638acc7c010349a69c3395f1a57c642dc62Ying Wang      return true;
62505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    TheCall->setArg(i, Arg.get());
62605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
62705436638acc7c010349a69c3395f1a57c642dc62Ying Wang
62805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  SmallVector<Expr*, 5> SubExprs;
62905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  SubExprs.push_back(Ptr);
63005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Op == AtomicExpr::Load) {
63105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(1)); // Order
63205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  } else if (Op == AtomicExpr::Init) {
63305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(1)); // Val1
63405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
63505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(2)); // Order
63605436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(1)); // Val1
63705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  } else {
63805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(3)); // Order
63905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(1)); // Val1
64005436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(2)); // Val2
64105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    SubExprs.push_back(TheCall->getArg(4)); // OrderFail
64205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
64305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
64405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
64505436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                        SubExprs.data(), SubExprs.size(),
64605436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                        ResultType, Op,
64705436638acc7c010349a69c3395f1a57c642dc62Ying Wang                                        TheCall->getRParenLoc()));
64805436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
64905436638acc7c010349a69c3395f1a57c642dc62Ying Wang
65005436638acc7c010349a69c3395f1a57c642dc62Ying Wang
65105436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// checkBuiltinArgument - Given a call to a builtin function, perform
65205436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// normal type-checking on the given argument, updating the call in
65305436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// place.  This is useful when a builtin function requires custom
65405436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// type-checking for some of its arguments but not necessarily all of
65505436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// them.
65605436638acc7c010349a69c3395f1a57c642dc62Ying Wang///
65705436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// Returns true on error.
65805436638acc7c010349a69c3395f1a57c642dc62Ying Wangstatic bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
65905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  FunctionDecl *Fn = E->getDirectCallee();
66005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  assert(Fn && "builtin call without direct callee!");
66105436638acc7c010349a69c3395f1a57c642dc62Ying Wang
66205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
66305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  InitializedEntity Entity =
66405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    InitializedEntity::InitializeParameter(S.Context, Param);
66505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
66605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  ExprResult Arg = E->getArg(0);
66705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
66805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (Arg.isInvalid())
66905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return true;
67005436638acc7c010349a69c3395f1a57c642dc62Ying Wang
67105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  E->setArg(ArgIndex, Arg.take());
67205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  return false;
67305436638acc7c010349a69c3395f1a57c642dc62Ying Wang}
67405436638acc7c010349a69c3395f1a57c642dc62Ying Wang
67505436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// SemaBuiltinAtomicOverloaded - We have a call to a function like
67605436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// __sync_fetch_and_add, which is an overloaded function based on the pointer
67705436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// type of its first argument.  The main ActOnCallExpr routines have already
67805436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// promoted the types of arguments because all of these calls are prototyped as
67905436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// void(...).
68005436638acc7c010349a69c3395f1a57c642dc62Ying Wang///
68105436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// This function goes through and does final semantic checking for these
68205436638acc7c010349a69c3395f1a57c642dc62Ying Wang/// builtins,
68305436638acc7c010349a69c3395f1a57c642dc62Ying WangExprResult
68405436638acc7c010349a69c3395f1a57c642dc62Ying WangSema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
68505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
68605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
68705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
68805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
68905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Ensure that we have at least one argument to do type inference from.
69005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (TheCall->getNumArgs() < 1) {
69105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
69205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << 0 << 1 << TheCall->getNumArgs()
69305436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << TheCall->getCallee()->getSourceRange();
69405436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
69505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
69605436638acc7c010349a69c3395f1a57c642dc62Ying Wang
69705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Inspect the first argument of the atomic builtin.  This should always be
69805436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // a pointer type, whose element is an integral scalar or pointer type.
69905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // Because it is a pointer type, we don't have to worry about any implicit
70005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // casts here.
70105436638acc7c010349a69c3395f1a57c642dc62Ying Wang  // FIXME: We don't allow floating point scalars as input.
70205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  Expr *FirstArg = TheCall->getArg(0);
70305436638acc7c010349a69c3395f1a57c642dc62Ying Wang  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
70405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (FirstArgResult.isInvalid())
70505436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
70605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  FirstArg = FirstArgResult.take();
70705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  TheCall->setArg(0, FirstArg);
70805436638acc7c010349a69c3395f1a57c642dc62Ying Wang
70905436638acc7c010349a69c3395f1a57c642dc62Ying Wang  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
71005436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!pointerType) {
71105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
71205436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << FirstArg->getType() << FirstArg->getSourceRange();
71305436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
71405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
71505436638acc7c010349a69c3395f1a57c642dc62Ying Wang
71605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  QualType ValType = pointerType->getPointeeType();
71705436638acc7c010349a69c3395f1a57c642dc62Ying Wang  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
71805436638acc7c010349a69c3395f1a57c642dc62Ying Wang      !ValType->isBlockPointerType()) {
71905436638acc7c010349a69c3395f1a57c642dc62Ying Wang    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
72005436638acc7c010349a69c3395f1a57c642dc62Ying Wang      << FirstArg->getType() << FirstArg->getSourceRange();
72105436638acc7c010349a69c3395f1a57c642dc62Ying Wang    return ExprError();
72205436638acc7c010349a69c3395f1a57c642dc62Ying Wang  }
72305436638acc7c010349a69c3395f1a57c642dc62Ying Wang
72405436638acc7c010349a69c3395f1a57c642dc62Ying Wang  switch (ValType.getObjCLifetime()) {
72505436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_None:
72605436638acc7c010349a69c3395f1a57c642dc62Ying Wang  case Qualifiers::OCL_ExplicitNone:
72705436638acc7c010349a69c3395f1a57c642dc62Ying Wang    // okay
72805436638acc7c010349a69c3395f1a57c642dc62Ying Wang    break;
729
730  case Qualifiers::OCL_Weak:
731  case Qualifiers::OCL_Strong:
732  case Qualifiers::OCL_Autoreleasing:
733    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
734      << ValType << FirstArg->getSourceRange();
735    return ExprError();
736  }
737
738  // Strip any qualifiers off ValType.
739  ValType = ValType.getUnqualifiedType();
740
741  // The majority of builtins return a value, but a few have special return
742  // types, so allow them to override appropriately below.
743  QualType ResultType = ValType;
744
745  // We need to figure out which concrete builtin this maps onto.  For example,
746  // __sync_fetch_and_add with a 2 byte object turns into
747  // __sync_fetch_and_add_2.
748#define BUILTIN_ROW(x) \
749  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
750    Builtin::BI##x##_8, Builtin::BI##x##_16 }
751
752  static const unsigned BuiltinIndices[][5] = {
753    BUILTIN_ROW(__sync_fetch_and_add),
754    BUILTIN_ROW(__sync_fetch_and_sub),
755    BUILTIN_ROW(__sync_fetch_and_or),
756    BUILTIN_ROW(__sync_fetch_and_and),
757    BUILTIN_ROW(__sync_fetch_and_xor),
758
759    BUILTIN_ROW(__sync_add_and_fetch),
760    BUILTIN_ROW(__sync_sub_and_fetch),
761    BUILTIN_ROW(__sync_and_and_fetch),
762    BUILTIN_ROW(__sync_or_and_fetch),
763    BUILTIN_ROW(__sync_xor_and_fetch),
764
765    BUILTIN_ROW(__sync_val_compare_and_swap),
766    BUILTIN_ROW(__sync_bool_compare_and_swap),
767    BUILTIN_ROW(__sync_lock_test_and_set),
768    BUILTIN_ROW(__sync_lock_release),
769    BUILTIN_ROW(__sync_swap)
770  };
771#undef BUILTIN_ROW
772
773  // Determine the index of the size.
774  unsigned SizeIndex;
775  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
776  case 1: SizeIndex = 0; break;
777  case 2: SizeIndex = 1; break;
778  case 4: SizeIndex = 2; break;
779  case 8: SizeIndex = 3; break;
780  case 16: SizeIndex = 4; break;
781  default:
782    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
783      << FirstArg->getType() << FirstArg->getSourceRange();
784    return ExprError();
785  }
786
787  // Each of these builtins has one pointer argument, followed by some number of
788  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
789  // that we ignore.  Find out which row of BuiltinIndices to read from as well
790  // as the number of fixed args.
791  unsigned BuiltinID = FDecl->getBuiltinID();
792  unsigned BuiltinIndex, NumFixed = 1;
793  switch (BuiltinID) {
794  default: llvm_unreachable("Unknown overloaded atomic builtin!");
795  case Builtin::BI__sync_fetch_and_add:
796  case Builtin::BI__sync_fetch_and_add_1:
797  case Builtin::BI__sync_fetch_and_add_2:
798  case Builtin::BI__sync_fetch_and_add_4:
799  case Builtin::BI__sync_fetch_and_add_8:
800  case Builtin::BI__sync_fetch_and_add_16:
801    BuiltinIndex = 0;
802    break;
803
804  case Builtin::BI__sync_fetch_and_sub:
805  case Builtin::BI__sync_fetch_and_sub_1:
806  case Builtin::BI__sync_fetch_and_sub_2:
807  case Builtin::BI__sync_fetch_and_sub_4:
808  case Builtin::BI__sync_fetch_and_sub_8:
809  case Builtin::BI__sync_fetch_and_sub_16:
810    BuiltinIndex = 1;
811    break;
812
813  case Builtin::BI__sync_fetch_and_or:
814  case Builtin::BI__sync_fetch_and_or_1:
815  case Builtin::BI__sync_fetch_and_or_2:
816  case Builtin::BI__sync_fetch_and_or_4:
817  case Builtin::BI__sync_fetch_and_or_8:
818  case Builtin::BI__sync_fetch_and_or_16:
819    BuiltinIndex = 2;
820    break;
821
822  case Builtin::BI__sync_fetch_and_and:
823  case Builtin::BI__sync_fetch_and_and_1:
824  case Builtin::BI__sync_fetch_and_and_2:
825  case Builtin::BI__sync_fetch_and_and_4:
826  case Builtin::BI__sync_fetch_and_and_8:
827  case Builtin::BI__sync_fetch_and_and_16:
828    BuiltinIndex = 3;
829    break;
830
831  case Builtin::BI__sync_fetch_and_xor:
832  case Builtin::BI__sync_fetch_and_xor_1:
833  case Builtin::BI__sync_fetch_and_xor_2:
834  case Builtin::BI__sync_fetch_and_xor_4:
835  case Builtin::BI__sync_fetch_and_xor_8:
836  case Builtin::BI__sync_fetch_and_xor_16:
837    BuiltinIndex = 4;
838    break;
839
840  case Builtin::BI__sync_add_and_fetch:
841  case Builtin::BI__sync_add_and_fetch_1:
842  case Builtin::BI__sync_add_and_fetch_2:
843  case Builtin::BI__sync_add_and_fetch_4:
844  case Builtin::BI__sync_add_and_fetch_8:
845  case Builtin::BI__sync_add_and_fetch_16:
846    BuiltinIndex = 5;
847    break;
848
849  case Builtin::BI__sync_sub_and_fetch:
850  case Builtin::BI__sync_sub_and_fetch_1:
851  case Builtin::BI__sync_sub_and_fetch_2:
852  case Builtin::BI__sync_sub_and_fetch_4:
853  case Builtin::BI__sync_sub_and_fetch_8:
854  case Builtin::BI__sync_sub_and_fetch_16:
855    BuiltinIndex = 6;
856    break;
857
858  case Builtin::BI__sync_and_and_fetch:
859  case Builtin::BI__sync_and_and_fetch_1:
860  case Builtin::BI__sync_and_and_fetch_2:
861  case Builtin::BI__sync_and_and_fetch_4:
862  case Builtin::BI__sync_and_and_fetch_8:
863  case Builtin::BI__sync_and_and_fetch_16:
864    BuiltinIndex = 7;
865    break;
866
867  case Builtin::BI__sync_or_and_fetch:
868  case Builtin::BI__sync_or_and_fetch_1:
869  case Builtin::BI__sync_or_and_fetch_2:
870  case Builtin::BI__sync_or_and_fetch_4:
871  case Builtin::BI__sync_or_and_fetch_8:
872  case Builtin::BI__sync_or_and_fetch_16:
873    BuiltinIndex = 8;
874    break;
875
876  case Builtin::BI__sync_xor_and_fetch:
877  case Builtin::BI__sync_xor_and_fetch_1:
878  case Builtin::BI__sync_xor_and_fetch_2:
879  case Builtin::BI__sync_xor_and_fetch_4:
880  case Builtin::BI__sync_xor_and_fetch_8:
881  case Builtin::BI__sync_xor_and_fetch_16:
882    BuiltinIndex = 9;
883    break;
884
885  case Builtin::BI__sync_val_compare_and_swap:
886  case Builtin::BI__sync_val_compare_and_swap_1:
887  case Builtin::BI__sync_val_compare_and_swap_2:
888  case Builtin::BI__sync_val_compare_and_swap_4:
889  case Builtin::BI__sync_val_compare_and_swap_8:
890  case Builtin::BI__sync_val_compare_and_swap_16:
891    BuiltinIndex = 10;
892    NumFixed = 2;
893    break;
894
895  case Builtin::BI__sync_bool_compare_and_swap:
896  case Builtin::BI__sync_bool_compare_and_swap_1:
897  case Builtin::BI__sync_bool_compare_and_swap_2:
898  case Builtin::BI__sync_bool_compare_and_swap_4:
899  case Builtin::BI__sync_bool_compare_and_swap_8:
900  case Builtin::BI__sync_bool_compare_and_swap_16:
901    BuiltinIndex = 11;
902    NumFixed = 2;
903    ResultType = Context.BoolTy;
904    break;
905
906  case Builtin::BI__sync_lock_test_and_set:
907  case Builtin::BI__sync_lock_test_and_set_1:
908  case Builtin::BI__sync_lock_test_and_set_2:
909  case Builtin::BI__sync_lock_test_and_set_4:
910  case Builtin::BI__sync_lock_test_and_set_8:
911  case Builtin::BI__sync_lock_test_and_set_16:
912    BuiltinIndex = 12;
913    break;
914
915  case Builtin::BI__sync_lock_release:
916  case Builtin::BI__sync_lock_release_1:
917  case Builtin::BI__sync_lock_release_2:
918  case Builtin::BI__sync_lock_release_4:
919  case Builtin::BI__sync_lock_release_8:
920  case Builtin::BI__sync_lock_release_16:
921    BuiltinIndex = 13;
922    NumFixed = 0;
923    ResultType = Context.VoidTy;
924    break;
925
926  case Builtin::BI__sync_swap:
927  case Builtin::BI__sync_swap_1:
928  case Builtin::BI__sync_swap_2:
929  case Builtin::BI__sync_swap_4:
930  case Builtin::BI__sync_swap_8:
931  case Builtin::BI__sync_swap_16:
932    BuiltinIndex = 14;
933    break;
934  }
935
936  // Now that we know how many fixed arguments we expect, first check that we
937  // have at least that many.
938  if (TheCall->getNumArgs() < 1+NumFixed) {
939    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
940      << 0 << 1+NumFixed << TheCall->getNumArgs()
941      << TheCall->getCallee()->getSourceRange();
942    return ExprError();
943  }
944
945  // Get the decl for the concrete builtin from this, we can tell what the
946  // concrete integer type we should convert to is.
947  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
948  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
949  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
950  FunctionDecl *NewBuiltinDecl =
951    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
952                                           TUScope, false, DRE->getLocStart()));
953
954  // The first argument --- the pointer --- has a fixed type; we
955  // deduce the types of the rest of the arguments accordingly.  Walk
956  // the remaining arguments, converting them to the deduced value type.
957  for (unsigned i = 0; i != NumFixed; ++i) {
958    ExprResult Arg = TheCall->getArg(i+1);
959
960    // GCC does an implicit conversion to the pointer or integer ValType.  This
961    // can fail in some cases (1i -> int**), check for this error case now.
962    // Initialize the argument.
963    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
964                                                   ValType, /*consume*/ false);
965    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
966    if (Arg.isInvalid())
967      return ExprError();
968
969    // Okay, we have something that *can* be converted to the right type.  Check
970    // to see if there is a potentially weird extension going on here.  This can
971    // happen when you do an atomic operation on something like an char* and
972    // pass in 42.  The 42 gets converted to char.  This is even more strange
973    // for things like 45.123 -> char, etc.
974    // FIXME: Do this check.
975    TheCall->setArg(i+1, Arg.take());
976  }
977
978  ASTContext& Context = this->getASTContext();
979
980  // Create a new DeclRefExpr to refer to the new decl.
981  DeclRefExpr* NewDRE = DeclRefExpr::Create(
982      Context,
983      DRE->getQualifierLoc(),
984      SourceLocation(),
985      NewBuiltinDecl,
986      DRE->getLocation(),
987      NewBuiltinDecl->getType(),
988      DRE->getValueKind());
989
990  // Set the callee in the CallExpr.
991  // FIXME: This leaks the original parens and implicit casts.
992  ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
993  if (PromotedCall.isInvalid())
994    return ExprError();
995  TheCall->setCallee(PromotedCall.take());
996
997  // Change the result type of the call to match the original value type. This
998  // is arbitrary, but the codegen for these builtins ins design to handle it
999  // gracefully.
1000  TheCall->setType(ResultType);
1001
1002  return move(TheCallResult);
1003}
1004
1005/// CheckObjCString - Checks that the argument to the builtin
1006/// CFString constructor is correct
1007/// Note: It might also make sense to do the UTF-16 conversion here (would
1008/// simplify the backend).
1009bool Sema::CheckObjCString(Expr *Arg) {
1010  Arg = Arg->IgnoreParenCasts();
1011  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1012
1013  if (!Literal || !Literal->isAscii()) {
1014    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1015      << Arg->getSourceRange();
1016    return true;
1017  }
1018
1019  if (Literal->containsNonAsciiOrNull()) {
1020    StringRef String = Literal->getString();
1021    unsigned NumBytes = String.size();
1022    SmallVector<UTF16, 128> ToBuf(NumBytes);
1023    const UTF8 *FromPtr = (UTF8 *)String.data();
1024    UTF16 *ToPtr = &ToBuf[0];
1025
1026    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1027                                                 &ToPtr, ToPtr + NumBytes,
1028                                                 strictConversion);
1029    // Check for conversion failure.
1030    if (Result != conversionOK)
1031      Diag(Arg->getLocStart(),
1032           diag::warn_cfstring_truncated) << Arg->getSourceRange();
1033  }
1034  return false;
1035}
1036
1037/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1038/// Emit an error and return true on failure, return false on success.
1039bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1040  Expr *Fn = TheCall->getCallee();
1041  if (TheCall->getNumArgs() > 2) {
1042    Diag(TheCall->getArg(2)->getLocStart(),
1043         diag::err_typecheck_call_too_many_args)
1044      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1045      << Fn->getSourceRange()
1046      << SourceRange(TheCall->getArg(2)->getLocStart(),
1047                     (*(TheCall->arg_end()-1))->getLocEnd());
1048    return true;
1049  }
1050
1051  if (TheCall->getNumArgs() < 2) {
1052    return Diag(TheCall->getLocEnd(),
1053      diag::err_typecheck_call_too_few_args_at_least)
1054      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1055  }
1056
1057  // Type-check the first argument normally.
1058  if (checkBuiltinArgument(*this, TheCall, 0))
1059    return true;
1060
1061  // Determine whether the current function is variadic or not.
1062  BlockScopeInfo *CurBlock = getCurBlock();
1063  bool isVariadic;
1064  if (CurBlock)
1065    isVariadic = CurBlock->TheDecl->isVariadic();
1066  else if (FunctionDecl *FD = getCurFunctionDecl())
1067    isVariadic = FD->isVariadic();
1068  else
1069    isVariadic = getCurMethodDecl()->isVariadic();
1070
1071  if (!isVariadic) {
1072    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1073    return true;
1074  }
1075
1076  // Verify that the second argument to the builtin is the last argument of the
1077  // current function or method.
1078  bool SecondArgIsLastNamedArgument = false;
1079  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1080
1081  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1082    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1083      // FIXME: This isn't correct for methods (results in bogus warning).
1084      // Get the last formal in the current function.
1085      const ParmVarDecl *LastArg;
1086      if (CurBlock)
1087        LastArg = *(CurBlock->TheDecl->param_end()-1);
1088      else if (FunctionDecl *FD = getCurFunctionDecl())
1089        LastArg = *(FD->param_end()-1);
1090      else
1091        LastArg = *(getCurMethodDecl()->param_end()-1);
1092      SecondArgIsLastNamedArgument = PV == LastArg;
1093    }
1094  }
1095
1096  if (!SecondArgIsLastNamedArgument)
1097    Diag(TheCall->getArg(1)->getLocStart(),
1098         diag::warn_second_parameter_of_va_start_not_last_named_argument);
1099  return false;
1100}
1101
1102/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1103/// friends.  This is declared to take (...), so we have to check everything.
1104bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1105  if (TheCall->getNumArgs() < 2)
1106    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1107      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1108  if (TheCall->getNumArgs() > 2)
1109    return Diag(TheCall->getArg(2)->getLocStart(),
1110                diag::err_typecheck_call_too_many_args)
1111      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1112      << SourceRange(TheCall->getArg(2)->getLocStart(),
1113                     (*(TheCall->arg_end()-1))->getLocEnd());
1114
1115  ExprResult OrigArg0 = TheCall->getArg(0);
1116  ExprResult OrigArg1 = TheCall->getArg(1);
1117
1118  // Do standard promotions between the two arguments, returning their common
1119  // type.
1120  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1121  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1122    return true;
1123
1124  // Make sure any conversions are pushed back into the call; this is
1125  // type safe since unordered compare builtins are declared as "_Bool
1126  // foo(...)".
1127  TheCall->setArg(0, OrigArg0.get());
1128  TheCall->setArg(1, OrigArg1.get());
1129
1130  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1131    return false;
1132
1133  // If the common type isn't a real floating type, then the arguments were
1134  // invalid for this operation.
1135  if (!Res->isRealFloatingType())
1136    return Diag(OrigArg0.get()->getLocStart(),
1137                diag::err_typecheck_call_invalid_ordered_compare)
1138      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1139      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1140
1141  return false;
1142}
1143
1144/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1145/// __builtin_isnan and friends.  This is declared to take (...), so we have
1146/// to check everything. We expect the last argument to be a floating point
1147/// value.
1148bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1149  if (TheCall->getNumArgs() < NumArgs)
1150    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1151      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1152  if (TheCall->getNumArgs() > NumArgs)
1153    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1154                diag::err_typecheck_call_too_many_args)
1155      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1156      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1157                     (*(TheCall->arg_end()-1))->getLocEnd());
1158
1159  Expr *OrigArg = TheCall->getArg(NumArgs-1);
1160
1161  if (OrigArg->isTypeDependent())
1162    return false;
1163
1164  // This operation requires a non-_Complex floating-point number.
1165  if (!OrigArg->getType()->isRealFloatingType())
1166    return Diag(OrigArg->getLocStart(),
1167                diag::err_typecheck_call_invalid_unary_fp)
1168      << OrigArg->getType() << OrigArg->getSourceRange();
1169
1170  // If this is an implicit conversion from float -> double, remove it.
1171  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1172    Expr *CastArg = Cast->getSubExpr();
1173    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1174      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1175             "promotion from float to double is the only expected cast here");
1176      Cast->setSubExpr(0);
1177      TheCall->setArg(NumArgs-1, CastArg);
1178      OrigArg = CastArg;
1179    }
1180  }
1181
1182  return false;
1183}
1184
1185/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1186// This is declared to take (...), so we have to check everything.
1187ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1188  if (TheCall->getNumArgs() < 2)
1189    return ExprError(Diag(TheCall->getLocEnd(),
1190                          diag::err_typecheck_call_too_few_args_at_least)
1191      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1192      << TheCall->getSourceRange());
1193
1194  // Determine which of the following types of shufflevector we're checking:
1195  // 1) unary, vector mask: (lhs, mask)
1196  // 2) binary, vector mask: (lhs, rhs, mask)
1197  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1198  QualType resType = TheCall->getArg(0)->getType();
1199  unsigned numElements = 0;
1200
1201  if (!TheCall->getArg(0)->isTypeDependent() &&
1202      !TheCall->getArg(1)->isTypeDependent()) {
1203    QualType LHSType = TheCall->getArg(0)->getType();
1204    QualType RHSType = TheCall->getArg(1)->getType();
1205
1206    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1207      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1208        << SourceRange(TheCall->getArg(0)->getLocStart(),
1209                       TheCall->getArg(1)->getLocEnd());
1210      return ExprError();
1211    }
1212
1213    numElements = LHSType->getAs<VectorType>()->getNumElements();
1214    unsigned numResElements = TheCall->getNumArgs() - 2;
1215
1216    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1217    // with mask.  If so, verify that RHS is an integer vector type with the
1218    // same number of elts as lhs.
1219    if (TheCall->getNumArgs() == 2) {
1220      if (!RHSType->hasIntegerRepresentation() ||
1221          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1222        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1223          << SourceRange(TheCall->getArg(1)->getLocStart(),
1224                         TheCall->getArg(1)->getLocEnd());
1225      numResElements = numElements;
1226    }
1227    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1228      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1229        << SourceRange(TheCall->getArg(0)->getLocStart(),
1230                       TheCall->getArg(1)->getLocEnd());
1231      return ExprError();
1232    } else if (numElements != numResElements) {
1233      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1234      resType = Context.getVectorType(eltType, numResElements,
1235                                      VectorType::GenericVector);
1236    }
1237  }
1238
1239  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1240    if (TheCall->getArg(i)->isTypeDependent() ||
1241        TheCall->getArg(i)->isValueDependent())
1242      continue;
1243
1244    llvm::APSInt Result(32);
1245    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1246      return ExprError(Diag(TheCall->getLocStart(),
1247                  diag::err_shufflevector_nonconstant_argument)
1248                << TheCall->getArg(i)->getSourceRange());
1249
1250    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1251      return ExprError(Diag(TheCall->getLocStart(),
1252                  diag::err_shufflevector_argument_too_large)
1253               << TheCall->getArg(i)->getSourceRange());
1254  }
1255
1256  SmallVector<Expr*, 32> exprs;
1257
1258  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1259    exprs.push_back(TheCall->getArg(i));
1260    TheCall->setArg(i, 0);
1261  }
1262
1263  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1264                                            exprs.size(), resType,
1265                                            TheCall->getCallee()->getLocStart(),
1266                                            TheCall->getRParenLoc()));
1267}
1268
1269/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1270// This is declared to take (const void*, ...) and can take two
1271// optional constant int args.
1272bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1273  unsigned NumArgs = TheCall->getNumArgs();
1274
1275  if (NumArgs > 3)
1276    return Diag(TheCall->getLocEnd(),
1277             diag::err_typecheck_call_too_many_args_at_most)
1278             << 0 /*function call*/ << 3 << NumArgs
1279             << TheCall->getSourceRange();
1280
1281  // Argument 0 is checked for us and the remaining arguments must be
1282  // constant integers.
1283  for (unsigned i = 1; i != NumArgs; ++i) {
1284    Expr *Arg = TheCall->getArg(i);
1285
1286    llvm::APSInt Result;
1287    if (SemaBuiltinConstantArg(TheCall, i, Result))
1288      return true;
1289
1290    // FIXME: gcc issues a warning and rewrites these to 0. These
1291    // seems especially odd for the third argument since the default
1292    // is 3.
1293    if (i == 1) {
1294      if (Result.getLimitedValue() > 1)
1295        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1296             << "0" << "1" << Arg->getSourceRange();
1297    } else {
1298      if (Result.getLimitedValue() > 3)
1299        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1300            << "0" << "3" << Arg->getSourceRange();
1301    }
1302  }
1303
1304  return false;
1305}
1306
1307/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1308/// TheCall is a constant expression.
1309bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1310                                  llvm::APSInt &Result) {
1311  Expr *Arg = TheCall->getArg(ArgNum);
1312  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1313  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1314
1315  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1316
1317  if (!Arg->isIntegerConstantExpr(Result, Context))
1318    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1319                << FDecl->getDeclName() <<  Arg->getSourceRange();
1320
1321  return false;
1322}
1323
1324/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1325/// int type). This simply type checks that type is one of the defined
1326/// constants (0-3).
1327// For compatibility check 0-3, llvm only handles 0 and 2.
1328bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1329  llvm::APSInt Result;
1330
1331  // Check constant-ness first.
1332  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1333    return true;
1334
1335  Expr *Arg = TheCall->getArg(1);
1336  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1337    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1338             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1339  }
1340
1341  return false;
1342}
1343
1344/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1345/// This checks that val is a constant 1.
1346bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1347  Expr *Arg = TheCall->getArg(1);
1348  llvm::APSInt Result;
1349
1350  // TODO: This is less than ideal. Overload this to take a value.
1351  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1352    return true;
1353
1354  if (Result != 1)
1355    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1356             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1357
1358  return false;
1359}
1360
1361// Handle i > 1 ? "x" : "y", recursively.
1362bool Sema::SemaCheckStringLiteral(const Expr *E, Expr **Args,
1363                                  unsigned NumArgs, bool HasVAListArg,
1364                                  unsigned format_idx, unsigned firstDataArg,
1365                                  FormatStringType Type, bool inFunctionCall) {
1366 tryAgain:
1367  if (E->isTypeDependent() || E->isValueDependent())
1368    return false;
1369
1370  E = E->IgnoreParenCasts();
1371
1372  if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1373    // Technically -Wformat-nonliteral does not warn about this case.
1374    // The behavior of printf and friends in this case is implementation
1375    // dependent.  Ideally if the format string cannot be null then
1376    // it should have a 'nonnull' attribute in the function prototype.
1377    return true;
1378
1379  switch (E->getStmtClass()) {
1380  case Stmt::BinaryConditionalOperatorClass:
1381  case Stmt::ConditionalOperatorClass: {
1382    const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1383    return SemaCheckStringLiteral(C->getTrueExpr(), Args, NumArgs, HasVAListArg,
1384                                  format_idx, firstDataArg, Type,
1385                                  inFunctionCall)
1386       && SemaCheckStringLiteral(C->getFalseExpr(), Args, NumArgs, HasVAListArg,
1387                                 format_idx, firstDataArg, Type,
1388                                 inFunctionCall);
1389  }
1390
1391  case Stmt::ImplicitCastExprClass: {
1392    E = cast<ImplicitCastExpr>(E)->getSubExpr();
1393    goto tryAgain;
1394  }
1395
1396  case Stmt::OpaqueValueExprClass:
1397    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1398      E = src;
1399      goto tryAgain;
1400    }
1401    return false;
1402
1403  case Stmt::PredefinedExprClass:
1404    // While __func__, etc., are technically not string literals, they
1405    // cannot contain format specifiers and thus are not a security
1406    // liability.
1407    return true;
1408
1409  case Stmt::DeclRefExprClass: {
1410    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1411
1412    // As an exception, do not flag errors for variables binding to
1413    // const string literals.
1414    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1415      bool isConstant = false;
1416      QualType T = DR->getType();
1417
1418      if (const ArrayType *AT = Context.getAsArrayType(T)) {
1419        isConstant = AT->getElementType().isConstant(Context);
1420      } else if (const PointerType *PT = T->getAs<PointerType>()) {
1421        isConstant = T.isConstant(Context) &&
1422                     PT->getPointeeType().isConstant(Context);
1423      } else if (T->isObjCObjectPointerType()) {
1424        // In ObjC, there is usually no "const ObjectPointer" type,
1425        // so don't check if the pointee type is constant.
1426        isConstant = T.isConstant(Context);
1427      }
1428
1429      if (isConstant) {
1430        if (const Expr *Init = VD->getAnyInitializer())
1431          return SemaCheckStringLiteral(Init, Args, NumArgs,
1432                                        HasVAListArg, format_idx, firstDataArg,
1433                                        Type, /*inFunctionCall*/false);
1434      }
1435
1436      // For vprintf* functions (i.e., HasVAListArg==true), we add a
1437      // special check to see if the format string is a function parameter
1438      // of the function calling the printf function.  If the function
1439      // has an attribute indicating it is a printf-like function, then we
1440      // should suppress warnings concerning non-literals being used in a call
1441      // to a vprintf function.  For example:
1442      //
1443      // void
1444      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1445      //      va_list ap;
1446      //      va_start(ap, fmt);
1447      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1448      //      ...
1449      //
1450      if (HasVAListArg) {
1451        if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
1452          if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
1453            int PVIndex = PV->getFunctionScopeIndex() + 1;
1454            for (specific_attr_iterator<FormatAttr>
1455                 i = ND->specific_attr_begin<FormatAttr>(),
1456                 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
1457              FormatAttr *PVFormat = *i;
1458              // adjust for implicit parameter
1459              if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1460                if (MD->isInstance())
1461                  ++PVIndex;
1462              // We also check if the formats are compatible.
1463              // We can't pass a 'scanf' string to a 'printf' function.
1464              if (PVIndex == PVFormat->getFormatIdx() &&
1465                  Type == GetFormatStringType(PVFormat))
1466                return true;
1467            }
1468          }
1469        }
1470      }
1471    }
1472
1473    return false;
1474  }
1475
1476  case Stmt::CallExprClass:
1477  case Stmt::CXXMemberCallExprClass: {
1478    const CallExpr *CE = cast<CallExpr>(E);
1479    if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
1480      if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
1481        unsigned ArgIndex = FA->getFormatIdx();
1482        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
1483          if (MD->isInstance())
1484            --ArgIndex;
1485        const Expr *Arg = CE->getArg(ArgIndex - 1);
1486
1487        return SemaCheckStringLiteral(Arg, Args, NumArgs, HasVAListArg,
1488                                      format_idx, firstDataArg, Type,
1489                                      inFunctionCall);
1490      }
1491    }
1492
1493    return false;
1494  }
1495  case Stmt::ObjCStringLiteralClass:
1496  case Stmt::StringLiteralClass: {
1497    const StringLiteral *StrE = NULL;
1498
1499    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1500      StrE = ObjCFExpr->getString();
1501    else
1502      StrE = cast<StringLiteral>(E);
1503
1504    if (StrE) {
1505      CheckFormatString(StrE, E, Args, NumArgs, HasVAListArg, format_idx,
1506                        firstDataArg, Type, inFunctionCall);
1507      return true;
1508    }
1509
1510    return false;
1511  }
1512
1513  default:
1514    return false;
1515  }
1516}
1517
1518void
1519Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1520                            const Expr * const *ExprArgs,
1521                            SourceLocation CallSiteLoc) {
1522  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1523                                  e = NonNull->args_end();
1524       i != e; ++i) {
1525    const Expr *ArgExpr = ExprArgs[*i];
1526    if (ArgExpr->isNullPointerConstant(Context,
1527                                       Expr::NPC_ValueDependentIsNotNull))
1528      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1529  }
1530}
1531
1532Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
1533  return llvm::StringSwitch<FormatStringType>(Format->getType())
1534  .Case("scanf", FST_Scanf)
1535  .Cases("printf", "printf0", FST_Printf)
1536  .Cases("NSString", "CFString", FST_NSString)
1537  .Case("strftime", FST_Strftime)
1538  .Case("strfmon", FST_Strfmon)
1539  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
1540  .Default(FST_Unknown);
1541}
1542
1543/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1544/// functions) for correct use of format strings.
1545void Sema::CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall) {
1546  bool IsCXXMember = false;
1547  // The way the format attribute works in GCC, the implicit this argument
1548  // of member functions is counted. However, it doesn't appear in our own
1549  // lists, so decrement format_idx in that case.
1550  IsCXXMember = isa<CXXMemberCallExpr>(TheCall);
1551  CheckFormatArguments(Format, TheCall->getArgs(), TheCall->getNumArgs(),
1552                       IsCXXMember, TheCall->getRParenLoc(),
1553                       TheCall->getCallee()->getSourceRange());
1554}
1555
1556void Sema::CheckFormatArguments(const FormatAttr *Format, Expr **Args,
1557                                unsigned NumArgs, bool IsCXXMember,
1558                                SourceLocation Loc, SourceRange Range) {
1559  bool HasVAListArg = Format->getFirstArg() == 0;
1560  unsigned format_idx = Format->getFormatIdx() - 1;
1561  unsigned firstDataArg = HasVAListArg ? 0 : Format->getFirstArg() - 1;
1562  if (IsCXXMember) {
1563    if (format_idx == 0)
1564      return;
1565    --format_idx;
1566    if(firstDataArg != 0)
1567      --firstDataArg;
1568  }
1569  CheckFormatArguments(Args, NumArgs, HasVAListArg, format_idx,
1570                       firstDataArg, GetFormatStringType(Format), Loc, Range);
1571}
1572
1573void Sema::CheckFormatArguments(Expr **Args, unsigned NumArgs,
1574                                bool HasVAListArg, unsigned format_idx,
1575                                unsigned firstDataArg, FormatStringType Type,
1576                                SourceLocation Loc, SourceRange Range) {
1577  // CHECK: printf/scanf-like function is called with no format string.
1578  if (format_idx >= NumArgs) {
1579    Diag(Loc, diag::warn_missing_format_string) << Range;
1580    return;
1581  }
1582
1583  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
1584
1585  // CHECK: format string is not a string literal.
1586  //
1587  // Dynamically generated format strings are difficult to
1588  // automatically vet at compile time.  Requiring that format strings
1589  // are string literals: (1) permits the checking of format strings by
1590  // the compiler and thereby (2) can practically remove the source of
1591  // many format string exploits.
1592
1593  // Format string can be either ObjC string (e.g. @"%d") or
1594  // C string (e.g. "%d")
1595  // ObjC string uses the same format specifiers as C string, so we can use
1596  // the same format string checking logic for both ObjC and C strings.
1597  if (SemaCheckStringLiteral(OrigFormatExpr, Args, NumArgs, HasVAListArg,
1598                             format_idx, firstDataArg, Type))
1599    return;  // Literal format string found, check done!
1600
1601  // Strftime is particular as it always uses a single 'time' argument,
1602  // so it is safe to pass a non-literal string.
1603  if (Type == FST_Strftime)
1604    return;
1605
1606  // Do not emit diag when the string param is a macro expansion and the
1607  // format is either NSString or CFString. This is a hack to prevent
1608  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
1609  // which are usually used in place of NS and CF string literals.
1610  if (Type == FST_NSString && Args[format_idx]->getLocStart().isMacroID())
1611    return;
1612
1613  // If there are no arguments specified, warn with -Wformat-security, otherwise
1614  // warn only with -Wformat-nonliteral.
1615  if (NumArgs == format_idx+1)
1616    Diag(Args[format_idx]->getLocStart(),
1617         diag::warn_format_nonliteral_noargs)
1618      << OrigFormatExpr->getSourceRange();
1619  else
1620    Diag(Args[format_idx]->getLocStart(),
1621         diag::warn_format_nonliteral)
1622           << OrigFormatExpr->getSourceRange();
1623}
1624
1625namespace {
1626class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1627protected:
1628  Sema &S;
1629  const StringLiteral *FExpr;
1630  const Expr *OrigFormatExpr;
1631  const unsigned FirstDataArg;
1632  const unsigned NumDataArgs;
1633  const bool IsObjCLiteral;
1634  const char *Beg; // Start of format string.
1635  const bool HasVAListArg;
1636  const Expr * const *Args;
1637  const unsigned NumArgs;
1638  unsigned FormatIdx;
1639  llvm::BitVector CoveredArgs;
1640  bool usesPositionalArgs;
1641  bool atFirstArg;
1642  bool inFunctionCall;
1643public:
1644  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1645                     const Expr *origFormatExpr, unsigned firstDataArg,
1646                     unsigned numDataArgs, bool isObjCLiteral,
1647                     const char *beg, bool hasVAListArg,
1648                     Expr **args, unsigned numArgs,
1649                     unsigned formatIdx, bool inFunctionCall)
1650    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1651      FirstDataArg(firstDataArg),
1652      NumDataArgs(numDataArgs),
1653      IsObjCLiteral(isObjCLiteral), Beg(beg),
1654      HasVAListArg(hasVAListArg),
1655      Args(args), NumArgs(numArgs), FormatIdx(formatIdx),
1656      usesPositionalArgs(false), atFirstArg(true),
1657      inFunctionCall(inFunctionCall) {
1658        CoveredArgs.resize(numDataArgs);
1659        CoveredArgs.reset();
1660      }
1661
1662  void DoneProcessing();
1663
1664  void HandleIncompleteSpecifier(const char *startSpecifier,
1665                                 unsigned specifierLen);
1666
1667  void HandleNonStandardLengthModifier(
1668      const analyze_format_string::LengthModifier &LM,
1669      const char *startSpecifier, unsigned specifierLen);
1670
1671  void HandleNonStandardConversionSpecifier(
1672      const analyze_format_string::ConversionSpecifier &CS,
1673      const char *startSpecifier, unsigned specifierLen);
1674
1675  void HandleNonStandardConversionSpecification(
1676      const analyze_format_string::LengthModifier &LM,
1677      const analyze_format_string::ConversionSpecifier &CS,
1678      const char *startSpecifier, unsigned specifierLen);
1679
1680  virtual void HandleInvalidPosition(const char *startSpecifier,
1681                                     unsigned specifierLen,
1682                                     analyze_format_string::PositionContext p);
1683
1684  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1685
1686  void HandleNullChar(const char *nullCharacter);
1687
1688  template <typename Range>
1689  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1690                                   const Expr *ArgumentExpr,
1691                                   PartialDiagnostic PDiag,
1692                                   SourceLocation StringLoc,
1693                                   bool IsStringLocation, Range StringRange,
1694                                   FixItHint Fixit = FixItHint());
1695
1696protected:
1697  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1698                                        const char *startSpec,
1699                                        unsigned specifierLen,
1700                                        const char *csStart, unsigned csLen);
1701
1702  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1703                                         const char *startSpec,
1704                                         unsigned specifierLen);
1705
1706  SourceRange getFormatStringRange();
1707  CharSourceRange getSpecifierRange(const char *startSpecifier,
1708                                    unsigned specifierLen);
1709  SourceLocation getLocationOfByte(const char *x);
1710
1711  const Expr *getDataArg(unsigned i) const;
1712
1713  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1714                    const analyze_format_string::ConversionSpecifier &CS,
1715                    const char *startSpecifier, unsigned specifierLen,
1716                    unsigned argIndex);
1717
1718  template <typename Range>
1719  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1720                            bool IsStringLocation, Range StringRange,
1721                            FixItHint Fixit = FixItHint());
1722
1723  void CheckPositionalAndNonpositionalArgs(
1724      const analyze_format_string::FormatSpecifier *FS);
1725};
1726}
1727
1728SourceRange CheckFormatHandler::getFormatStringRange() {
1729  return OrigFormatExpr->getSourceRange();
1730}
1731
1732CharSourceRange CheckFormatHandler::
1733getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1734  SourceLocation Start = getLocationOfByte(startSpecifier);
1735  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1736
1737  // Advance the end SourceLocation by one due to half-open ranges.
1738  End = End.getLocWithOffset(1);
1739
1740  return CharSourceRange::getCharRange(Start, End);
1741}
1742
1743SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1744  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1745}
1746
1747void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1748                                                   unsigned specifierLen){
1749  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1750                       getLocationOfByte(startSpecifier),
1751                       /*IsStringLocation*/true,
1752                       getSpecifierRange(startSpecifier, specifierLen));
1753}
1754
1755void CheckFormatHandler::HandleNonStandardLengthModifier(
1756    const analyze_format_string::LengthModifier &LM,
1757    const char *startSpecifier, unsigned specifierLen) {
1758  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << LM.toString()
1759                       << "length modifier",
1760                       getLocationOfByte(LM.getStart()),
1761                       /*IsStringLocation*/true,
1762                       getSpecifierRange(startSpecifier, specifierLen));
1763}
1764
1765void CheckFormatHandler::HandleNonStandardConversionSpecifier(
1766    const analyze_format_string::ConversionSpecifier &CS,
1767    const char *startSpecifier, unsigned specifierLen) {
1768  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) << CS.toString()
1769                       << "conversion specifier",
1770                       getLocationOfByte(CS.getStart()),
1771                       /*IsStringLocation*/true,
1772                       getSpecifierRange(startSpecifier, specifierLen));
1773}
1774
1775void CheckFormatHandler::HandleNonStandardConversionSpecification(
1776    const analyze_format_string::LengthModifier &LM,
1777    const analyze_format_string::ConversionSpecifier &CS,
1778    const char *startSpecifier, unsigned specifierLen) {
1779  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_conversion_spec)
1780                       << LM.toString() << CS.toString(),
1781                       getLocationOfByte(LM.getStart()),
1782                       /*IsStringLocation*/true,
1783                       getSpecifierRange(startSpecifier, specifierLen));
1784}
1785
1786void
1787CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1788                                     analyze_format_string::PositionContext p) {
1789  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1790                         << (unsigned) p,
1791                       getLocationOfByte(startPos), /*IsStringLocation*/true,
1792                       getSpecifierRange(startPos, posLen));
1793}
1794
1795void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1796                                            unsigned posLen) {
1797  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1798                               getLocationOfByte(startPos),
1799                               /*IsStringLocation*/true,
1800                               getSpecifierRange(startPos, posLen));
1801}
1802
1803void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1804  if (!IsObjCLiteral) {
1805    // The presence of a null character is likely an error.
1806    EmitFormatDiagnostic(
1807      S.PDiag(diag::warn_printf_format_string_contains_null_char),
1808      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1809      getFormatStringRange());
1810  }
1811}
1812
1813const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1814  return Args[FirstDataArg + i];
1815}
1816
1817void CheckFormatHandler::DoneProcessing() {
1818    // Does the number of data arguments exceed the number of
1819    // format conversions in the format string?
1820  if (!HasVAListArg) {
1821      // Find any arguments that weren't covered.
1822    CoveredArgs.flip();
1823    signed notCoveredArg = CoveredArgs.find_first();
1824    if (notCoveredArg >= 0) {
1825      assert((unsigned)notCoveredArg < NumDataArgs);
1826      EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1827                           getDataArg((unsigned) notCoveredArg)->getLocStart(),
1828                           /*IsStringLocation*/false, getFormatStringRange());
1829    }
1830  }
1831}
1832
1833bool
1834CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1835                                                     SourceLocation Loc,
1836                                                     const char *startSpec,
1837                                                     unsigned specifierLen,
1838                                                     const char *csStart,
1839                                                     unsigned csLen) {
1840
1841  bool keepGoing = true;
1842  if (argIndex < NumDataArgs) {
1843    // Consider the argument coverered, even though the specifier doesn't
1844    // make sense.
1845    CoveredArgs.set(argIndex);
1846  }
1847  else {
1848    // If argIndex exceeds the number of data arguments we
1849    // don't issue a warning because that is just a cascade of warnings (and
1850    // they may have intended '%%' anyway). We don't want to continue processing
1851    // the format string after this point, however, as we will like just get
1852    // gibberish when trying to match arguments.
1853    keepGoing = false;
1854  }
1855
1856  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1857                         << StringRef(csStart, csLen),
1858                       Loc, /*IsStringLocation*/true,
1859                       getSpecifierRange(startSpec, specifierLen));
1860
1861  return keepGoing;
1862}
1863
1864void
1865CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1866                                                      const char *startSpec,
1867                                                      unsigned specifierLen) {
1868  EmitFormatDiagnostic(
1869    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1870    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1871}
1872
1873bool
1874CheckFormatHandler::CheckNumArgs(
1875  const analyze_format_string::FormatSpecifier &FS,
1876  const analyze_format_string::ConversionSpecifier &CS,
1877  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1878
1879  if (argIndex >= NumDataArgs) {
1880    PartialDiagnostic PDiag = FS.usesPositionalArg()
1881      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1882           << (argIndex+1) << NumDataArgs)
1883      : S.PDiag(diag::warn_printf_insufficient_data_args);
1884    EmitFormatDiagnostic(
1885      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1886      getSpecifierRange(startSpecifier, specifierLen));
1887    return false;
1888  }
1889  return true;
1890}
1891
1892template<typename Range>
1893void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1894                                              SourceLocation Loc,
1895                                              bool IsStringLocation,
1896                                              Range StringRange,
1897                                              FixItHint FixIt) {
1898  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
1899                       Loc, IsStringLocation, StringRange, FixIt);
1900}
1901
1902/// \brief If the format string is not within the funcion call, emit a note
1903/// so that the function call and string are in diagnostic messages.
1904///
1905/// \param inFunctionCall if true, the format string is within the function
1906/// call and only one diagnostic message will be produced.  Otherwise, an
1907/// extra note will be emitted pointing to location of the format string.
1908///
1909/// \param ArgumentExpr the expression that is passed as the format string
1910/// argument in the function call.  Used for getting locations when two
1911/// diagnostics are emitted.
1912///
1913/// \param PDiag the callee should already have provided any strings for the
1914/// diagnostic message.  This function only adds locations and fixits
1915/// to diagnostics.
1916///
1917/// \param Loc primary location for diagnostic.  If two diagnostics are
1918/// required, one will be at Loc and a new SourceLocation will be created for
1919/// the other one.
1920///
1921/// \param IsStringLocation if true, Loc points to the format string should be
1922/// used for the note.  Otherwise, Loc points to the argument list and will
1923/// be used with PDiag.
1924///
1925/// \param StringRange some or all of the string to highlight.  This is
1926/// templated so it can accept either a CharSourceRange or a SourceRange.
1927///
1928/// \param Fixit optional fix it hint for the format string.
1929template<typename Range>
1930void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1931                                              const Expr *ArgumentExpr,
1932                                              PartialDiagnostic PDiag,
1933                                              SourceLocation Loc,
1934                                              bool IsStringLocation,
1935                                              Range StringRange,
1936                                              FixItHint FixIt) {
1937  if (InFunctionCall)
1938    S.Diag(Loc, PDiag) << StringRange << FixIt;
1939  else {
1940    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1941      << ArgumentExpr->getSourceRange();
1942    S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1943           diag::note_format_string_defined)
1944      << StringRange << FixIt;
1945  }
1946}
1947
1948//===--- CHECK: Printf format string checking ------------------------------===//
1949
1950namespace {
1951class CheckPrintfHandler : public CheckFormatHandler {
1952public:
1953  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1954                     const Expr *origFormatExpr, unsigned firstDataArg,
1955                     unsigned numDataArgs, bool isObjCLiteral,
1956                     const char *beg, bool hasVAListArg,
1957                     Expr **Args, unsigned NumArgs,
1958                     unsigned formatIdx, bool inFunctionCall)
1959  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1960                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1961                       Args, NumArgs, formatIdx, inFunctionCall) {}
1962
1963
1964  bool HandleInvalidPrintfConversionSpecifier(
1965                                      const analyze_printf::PrintfSpecifier &FS,
1966                                      const char *startSpecifier,
1967                                      unsigned specifierLen);
1968
1969  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1970                             const char *startSpecifier,
1971                             unsigned specifierLen);
1972
1973  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1974                    const char *startSpecifier, unsigned specifierLen);
1975  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1976                           const analyze_printf::OptionalAmount &Amt,
1977                           unsigned type,
1978                           const char *startSpecifier, unsigned specifierLen);
1979  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1980                  const analyze_printf::OptionalFlag &flag,
1981                  const char *startSpecifier, unsigned specifierLen);
1982  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1983                         const analyze_printf::OptionalFlag &ignoredFlag,
1984                         const analyze_printf::OptionalFlag &flag,
1985                         const char *startSpecifier, unsigned specifierLen);
1986};
1987}
1988
1989bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1990                                      const analyze_printf::PrintfSpecifier &FS,
1991                                      const char *startSpecifier,
1992                                      unsigned specifierLen) {
1993  const analyze_printf::PrintfConversionSpecifier &CS =
1994    FS.getConversionSpecifier();
1995
1996  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1997                                          getLocationOfByte(CS.getStart()),
1998                                          startSpecifier, specifierLen,
1999                                          CS.getStart(), CS.getLength());
2000}
2001
2002bool CheckPrintfHandler::HandleAmount(
2003                               const analyze_format_string::OptionalAmount &Amt,
2004                               unsigned k, const char *startSpecifier,
2005                               unsigned specifierLen) {
2006
2007  if (Amt.hasDataArgument()) {
2008    if (!HasVAListArg) {
2009      unsigned argIndex = Amt.getArgIndex();
2010      if (argIndex >= NumDataArgs) {
2011        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2012                               << k,
2013                             getLocationOfByte(Amt.getStart()),
2014                             /*IsStringLocation*/true,
2015                             getSpecifierRange(startSpecifier, specifierLen));
2016        // Don't do any more checking.  We will just emit
2017        // spurious errors.
2018        return false;
2019      }
2020
2021      // Type check the data argument.  It should be an 'int'.
2022      // Although not in conformance with C99, we also allow the argument to be
2023      // an 'unsigned int' as that is a reasonably safe case.  GCC also
2024      // doesn't emit a warning for that case.
2025      CoveredArgs.set(argIndex);
2026      const Expr *Arg = getDataArg(argIndex);
2027      QualType T = Arg->getType();
2028
2029      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2030      assert(ATR.isValid());
2031
2032      if (!ATR.matchesType(S.Context, T)) {
2033        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2034                               << k << ATR.getRepresentativeTypeName(S.Context)
2035                               << T << Arg->getSourceRange(),
2036                             getLocationOfByte(Amt.getStart()),
2037                             /*IsStringLocation*/true,
2038                             getSpecifierRange(startSpecifier, specifierLen));
2039        // Don't do any more checking.  We will just emit
2040        // spurious errors.
2041        return false;
2042      }
2043    }
2044  }
2045  return true;
2046}
2047
2048void CheckPrintfHandler::HandleInvalidAmount(
2049                                      const analyze_printf::PrintfSpecifier &FS,
2050                                      const analyze_printf::OptionalAmount &Amt,
2051                                      unsigned type,
2052                                      const char *startSpecifier,
2053                                      unsigned specifierLen) {
2054  const analyze_printf::PrintfConversionSpecifier &CS =
2055    FS.getConversionSpecifier();
2056
2057  FixItHint fixit =
2058    Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2059      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2060                                 Amt.getConstantLength()))
2061      : FixItHint();
2062
2063  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2064                         << type << CS.toString(),
2065                       getLocationOfByte(Amt.getStart()),
2066                       /*IsStringLocation*/true,
2067                       getSpecifierRange(startSpecifier, specifierLen),
2068                       fixit);
2069}
2070
2071void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2072                                    const analyze_printf::OptionalFlag &flag,
2073                                    const char *startSpecifier,
2074                                    unsigned specifierLen) {
2075  // Warn about pointless flag with a fixit removal.
2076  const analyze_printf::PrintfConversionSpecifier &CS =
2077    FS.getConversionSpecifier();
2078  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2079                         << flag.toString() << CS.toString(),
2080                       getLocationOfByte(flag.getPosition()),
2081                       /*IsStringLocation*/true,
2082                       getSpecifierRange(startSpecifier, specifierLen),
2083                       FixItHint::CreateRemoval(
2084                         getSpecifierRange(flag.getPosition(), 1)));
2085}
2086
2087void CheckPrintfHandler::HandleIgnoredFlag(
2088                                const analyze_printf::PrintfSpecifier &FS,
2089                                const analyze_printf::OptionalFlag &ignoredFlag,
2090                                const analyze_printf::OptionalFlag &flag,
2091                                const char *startSpecifier,
2092                                unsigned specifierLen) {
2093  // Warn about ignored flag with a fixit removal.
2094  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2095                         << ignoredFlag.toString() << flag.toString(),
2096                       getLocationOfByte(ignoredFlag.getPosition()),
2097                       /*IsStringLocation*/true,
2098                       getSpecifierRange(startSpecifier, specifierLen),
2099                       FixItHint::CreateRemoval(
2100                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
2101}
2102
2103bool
2104CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2105                                            &FS,
2106                                          const char *startSpecifier,
2107                                          unsigned specifierLen) {
2108
2109  using namespace analyze_format_string;
2110  using namespace analyze_printf;
2111  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2112
2113  if (FS.consumesDataArgument()) {
2114    if (atFirstArg) {
2115        atFirstArg = false;
2116        usesPositionalArgs = FS.usesPositionalArg();
2117    }
2118    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2119      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2120                                        startSpecifier, specifierLen);
2121      return false;
2122    }
2123  }
2124
2125  // First check if the field width, precision, and conversion specifier
2126  // have matching data arguments.
2127  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2128                    startSpecifier, specifierLen)) {
2129    return false;
2130  }
2131
2132  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2133                    startSpecifier, specifierLen)) {
2134    return false;
2135  }
2136
2137  if (!CS.consumesDataArgument()) {
2138    // FIXME: Technically specifying a precision or field width here
2139    // makes no sense.  Worth issuing a warning at some point.
2140    return true;
2141  }
2142
2143  // Consume the argument.
2144  unsigned argIndex = FS.getArgIndex();
2145  if (argIndex < NumDataArgs) {
2146    // The check to see if the argIndex is valid will come later.
2147    // We set the bit here because we may exit early from this
2148    // function if we encounter some other error.
2149    CoveredArgs.set(argIndex);
2150  }
2151
2152  // Check for using an Objective-C specific conversion specifier
2153  // in a non-ObjC literal.
2154  if (!IsObjCLiteral && CS.isObjCArg()) {
2155    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2156                                                  specifierLen);
2157  }
2158
2159  // Check for invalid use of field width
2160  if (!FS.hasValidFieldWidth()) {
2161    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2162        startSpecifier, specifierLen);
2163  }
2164
2165  // Check for invalid use of precision
2166  if (!FS.hasValidPrecision()) {
2167    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2168        startSpecifier, specifierLen);
2169  }
2170
2171  // Check each flag does not conflict with any other component.
2172  if (!FS.hasValidThousandsGroupingPrefix())
2173    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2174  if (!FS.hasValidLeadingZeros())
2175    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2176  if (!FS.hasValidPlusPrefix())
2177    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2178  if (!FS.hasValidSpacePrefix())
2179    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
2180  if (!FS.hasValidAlternativeForm())
2181    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2182  if (!FS.hasValidLeftJustified())
2183    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2184
2185  // Check that flags are not ignored by another flag
2186  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2187    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2188        startSpecifier, specifierLen);
2189  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2190    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2191            startSpecifier, specifierLen);
2192
2193  // Check the length modifier is valid with the given conversion specifier.
2194  const LengthModifier &LM = FS.getLengthModifier();
2195  if (!FS.hasValidLengthModifier())
2196    EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2197                           << LM.toString() << CS.toString(),
2198                         getLocationOfByte(LM.getStart()),
2199                         /*IsStringLocation*/true,
2200                         getSpecifierRange(startSpecifier, specifierLen),
2201                         FixItHint::CreateRemoval(
2202                           getSpecifierRange(LM.getStart(),
2203                                             LM.getLength())));
2204  if (!FS.hasStandardLengthModifier())
2205    HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
2206  if (!FS.hasStandardConversionSpecifier(S.getLangOptions()))
2207    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2208  if (!FS.hasStandardLengthConversionCombination())
2209    HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2210                                             specifierLen);
2211
2212  // Are we using '%n'?
2213  if (CS.getKind() == ConversionSpecifier::nArg) {
2214    // Issue a warning about this being a possible security issue.
2215    EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2216                         getLocationOfByte(CS.getStart()),
2217                         /*IsStringLocation*/true,
2218                         getSpecifierRange(startSpecifier, specifierLen));
2219    // Continue checking the other format specifiers.
2220    return true;
2221  }
2222
2223  // The remaining checks depend on the data arguments.
2224  if (HasVAListArg)
2225    return true;
2226
2227  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2228    return false;
2229
2230  // Now type check the data expression that matches the
2231  // format specifier.
2232  const Expr *Ex = getDataArg(argIndex);
2233  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context,
2234                                                           IsObjCLiteral);
2235  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2236    // Check if we didn't match because of an implicit cast from a 'char'
2237    // or 'short' to an 'int'.  This is done because printf is a varargs
2238    // function.
2239    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
2240      if (ICE->getType() == S.Context.IntTy) {
2241        // All further checking is done on the subexpression.
2242        Ex = ICE->getSubExpr();
2243        if (ATR.matchesType(S.Context, Ex->getType()))
2244          return true;
2245      }
2246
2247    // We may be able to offer a FixItHint if it is a supported type.
2248    PrintfSpecifier fixedFS = FS;
2249    bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2250                                   S.Context, IsObjCLiteral);
2251
2252    if (success) {
2253      // Get the fix string from the fixed format specifier
2254      SmallString<128> buf;
2255      llvm::raw_svector_ostream os(buf);
2256      fixedFS.toString(os);
2257
2258      EmitFormatDiagnostic(
2259        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2260          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2261          << Ex->getSourceRange(),
2262        getLocationOfByte(CS.getStart()),
2263        /*IsStringLocation*/true,
2264        getSpecifierRange(startSpecifier, specifierLen),
2265        FixItHint::CreateReplacement(
2266          getSpecifierRange(startSpecifier, specifierLen),
2267          os.str()));
2268    }
2269    else {
2270      EmitFormatDiagnostic(
2271        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2272          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2273          << getSpecifierRange(startSpecifier, specifierLen)
2274          << Ex->getSourceRange(),
2275        getLocationOfByte(CS.getStart()),
2276        true,
2277        getSpecifierRange(startSpecifier, specifierLen));
2278    }
2279  }
2280
2281  return true;
2282}
2283
2284//===--- CHECK: Scanf format string checking ------------------------------===//
2285
2286namespace {
2287class CheckScanfHandler : public CheckFormatHandler {
2288public:
2289  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2290                    const Expr *origFormatExpr, unsigned firstDataArg,
2291                    unsigned numDataArgs, bool isObjCLiteral,
2292                    const char *beg, bool hasVAListArg,
2293                    Expr **Args, unsigned NumArgs,
2294                    unsigned formatIdx, bool inFunctionCall)
2295  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2296                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
2297                       Args, NumArgs, formatIdx, inFunctionCall) {}
2298
2299  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2300                            const char *startSpecifier,
2301                            unsigned specifierLen);
2302
2303  bool HandleInvalidScanfConversionSpecifier(
2304          const analyze_scanf::ScanfSpecifier &FS,
2305          const char *startSpecifier,
2306          unsigned specifierLen);
2307
2308  void HandleIncompleteScanList(const char *start, const char *end);
2309};
2310}
2311
2312void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2313                                                 const char *end) {
2314  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2315                       getLocationOfByte(end), /*IsStringLocation*/true,
2316                       getSpecifierRange(start, end - start));
2317}
2318
2319bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2320                                        const analyze_scanf::ScanfSpecifier &FS,
2321                                        const char *startSpecifier,
2322                                        unsigned specifierLen) {
2323
2324  const analyze_scanf::ScanfConversionSpecifier &CS =
2325    FS.getConversionSpecifier();
2326
2327  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2328                                          getLocationOfByte(CS.getStart()),
2329                                          startSpecifier, specifierLen,
2330                                          CS.getStart(), CS.getLength());
2331}
2332
2333bool CheckScanfHandler::HandleScanfSpecifier(
2334                                       const analyze_scanf::ScanfSpecifier &FS,
2335                                       const char *startSpecifier,
2336                                       unsigned specifierLen) {
2337
2338  using namespace analyze_scanf;
2339  using namespace analyze_format_string;
2340
2341  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2342
2343  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2344  // be used to decide if we are using positional arguments consistently.
2345  if (FS.consumesDataArgument()) {
2346    if (atFirstArg) {
2347      atFirstArg = false;
2348      usesPositionalArgs = FS.usesPositionalArg();
2349    }
2350    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2351      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2352                                        startSpecifier, specifierLen);
2353      return false;
2354    }
2355  }
2356
2357  // Check if the field with is non-zero.
2358  const OptionalAmount &Amt = FS.getFieldWidth();
2359  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2360    if (Amt.getConstantAmount() == 0) {
2361      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2362                                                   Amt.getConstantLength());
2363      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2364                           getLocationOfByte(Amt.getStart()),
2365                           /*IsStringLocation*/true, R,
2366                           FixItHint::CreateRemoval(R));
2367    }
2368  }
2369
2370  if (!FS.consumesDataArgument()) {
2371    // FIXME: Technically specifying a precision or field width here
2372    // makes no sense.  Worth issuing a warning at some point.
2373    return true;
2374  }
2375
2376  // Consume the argument.
2377  unsigned argIndex = FS.getArgIndex();
2378  if (argIndex < NumDataArgs) {
2379      // The check to see if the argIndex is valid will come later.
2380      // We set the bit here because we may exit early from this
2381      // function if we encounter some other error.
2382    CoveredArgs.set(argIndex);
2383  }
2384
2385  // Check the length modifier is valid with the given conversion specifier.
2386  const LengthModifier &LM = FS.getLengthModifier();
2387  if (!FS.hasValidLengthModifier()) {
2388    const CharSourceRange &R = getSpecifierRange(LM.getStart(), LM.getLength());
2389    EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2390                         << LM.toString() << CS.toString()
2391                         << getSpecifierRange(startSpecifier, specifierLen),
2392                         getLocationOfByte(LM.getStart()),
2393                         /*IsStringLocation*/true, R,
2394                         FixItHint::CreateRemoval(R));
2395  }
2396
2397  if (!FS.hasStandardLengthModifier())
2398    HandleNonStandardLengthModifier(LM, startSpecifier, specifierLen);
2399  if (!FS.hasStandardConversionSpecifier(S.getLangOptions()))
2400    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
2401  if (!FS.hasStandardLengthConversionCombination())
2402    HandleNonStandardConversionSpecification(LM, CS, startSpecifier,
2403                                             specifierLen);
2404
2405  // The remaining checks depend on the data arguments.
2406  if (HasVAListArg)
2407    return true;
2408
2409  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2410    return false;
2411
2412  // Check that the argument type matches the format specifier.
2413  const Expr *Ex = getDataArg(argIndex);
2414  const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2415  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2416    ScanfSpecifier fixedFS = FS;
2417    bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions(),
2418                                   S.Context);
2419
2420    if (success) {
2421      // Get the fix string from the fixed format specifier.
2422      SmallString<128> buf;
2423      llvm::raw_svector_ostream os(buf);
2424      fixedFS.toString(os);
2425
2426      EmitFormatDiagnostic(
2427        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2428          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2429          << Ex->getSourceRange(),
2430        getLocationOfByte(CS.getStart()),
2431        /*IsStringLocation*/true,
2432        getSpecifierRange(startSpecifier, specifierLen),
2433        FixItHint::CreateReplacement(
2434          getSpecifierRange(startSpecifier, specifierLen),
2435          os.str()));
2436    } else {
2437      EmitFormatDiagnostic(
2438        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2439          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2440          << Ex->getSourceRange(),
2441        getLocationOfByte(CS.getStart()),
2442        /*IsStringLocation*/true,
2443        getSpecifierRange(startSpecifier, specifierLen));
2444    }
2445  }
2446
2447  return true;
2448}
2449
2450void Sema::CheckFormatString(const StringLiteral *FExpr,
2451                             const Expr *OrigFormatExpr,
2452                             Expr **Args, unsigned NumArgs,
2453                             bool HasVAListArg, unsigned format_idx,
2454                             unsigned firstDataArg, FormatStringType Type,
2455                             bool inFunctionCall) {
2456
2457  // CHECK: is the format string a wide literal?
2458  if (!FExpr->isAscii()) {
2459    CheckFormatHandler::EmitFormatDiagnostic(
2460      *this, inFunctionCall, Args[format_idx],
2461      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2462      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2463    return;
2464  }
2465
2466  // Str - The format string.  NOTE: this is NOT null-terminated!
2467  StringRef StrRef = FExpr->getString();
2468  const char *Str = StrRef.data();
2469  unsigned StrLen = StrRef.size();
2470  const unsigned numDataArgs = NumArgs - firstDataArg;
2471
2472  // CHECK: empty format string?
2473  if (StrLen == 0 && numDataArgs > 0) {
2474    CheckFormatHandler::EmitFormatDiagnostic(
2475      *this, inFunctionCall, Args[format_idx],
2476      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2477      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2478    return;
2479  }
2480
2481  if (Type == FST_Printf || Type == FST_NSString) {
2482    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2483                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2484                         Str, HasVAListArg, Args, NumArgs, format_idx,
2485                         inFunctionCall);
2486
2487    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2488                                                  getLangOptions()))
2489      H.DoneProcessing();
2490  } else if (Type == FST_Scanf) {
2491    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2492                        numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2493                        Str, HasVAListArg, Args, NumArgs, format_idx,
2494                        inFunctionCall);
2495
2496    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
2497                                                 getLangOptions()))
2498      H.DoneProcessing();
2499  } // TODO: handle other formats
2500}
2501
2502//===--- CHECK: Standard memory functions ---------------------------------===//
2503
2504/// \brief Determine whether the given type is a dynamic class type (e.g.,
2505/// whether it has a vtable).
2506static bool isDynamicClassType(QualType T) {
2507  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2508    if (CXXRecordDecl *Definition = Record->getDefinition())
2509      if (Definition->isDynamicClass())
2510        return true;
2511
2512  return false;
2513}
2514
2515/// \brief If E is a sizeof expression, returns its argument expression,
2516/// otherwise returns NULL.
2517static const Expr *getSizeOfExprArg(const Expr* E) {
2518  if (const UnaryExprOrTypeTraitExpr *SizeOf =
2519      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2520    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2521      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2522
2523  return 0;
2524}
2525
2526/// \brief If E is a sizeof expression, returns its argument type.
2527static QualType getSizeOfArgType(const Expr* E) {
2528  if (const UnaryExprOrTypeTraitExpr *SizeOf =
2529      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2530    if (SizeOf->getKind() == clang::UETT_SizeOf)
2531      return SizeOf->getTypeOfArgument();
2532
2533  return QualType();
2534}
2535
2536/// \brief Check for dangerous or invalid arguments to memset().
2537///
2538/// This issues warnings on known problematic, dangerous or unspecified
2539/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2540/// function calls.
2541///
2542/// \param Call The call expression to diagnose.
2543void Sema::CheckMemaccessArguments(const CallExpr *Call,
2544                                   unsigned BId,
2545                                   IdentifierInfo *FnName) {
2546  assert(BId != 0);
2547
2548  // It is possible to have a non-standard definition of memset.  Validate
2549  // we have enough arguments, and if not, abort further checking.
2550  unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
2551  if (Call->getNumArgs() < ExpectedNumArgs)
2552    return;
2553
2554  unsigned LastArg = (BId == Builtin::BImemset ||
2555                      BId == Builtin::BIstrndup ? 1 : 2);
2556  unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
2557  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2558
2559  // We have special checking when the length is a sizeof expression.
2560  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2561  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2562  llvm::FoldingSetNodeID SizeOfArgID;
2563
2564  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2565    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2566    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2567
2568    QualType DestTy = Dest->getType();
2569    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2570      QualType PointeeTy = DestPtrTy->getPointeeType();
2571
2572      // Never warn about void type pointers. This can be used to suppress
2573      // false positives.
2574      if (PointeeTy->isVoidType())
2575        continue;
2576
2577      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2578      // actually comparing the expressions for equality. Because computing the
2579      // expression IDs can be expensive, we only do this if the diagnostic is
2580      // enabled.
2581      if (SizeOfArg &&
2582          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2583                                   SizeOfArg->getExprLoc())) {
2584        // We only compute IDs for expressions if the warning is enabled, and
2585        // cache the sizeof arg's ID.
2586        if (SizeOfArgID == llvm::FoldingSetNodeID())
2587          SizeOfArg->Profile(SizeOfArgID, Context, true);
2588        llvm::FoldingSetNodeID DestID;
2589        Dest->Profile(DestID, Context, true);
2590        if (DestID == SizeOfArgID) {
2591          // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2592          //       over sizeof(src) as well.
2593          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2594          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2595            if (UnaryOp->getOpcode() == UO_AddrOf)
2596              ActionIdx = 1; // If its an address-of operator, just remove it.
2597          if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2598            ActionIdx = 2; // If the pointee's size is sizeof(char),
2599                           // suggest an explicit length.
2600          unsigned DestSrcSelect =
2601            (BId == Builtin::BIstrndup ? 1 : ArgIdx);
2602          DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2603                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2604                                << FnName << DestSrcSelect << ActionIdx
2605                                << Dest->getSourceRange()
2606                                << SizeOfArg->getSourceRange());
2607          break;
2608        }
2609      }
2610
2611      // Also check for cases where the sizeof argument is the exact same
2612      // type as the memory argument, and where it points to a user-defined
2613      // record type.
2614      if (SizeOfArgTy != QualType()) {
2615        if (PointeeTy->isRecordType() &&
2616            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2617          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2618                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
2619                                << FnName << SizeOfArgTy << ArgIdx
2620                                << PointeeTy << Dest->getSourceRange()
2621                                << LenExpr->getSourceRange());
2622          break;
2623        }
2624      }
2625
2626      // Always complain about dynamic classes.
2627      if (isDynamicClassType(PointeeTy)) {
2628
2629        unsigned OperationType = 0;
2630        // "overwritten" if we're warning about the destination for any call
2631        // but memcmp; otherwise a verb appropriate to the call.
2632        if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
2633          if (BId == Builtin::BImemcpy)
2634            OperationType = 1;
2635          else if(BId == Builtin::BImemmove)
2636            OperationType = 2;
2637          else if (BId == Builtin::BImemcmp)
2638            OperationType = 3;
2639        }
2640
2641        DiagRuntimeBehavior(
2642          Dest->getExprLoc(), Dest,
2643          PDiag(diag::warn_dyn_class_memaccess)
2644            << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
2645            << FnName << PointeeTy
2646            << OperationType
2647            << Call->getCallee()->getSourceRange());
2648      } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
2649               BId != Builtin::BImemset)
2650        DiagRuntimeBehavior(
2651          Dest->getExprLoc(), Dest,
2652          PDiag(diag::warn_arc_object_memaccess)
2653            << ArgIdx << FnName << PointeeTy
2654            << Call->getCallee()->getSourceRange());
2655      else
2656        continue;
2657
2658      DiagRuntimeBehavior(
2659        Dest->getExprLoc(), Dest,
2660        PDiag(diag::note_bad_memaccess_silence)
2661          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2662      break;
2663    }
2664  }
2665}
2666
2667// A little helper routine: ignore addition and subtraction of integer literals.
2668// This intentionally does not ignore all integer constant expressions because
2669// we don't want to remove sizeof().
2670static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2671  Ex = Ex->IgnoreParenCasts();
2672
2673  for (;;) {
2674    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2675    if (!BO || !BO->isAdditiveOp())
2676      break;
2677
2678    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2679    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2680
2681    if (isa<IntegerLiteral>(RHS))
2682      Ex = LHS;
2683    else if (isa<IntegerLiteral>(LHS))
2684      Ex = RHS;
2685    else
2686      break;
2687  }
2688
2689  return Ex;
2690}
2691
2692// Warn if the user has made the 'size' argument to strlcpy or strlcat
2693// be the size of the source, instead of the destination.
2694void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2695                                    IdentifierInfo *FnName) {
2696
2697  // Don't crash if the user has the wrong number of arguments
2698  if (Call->getNumArgs() != 3)
2699    return;
2700
2701  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2702  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2703  const Expr *CompareWithSrc = NULL;
2704
2705  // Look for 'strlcpy(dst, x, sizeof(x))'
2706  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2707    CompareWithSrc = Ex;
2708  else {
2709    // Look for 'strlcpy(dst, x, strlen(x))'
2710    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2711      if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
2712          && SizeCall->getNumArgs() == 1)
2713        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2714    }
2715  }
2716
2717  if (!CompareWithSrc)
2718    return;
2719
2720  // Determine if the argument to sizeof/strlen is equal to the source
2721  // argument.  In principle there's all kinds of things you could do
2722  // here, for instance creating an == expression and evaluating it with
2723  // EvaluateAsBooleanCondition, but this uses a more direct technique:
2724  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2725  if (!SrcArgDRE)
2726    return;
2727
2728  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2729  if (!CompareWithSrcDRE ||
2730      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2731    return;
2732
2733  const Expr *OriginalSizeArg = Call->getArg(2);
2734  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2735    << OriginalSizeArg->getSourceRange() << FnName;
2736
2737  // Output a FIXIT hint if the destination is an array (rather than a
2738  // pointer to an array).  This could be enhanced to handle some
2739  // pointers if we know the actual size, like if DstArg is 'array+2'
2740  // we could say 'sizeof(array)-2'.
2741  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2742  QualType DstArgTy = DstArg->getType();
2743
2744  // Only handle constant-sized or VLAs, but not flexible members.
2745  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2746    // Only issue the FIXIT for arrays of size > 1.
2747    if (CAT->getSize().getSExtValue() <= 1)
2748      return;
2749  } else if (!DstArgTy->isVariableArrayType()) {
2750    return;
2751  }
2752
2753  SmallString<128> sizeString;
2754  llvm::raw_svector_ostream OS(sizeString);
2755  OS << "sizeof(";
2756  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2757  OS << ")";
2758
2759  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2760    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2761                                    OS.str());
2762}
2763
2764/// Check if two expressions refer to the same declaration.
2765static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
2766  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
2767    if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
2768      return D1->getDecl() == D2->getDecl();
2769  return false;
2770}
2771
2772static const Expr *getStrlenExprArg(const Expr *E) {
2773  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
2774    const FunctionDecl *FD = CE->getDirectCallee();
2775    if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
2776      return 0;
2777    return CE->getArg(0)->IgnoreParenCasts();
2778  }
2779  return 0;
2780}
2781
2782// Warn on anti-patterns as the 'size' argument to strncat.
2783// The correct size argument should look like following:
2784//   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
2785void Sema::CheckStrncatArguments(const CallExpr *CE,
2786                                 IdentifierInfo *FnName) {
2787  // Don't crash if the user has the wrong number of arguments.
2788  if (CE->getNumArgs() < 3)
2789    return;
2790  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
2791  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
2792  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
2793
2794  // Identify common expressions, which are wrongly used as the size argument
2795  // to strncat and may lead to buffer overflows.
2796  unsigned PatternType = 0;
2797  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
2798    // - sizeof(dst)
2799    if (referToTheSameDecl(SizeOfArg, DstArg))
2800      PatternType = 1;
2801    // - sizeof(src)
2802    else if (referToTheSameDecl(SizeOfArg, SrcArg))
2803      PatternType = 2;
2804  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
2805    if (BE->getOpcode() == BO_Sub) {
2806      const Expr *L = BE->getLHS()->IgnoreParenCasts();
2807      const Expr *R = BE->getRHS()->IgnoreParenCasts();
2808      // - sizeof(dst) - strlen(dst)
2809      if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
2810          referToTheSameDecl(DstArg, getStrlenExprArg(R)))
2811        PatternType = 1;
2812      // - sizeof(src) - (anything)
2813      else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
2814        PatternType = 2;
2815    }
2816  }
2817
2818  if (PatternType == 0)
2819    return;
2820
2821  // Generate the diagnostic.
2822  SourceLocation SL = LenArg->getLocStart();
2823  SourceRange SR = LenArg->getSourceRange();
2824  SourceManager &SM  = PP.getSourceManager();
2825
2826  // If the function is defined as a builtin macro, do not show macro expansion.
2827  if (SM.isMacroArgExpansion(SL)) {
2828    SL = SM.getSpellingLoc(SL);
2829    SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
2830                     SM.getSpellingLoc(SR.getEnd()));
2831  }
2832
2833  if (PatternType == 1)
2834    Diag(SL, diag::warn_strncat_large_size) << SR;
2835  else
2836    Diag(SL, diag::warn_strncat_src_size) << SR;
2837
2838  // Output a FIXIT hint if the destination is an array (rather than a
2839  // pointer to an array).  This could be enhanced to handle some
2840  // pointers if we know the actual size, like if DstArg is 'array+2'
2841  // we could say 'sizeof(array)-2'.
2842  QualType DstArgTy = DstArg->getType();
2843
2844  // Only handle constant-sized or VLAs, but not flexible members.
2845  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2846    // Only issue the FIXIT for arrays of size > 1.
2847    if (CAT->getSize().getSExtValue() <= 1)
2848      return;
2849  } else if (!DstArgTy->isVariableArrayType()) {
2850    return;
2851  }
2852
2853  SmallString<128> sizeString;
2854  llvm::raw_svector_ostream OS(sizeString);
2855  OS << "sizeof(";
2856  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2857  OS << ") - ";
2858  OS << "strlen(";
2859  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2860  OS << ") - 1";
2861
2862  Diag(SL, diag::note_strncat_wrong_size)
2863    << FixItHint::CreateReplacement(SR, OS.str());
2864}
2865
2866//===--- CHECK: Return Address of Stack Variable --------------------------===//
2867
2868static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2869static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2870
2871/// CheckReturnStackAddr - Check if a return statement returns the address
2872///   of a stack variable.
2873void
2874Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2875                           SourceLocation ReturnLoc) {
2876
2877  Expr *stackE = 0;
2878  SmallVector<DeclRefExpr *, 8> refVars;
2879
2880  // Perform checking for returned stack addresses, local blocks,
2881  // label addresses or references to temporaries.
2882  if (lhsType->isPointerType() ||
2883      (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2884    stackE = EvalAddr(RetValExp, refVars);
2885  } else if (lhsType->isReferenceType()) {
2886    stackE = EvalVal(RetValExp, refVars);
2887  }
2888
2889  if (stackE == 0)
2890    return; // Nothing suspicious was found.
2891
2892  SourceLocation diagLoc;
2893  SourceRange diagRange;
2894  if (refVars.empty()) {
2895    diagLoc = stackE->getLocStart();
2896    diagRange = stackE->getSourceRange();
2897  } else {
2898    // We followed through a reference variable. 'stackE' contains the
2899    // problematic expression but we will warn at the return statement pointing
2900    // at the reference variable. We will later display the "trail" of
2901    // reference variables using notes.
2902    diagLoc = refVars[0]->getLocStart();
2903    diagRange = refVars[0]->getSourceRange();
2904  }
2905
2906  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2907    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2908                                             : diag::warn_ret_stack_addr)
2909     << DR->getDecl()->getDeclName() << diagRange;
2910  } else if (isa<BlockExpr>(stackE)) { // local block.
2911    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2912  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2913    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2914  } else { // local temporary.
2915    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2916                                             : diag::warn_ret_local_temp_addr)
2917     << diagRange;
2918  }
2919
2920  // Display the "trail" of reference variables that we followed until we
2921  // found the problematic expression using notes.
2922  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2923    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2924    // If this var binds to another reference var, show the range of the next
2925    // var, otherwise the var binds to the problematic expression, in which case
2926    // show the range of the expression.
2927    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2928                                  : stackE->getSourceRange();
2929    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2930      << VD->getDeclName() << range;
2931  }
2932}
2933
2934/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2935///  check if the expression in a return statement evaluates to an address
2936///  to a location on the stack, a local block, an address of a label, or a
2937///  reference to local temporary. The recursion is used to traverse the
2938///  AST of the return expression, with recursion backtracking when we
2939///  encounter a subexpression that (1) clearly does not lead to one of the
2940///  above problematic expressions (2) is something we cannot determine leads to
2941///  a problematic expression based on such local checking.
2942///
2943///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2944///  the expression that they point to. Such variables are added to the
2945///  'refVars' vector so that we know what the reference variable "trail" was.
2946///
2947///  EvalAddr processes expressions that are pointers that are used as
2948///  references (and not L-values).  EvalVal handles all other values.
2949///  At the base case of the recursion is a check for the above problematic
2950///  expressions.
2951///
2952///  This implementation handles:
2953///
2954///   * pointer-to-pointer casts
2955///   * implicit conversions from array references to pointers
2956///   * taking the address of fields
2957///   * arbitrary interplay between "&" and "*" operators
2958///   * pointer arithmetic from an address of a stack variable
2959///   * taking the address of an array element where the array is on the stack
2960static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2961  if (E->isTypeDependent())
2962      return NULL;
2963
2964  // We should only be called for evaluating pointer expressions.
2965  assert((E->getType()->isAnyPointerType() ||
2966          E->getType()->isBlockPointerType() ||
2967          E->getType()->isObjCQualifiedIdType()) &&
2968         "EvalAddr only works on pointers");
2969
2970  E = E->IgnoreParens();
2971
2972  // Our "symbolic interpreter" is just a dispatch off the currently
2973  // viewed AST node.  We then recursively traverse the AST by calling
2974  // EvalAddr and EvalVal appropriately.
2975  switch (E->getStmtClass()) {
2976  case Stmt::DeclRefExprClass: {
2977    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2978
2979    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2980      // If this is a reference variable, follow through to the expression that
2981      // it points to.
2982      if (V->hasLocalStorage() &&
2983          V->getType()->isReferenceType() && V->hasInit()) {
2984        // Add the reference variable to the "trail".
2985        refVars.push_back(DR);
2986        return EvalAddr(V->getInit(), refVars);
2987      }
2988
2989    return NULL;
2990  }
2991
2992  case Stmt::UnaryOperatorClass: {
2993    // The only unary operator that make sense to handle here
2994    // is AddrOf.  All others don't make sense as pointers.
2995    UnaryOperator *U = cast<UnaryOperator>(E);
2996
2997    if (U->getOpcode() == UO_AddrOf)
2998      return EvalVal(U->getSubExpr(), refVars);
2999    else
3000      return NULL;
3001  }
3002
3003  case Stmt::BinaryOperatorClass: {
3004    // Handle pointer arithmetic.  All other binary operators are not valid
3005    // in this context.
3006    BinaryOperator *B = cast<BinaryOperator>(E);
3007    BinaryOperatorKind op = B->getOpcode();
3008
3009    if (op != BO_Add && op != BO_Sub)
3010      return NULL;
3011
3012    Expr *Base = B->getLHS();
3013
3014    // Determine which argument is the real pointer base.  It could be
3015    // the RHS argument instead of the LHS.
3016    if (!Base->getType()->isPointerType()) Base = B->getRHS();
3017
3018    assert (Base->getType()->isPointerType());
3019    return EvalAddr(Base, refVars);
3020  }
3021
3022  // For conditional operators we need to see if either the LHS or RHS are
3023  // valid DeclRefExpr*s.  If one of them is valid, we return it.
3024  case Stmt::ConditionalOperatorClass: {
3025    ConditionalOperator *C = cast<ConditionalOperator>(E);
3026
3027    // Handle the GNU extension for missing LHS.
3028    if (Expr *lhsExpr = C->getLHS()) {
3029    // In C++, we can have a throw-expression, which has 'void' type.
3030      if (!lhsExpr->getType()->isVoidType())
3031        if (Expr* LHS = EvalAddr(lhsExpr, refVars))
3032          return LHS;
3033    }
3034
3035    // In C++, we can have a throw-expression, which has 'void' type.
3036    if (C->getRHS()->getType()->isVoidType())
3037      return NULL;
3038
3039    return EvalAddr(C->getRHS(), refVars);
3040  }
3041
3042  case Stmt::BlockExprClass:
3043    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
3044      return E; // local block.
3045    return NULL;
3046
3047  case Stmt::AddrLabelExprClass:
3048    return E; // address of label.
3049
3050  case Stmt::ExprWithCleanupsClass:
3051    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3052
3053  // For casts, we need to handle conversions from arrays to
3054  // pointer values, and pointer-to-pointer conversions.
3055  case Stmt::ImplicitCastExprClass:
3056  case Stmt::CStyleCastExprClass:
3057  case Stmt::CXXFunctionalCastExprClass:
3058  case Stmt::ObjCBridgedCastExprClass:
3059  case Stmt::CXXStaticCastExprClass:
3060  case Stmt::CXXDynamicCastExprClass:
3061  case Stmt::CXXConstCastExprClass:
3062  case Stmt::CXXReinterpretCastExprClass: {
3063    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
3064    switch (cast<CastExpr>(E)->getCastKind()) {
3065    case CK_BitCast:
3066    case CK_LValueToRValue:
3067    case CK_NoOp:
3068    case CK_BaseToDerived:
3069    case CK_DerivedToBase:
3070    case CK_UncheckedDerivedToBase:
3071    case CK_Dynamic:
3072    case CK_CPointerToObjCPointerCast:
3073    case CK_BlockPointerToObjCPointerCast:
3074    case CK_AnyPointerToBlockPointerCast:
3075      return EvalAddr(SubExpr, refVars);
3076
3077    case CK_ArrayToPointerDecay:
3078      return EvalVal(SubExpr, refVars);
3079
3080    default:
3081      return 0;
3082    }
3083  }
3084
3085  case Stmt::MaterializeTemporaryExprClass:
3086    if (Expr *Result = EvalAddr(
3087                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3088                                refVars))
3089      return Result;
3090
3091    return E;
3092
3093  // Everything else: we simply don't reason about them.
3094  default:
3095    return NULL;
3096  }
3097}
3098
3099
3100///  EvalVal - This function is complements EvalAddr in the mutual recursion.
3101///   See the comments for EvalAddr for more details.
3102static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
3103do {
3104  // We should only be called for evaluating non-pointer expressions, or
3105  // expressions with a pointer type that are not used as references but instead
3106  // are l-values (e.g., DeclRefExpr with a pointer type).
3107
3108  // Our "symbolic interpreter" is just a dispatch off the currently
3109  // viewed AST node.  We then recursively traverse the AST by calling
3110  // EvalAddr and EvalVal appropriately.
3111
3112  E = E->IgnoreParens();
3113  switch (E->getStmtClass()) {
3114  case Stmt::ImplicitCastExprClass: {
3115    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
3116    if (IE->getValueKind() == VK_LValue) {
3117      E = IE->getSubExpr();
3118      continue;
3119    }
3120    return NULL;
3121  }
3122
3123  case Stmt::ExprWithCleanupsClass:
3124    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
3125
3126  case Stmt::DeclRefExprClass: {
3127    // When we hit a DeclRefExpr we are looking at code that refers to a
3128    // variable's name. If it's not a reference variable we check if it has
3129    // local storage within the function, and if so, return the expression.
3130    DeclRefExpr *DR = cast<DeclRefExpr>(E);
3131
3132    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
3133      if (V->hasLocalStorage()) {
3134        if (!V->getType()->isReferenceType())
3135          return DR;
3136
3137        // Reference variable, follow through to the expression that
3138        // it points to.
3139        if (V->hasInit()) {
3140          // Add the reference variable to the "trail".
3141          refVars.push_back(DR);
3142          return EvalVal(V->getInit(), refVars);
3143        }
3144      }
3145
3146    return NULL;
3147  }
3148
3149  case Stmt::UnaryOperatorClass: {
3150    // The only unary operator that make sense to handle here
3151    // is Deref.  All others don't resolve to a "name."  This includes
3152    // handling all sorts of rvalues passed to a unary operator.
3153    UnaryOperator *U = cast<UnaryOperator>(E);
3154
3155    if (U->getOpcode() == UO_Deref)
3156      return EvalAddr(U->getSubExpr(), refVars);
3157
3158    return NULL;
3159  }
3160
3161  case Stmt::ArraySubscriptExprClass: {
3162    // Array subscripts are potential references to data on the stack.  We
3163    // retrieve the DeclRefExpr* for the array variable if it indeed
3164    // has local storage.
3165    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
3166  }
3167
3168  case Stmt::ConditionalOperatorClass: {
3169    // For conditional operators we need to see if either the LHS or RHS are
3170    // non-NULL Expr's.  If one is non-NULL, we return it.
3171    ConditionalOperator *C = cast<ConditionalOperator>(E);
3172
3173    // Handle the GNU extension for missing LHS.
3174    if (Expr *lhsExpr = C->getLHS())
3175      if (Expr *LHS = EvalVal(lhsExpr, refVars))
3176        return LHS;
3177
3178    return EvalVal(C->getRHS(), refVars);
3179  }
3180
3181  // Accesses to members are potential references to data on the stack.
3182  case Stmt::MemberExprClass: {
3183    MemberExpr *M = cast<MemberExpr>(E);
3184
3185    // Check for indirect access.  We only want direct field accesses.
3186    if (M->isArrow())
3187      return NULL;
3188
3189    // Check whether the member type is itself a reference, in which case
3190    // we're not going to refer to the member, but to what the member refers to.
3191    if (M->getMemberDecl()->getType()->isReferenceType())
3192      return NULL;
3193
3194    return EvalVal(M->getBase(), refVars);
3195  }
3196
3197  case Stmt::MaterializeTemporaryExprClass:
3198    if (Expr *Result = EvalVal(
3199                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3200                               refVars))
3201      return Result;
3202
3203    return E;
3204
3205  default:
3206    // Check that we don't return or take the address of a reference to a
3207    // temporary. This is only useful in C++.
3208    if (!E->isTypeDependent() && E->isRValue())
3209      return E;
3210
3211    // Everything else: we simply don't reason about them.
3212    return NULL;
3213  }
3214} while (true);
3215}
3216
3217//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3218
3219/// Check for comparisons of floating point operands using != and ==.
3220/// Issue a warning if these are no self-comparisons, as they are not likely
3221/// to do what the programmer intended.
3222void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
3223  bool EmitWarning = true;
3224
3225  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3226  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
3227
3228  // Special case: check for x == x (which is OK).
3229  // Do not emit warnings for such cases.
3230  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3231    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3232      if (DRL->getDecl() == DRR->getDecl())
3233        EmitWarning = false;
3234
3235
3236  // Special case: check for comparisons against literals that can be exactly
3237  //  represented by APFloat.  In such cases, do not emit a warning.  This
3238  //  is a heuristic: often comparison against such literals are used to
3239  //  detect if a value in a variable has not changed.  This clearly can
3240  //  lead to false negatives.
3241  if (EmitWarning) {
3242    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3243      if (FLL->isExact())
3244        EmitWarning = false;
3245    } else
3246      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3247        if (FLR->isExact())
3248          EmitWarning = false;
3249    }
3250  }
3251
3252  // Check for comparisons with builtin types.
3253  if (EmitWarning)
3254    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3255      if (CL->isBuiltinCall())
3256        EmitWarning = false;
3257
3258  if (EmitWarning)
3259    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3260      if (CR->isBuiltinCall())
3261        EmitWarning = false;
3262
3263  // Emit the diagnostic.
3264  if (EmitWarning)
3265    Diag(Loc, diag::warn_floatingpoint_eq)
3266      << LHS->getSourceRange() << RHS->getSourceRange();
3267}
3268
3269//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3270//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
3271
3272namespace {
3273
3274/// Structure recording the 'active' range of an integer-valued
3275/// expression.
3276struct IntRange {
3277  /// The number of bits active in the int.
3278  unsigned Width;
3279
3280  /// True if the int is known not to have negative values.
3281  bool NonNegative;
3282
3283  IntRange(unsigned Width, bool NonNegative)
3284    : Width(Width), NonNegative(NonNegative)
3285  {}
3286
3287  /// Returns the range of the bool type.
3288  static IntRange forBoolType() {
3289    return IntRange(1, true);
3290  }
3291
3292  /// Returns the range of an opaque value of the given integral type.
3293  static IntRange forValueOfType(ASTContext &C, QualType T) {
3294    return forValueOfCanonicalType(C,
3295                          T->getCanonicalTypeInternal().getTypePtr());
3296  }
3297
3298  /// Returns the range of an opaque value of a canonical integral type.
3299  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
3300    assert(T->isCanonicalUnqualified());
3301
3302    if (const VectorType *VT = dyn_cast<VectorType>(T))
3303      T = VT->getElementType().getTypePtr();
3304    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3305      T = CT->getElementType().getTypePtr();
3306
3307    // For enum types, use the known bit width of the enumerators.
3308    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3309      EnumDecl *Enum = ET->getDecl();
3310      if (!Enum->isCompleteDefinition())
3311        return IntRange(C.getIntWidth(QualType(T, 0)), false);
3312
3313      unsigned NumPositive = Enum->getNumPositiveBits();
3314      unsigned NumNegative = Enum->getNumNegativeBits();
3315
3316      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3317    }
3318
3319    const BuiltinType *BT = cast<BuiltinType>(T);
3320    assert(BT->isInteger());
3321
3322    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3323  }
3324
3325  /// Returns the "target" range of a canonical integral type, i.e.
3326  /// the range of values expressible in the type.
3327  ///
3328  /// This matches forValueOfCanonicalType except that enums have the
3329  /// full range of their type, not the range of their enumerators.
3330  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3331    assert(T->isCanonicalUnqualified());
3332
3333    if (const VectorType *VT = dyn_cast<VectorType>(T))
3334      T = VT->getElementType().getTypePtr();
3335    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3336      T = CT->getElementType().getTypePtr();
3337    if (const EnumType *ET = dyn_cast<EnumType>(T))
3338      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
3339
3340    const BuiltinType *BT = cast<BuiltinType>(T);
3341    assert(BT->isInteger());
3342
3343    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3344  }
3345
3346  /// Returns the supremum of two ranges: i.e. their conservative merge.
3347  static IntRange join(IntRange L, IntRange R) {
3348    return IntRange(std::max(L.Width, R.Width),
3349                    L.NonNegative && R.NonNegative);
3350  }
3351
3352  /// Returns the infinum of two ranges: i.e. their aggressive merge.
3353  static IntRange meet(IntRange L, IntRange R) {
3354    return IntRange(std::min(L.Width, R.Width),
3355                    L.NonNegative || R.NonNegative);
3356  }
3357};
3358
3359static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
3360                              unsigned MaxWidth) {
3361  if (value.isSigned() && value.isNegative())
3362    return IntRange(value.getMinSignedBits(), false);
3363
3364  if (value.getBitWidth() > MaxWidth)
3365    value = value.trunc(MaxWidth);
3366
3367  // isNonNegative() just checks the sign bit without considering
3368  // signedness.
3369  return IntRange(value.getActiveBits(), true);
3370}
3371
3372static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3373                              unsigned MaxWidth) {
3374  if (result.isInt())
3375    return GetValueRange(C, result.getInt(), MaxWidth);
3376
3377  if (result.isVector()) {
3378    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3379    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3380      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3381      R = IntRange::join(R, El);
3382    }
3383    return R;
3384  }
3385
3386  if (result.isComplexInt()) {
3387    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3388    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3389    return IntRange::join(R, I);
3390  }
3391
3392  // This can happen with lossless casts to intptr_t of "based" lvalues.
3393  // Assume it might use arbitrary bits.
3394  // FIXME: The only reason we need to pass the type in here is to get
3395  // the sign right on this one case.  It would be nice if APValue
3396  // preserved this.
3397  assert(result.isLValue() || result.isAddrLabelDiff());
3398  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
3399}
3400
3401/// Pseudo-evaluate the given integer expression, estimating the
3402/// range of values it might take.
3403///
3404/// \param MaxWidth - the width to which the value will be truncated
3405static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3406  E = E->IgnoreParens();
3407
3408  // Try a full evaluation first.
3409  Expr::EvalResult result;
3410  if (E->EvaluateAsRValue(result, C))
3411    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
3412
3413  // I think we only want to look through implicit casts here; if the
3414  // user has an explicit widening cast, we should treat the value as
3415  // being of the new, wider type.
3416  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
3417    if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
3418      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3419
3420    IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
3421
3422    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
3423
3424    // Assume that non-integer casts can span the full range of the type.
3425    if (!isIntegerCast)
3426      return OutputTypeRange;
3427
3428    IntRange SubRange
3429      = GetExprRange(C, CE->getSubExpr(),
3430                     std::min(MaxWidth, OutputTypeRange.Width));
3431
3432    // Bail out if the subexpr's range is as wide as the cast type.
3433    if (SubRange.Width >= OutputTypeRange.Width)
3434      return OutputTypeRange;
3435
3436    // Otherwise, we take the smaller width, and we're non-negative if
3437    // either the output type or the subexpr is.
3438    return IntRange(SubRange.Width,
3439                    SubRange.NonNegative || OutputTypeRange.NonNegative);
3440  }
3441
3442  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3443    // If we can fold the condition, just take that operand.
3444    bool CondResult;
3445    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3446      return GetExprRange(C, CondResult ? CO->getTrueExpr()
3447                                        : CO->getFalseExpr(),
3448                          MaxWidth);
3449
3450    // Otherwise, conservatively merge.
3451    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3452    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3453    return IntRange::join(L, R);
3454  }
3455
3456  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3457    switch (BO->getOpcode()) {
3458
3459    // Boolean-valued operations are single-bit and positive.
3460    case BO_LAnd:
3461    case BO_LOr:
3462    case BO_LT:
3463    case BO_GT:
3464    case BO_LE:
3465    case BO_GE:
3466    case BO_EQ:
3467    case BO_NE:
3468      return IntRange::forBoolType();
3469
3470    // The type of the assignments is the type of the LHS, so the RHS
3471    // is not necessarily the same type.
3472    case BO_MulAssign:
3473    case BO_DivAssign:
3474    case BO_RemAssign:
3475    case BO_AddAssign:
3476    case BO_SubAssign:
3477    case BO_XorAssign:
3478    case BO_OrAssign:
3479      // TODO: bitfields?
3480      return IntRange::forValueOfType(C, E->getType());
3481
3482    // Simple assignments just pass through the RHS, which will have
3483    // been coerced to the LHS type.
3484    case BO_Assign:
3485      // TODO: bitfields?
3486      return GetExprRange(C, BO->getRHS(), MaxWidth);
3487
3488    // Operations with opaque sources are black-listed.
3489    case BO_PtrMemD:
3490    case BO_PtrMemI:
3491      return IntRange::forValueOfType(C, E->getType());
3492
3493    // Bitwise-and uses the *infinum* of the two source ranges.
3494    case BO_And:
3495    case BO_AndAssign:
3496      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3497                            GetExprRange(C, BO->getRHS(), MaxWidth));
3498
3499    // Left shift gets black-listed based on a judgement call.
3500    case BO_Shl:
3501      // ...except that we want to treat '1 << (blah)' as logically
3502      // positive.  It's an important idiom.
3503      if (IntegerLiteral *I
3504            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3505        if (I->getValue() == 1) {
3506          IntRange R = IntRange::forValueOfType(C, E->getType());
3507          return IntRange(R.Width, /*NonNegative*/ true);
3508        }
3509      }
3510      // fallthrough
3511
3512    case BO_ShlAssign:
3513      return IntRange::forValueOfType(C, E->getType());
3514
3515    // Right shift by a constant can narrow its left argument.
3516    case BO_Shr:
3517    case BO_ShrAssign: {
3518      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3519
3520      // If the shift amount is a positive constant, drop the width by
3521      // that much.
3522      llvm::APSInt shift;
3523      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3524          shift.isNonNegative()) {
3525        unsigned zext = shift.getZExtValue();
3526        if (zext >= L.Width)
3527          L.Width = (L.NonNegative ? 0 : 1);
3528        else
3529          L.Width -= zext;
3530      }
3531
3532      return L;
3533    }
3534
3535    // Comma acts as its right operand.
3536    case BO_Comma:
3537      return GetExprRange(C, BO->getRHS(), MaxWidth);
3538
3539    // Black-list pointer subtractions.
3540    case BO_Sub:
3541      if (BO->getLHS()->getType()->isPointerType())
3542        return IntRange::forValueOfType(C, E->getType());
3543      break;
3544
3545    // The width of a division result is mostly determined by the size
3546    // of the LHS.
3547    case BO_Div: {
3548      // Don't 'pre-truncate' the operands.
3549      unsigned opWidth = C.getIntWidth(E->getType());
3550      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3551
3552      // If the divisor is constant, use that.
3553      llvm::APSInt divisor;
3554      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3555        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3556        if (log2 >= L.Width)
3557          L.Width = (L.NonNegative ? 0 : 1);
3558        else
3559          L.Width = std::min(L.Width - log2, MaxWidth);
3560        return L;
3561      }
3562
3563      // Otherwise, just use the LHS's width.
3564      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3565      return IntRange(L.Width, L.NonNegative && R.NonNegative);
3566    }
3567
3568    // The result of a remainder can't be larger than the result of
3569    // either side.
3570    case BO_Rem: {
3571      // Don't 'pre-truncate' the operands.
3572      unsigned opWidth = C.getIntWidth(E->getType());
3573      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3574      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3575
3576      IntRange meet = IntRange::meet(L, R);
3577      meet.Width = std::min(meet.Width, MaxWidth);
3578      return meet;
3579    }
3580
3581    // The default behavior is okay for these.
3582    case BO_Mul:
3583    case BO_Add:
3584    case BO_Xor:
3585    case BO_Or:
3586      break;
3587    }
3588
3589    // The default case is to treat the operation as if it were closed
3590    // on the narrowest type that encompasses both operands.
3591    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3592    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3593    return IntRange::join(L, R);
3594  }
3595
3596  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3597    switch (UO->getOpcode()) {
3598    // Boolean-valued operations are white-listed.
3599    case UO_LNot:
3600      return IntRange::forBoolType();
3601
3602    // Operations with opaque sources are black-listed.
3603    case UO_Deref:
3604    case UO_AddrOf: // should be impossible
3605      return IntRange::forValueOfType(C, E->getType());
3606
3607    default:
3608      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3609    }
3610  }
3611
3612  if (dyn_cast<OffsetOfExpr>(E)) {
3613    IntRange::forValueOfType(C, E->getType());
3614  }
3615
3616  if (FieldDecl *BitField = E->getBitField())
3617    return IntRange(BitField->getBitWidthValue(C),
3618                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
3619
3620  return IntRange::forValueOfType(C, E->getType());
3621}
3622
3623static IntRange GetExprRange(ASTContext &C, Expr *E) {
3624  return GetExprRange(C, E, C.getIntWidth(E->getType()));
3625}
3626
3627/// Checks whether the given value, which currently has the given
3628/// source semantics, has the same value when coerced through the
3629/// target semantics.
3630static bool IsSameFloatAfterCast(const llvm::APFloat &value,
3631                                 const llvm::fltSemantics &Src,
3632                                 const llvm::fltSemantics &Tgt) {
3633  llvm::APFloat truncated = value;
3634
3635  bool ignored;
3636  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3637  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3638
3639  return truncated.bitwiseIsEqual(value);
3640}
3641
3642/// Checks whether the given value, which currently has the given
3643/// source semantics, has the same value when coerced through the
3644/// target semantics.
3645///
3646/// The value might be a vector of floats (or a complex number).
3647static bool IsSameFloatAfterCast(const APValue &value,
3648                                 const llvm::fltSemantics &Src,
3649                                 const llvm::fltSemantics &Tgt) {
3650  if (value.isFloat())
3651    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3652
3653  if (value.isVector()) {
3654    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3655      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3656        return false;
3657    return true;
3658  }
3659
3660  assert(value.isComplexFloat());
3661  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3662          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3663}
3664
3665static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3666
3667static bool IsZero(Sema &S, Expr *E) {
3668  // Suppress cases where we are comparing against an enum constant.
3669  if (const DeclRefExpr *DR =
3670      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3671    if (isa<EnumConstantDecl>(DR->getDecl()))
3672      return false;
3673
3674  // Suppress cases where the '0' value is expanded from a macro.
3675  if (E->getLocStart().isMacroID())
3676    return false;
3677
3678  llvm::APSInt Value;
3679  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3680}
3681
3682static bool HasEnumType(Expr *E) {
3683  // Strip off implicit integral promotions.
3684  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3685    if (ICE->getCastKind() != CK_IntegralCast &&
3686        ICE->getCastKind() != CK_NoOp)
3687      break;
3688    E = ICE->getSubExpr();
3689  }
3690
3691  return E->getType()->isEnumeralType();
3692}
3693
3694static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3695  BinaryOperatorKind op = E->getOpcode();
3696  if (E->isValueDependent())
3697    return;
3698
3699  if (op == BO_LT && IsZero(S, E->getRHS())) {
3700    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3701      << "< 0" << "false" << HasEnumType(E->getLHS())
3702      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3703  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3704    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3705      << ">= 0" << "true" << HasEnumType(E->getLHS())
3706      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3707  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3708    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3709      << "0 >" << "false" << HasEnumType(E->getRHS())
3710      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3711  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3712    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3713      << "0 <=" << "true" << HasEnumType(E->getRHS())
3714      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3715  }
3716}
3717
3718/// Analyze the operands of the given comparison.  Implements the
3719/// fallback case from AnalyzeComparison.
3720static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3721  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3722  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3723}
3724
3725/// \brief Implements -Wsign-compare.
3726///
3727/// \param E the binary operator to check for warnings
3728static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3729  // The type the comparison is being performed in.
3730  QualType T = E->getLHS()->getType();
3731  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3732         && "comparison with mismatched types");
3733
3734  // We don't do anything special if this isn't an unsigned integral
3735  // comparison:  we're only interested in integral comparisons, and
3736  // signed comparisons only happen in cases we don't care to warn about.
3737  //
3738  // We also don't care about value-dependent expressions or expressions
3739  // whose result is a constant.
3740  if (!T->hasUnsignedIntegerRepresentation()
3741      || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3742    return AnalyzeImpConvsInComparison(S, E);
3743
3744  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3745  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3746
3747  // Check to see if one of the (unmodified) operands is of different
3748  // signedness.
3749  Expr *signedOperand, *unsignedOperand;
3750  if (LHS->getType()->hasSignedIntegerRepresentation()) {
3751    assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3752           "unsigned comparison between two signed integer expressions?");
3753    signedOperand = LHS;
3754    unsignedOperand = RHS;
3755  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3756    signedOperand = RHS;
3757    unsignedOperand = LHS;
3758  } else {
3759    CheckTrivialUnsignedComparison(S, E);
3760    return AnalyzeImpConvsInComparison(S, E);
3761  }
3762
3763  // Otherwise, calculate the effective range of the signed operand.
3764  IntRange signedRange = GetExprRange(S.Context, signedOperand);
3765
3766  // Go ahead and analyze implicit conversions in the operands.  Note
3767  // that we skip the implicit conversions on both sides.
3768  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3769  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3770
3771  // If the signed range is non-negative, -Wsign-compare won't fire,
3772  // but we should still check for comparisons which are always true
3773  // or false.
3774  if (signedRange.NonNegative)
3775    return CheckTrivialUnsignedComparison(S, E);
3776
3777  // For (in)equality comparisons, if the unsigned operand is a
3778  // constant which cannot collide with a overflowed signed operand,
3779  // then reinterpreting the signed operand as unsigned will not
3780  // change the result of the comparison.
3781  if (E->isEqualityOp()) {
3782    unsigned comparisonWidth = S.Context.getIntWidth(T);
3783    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3784
3785    // We should never be unable to prove that the unsigned operand is
3786    // non-negative.
3787    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3788
3789    if (unsignedRange.Width < comparisonWidth)
3790      return;
3791  }
3792
3793  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3794    << LHS->getType() << RHS->getType()
3795    << LHS->getSourceRange() << RHS->getSourceRange();
3796}
3797
3798/// Analyzes an attempt to assign the given value to a bitfield.
3799///
3800/// Returns true if there was something fishy about the attempt.
3801static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3802                                      SourceLocation InitLoc) {
3803  assert(Bitfield->isBitField());
3804  if (Bitfield->isInvalidDecl())
3805    return false;
3806
3807  // White-list bool bitfields.
3808  if (Bitfield->getType()->isBooleanType())
3809    return false;
3810
3811  // Ignore value- or type-dependent expressions.
3812  if (Bitfield->getBitWidth()->isValueDependent() ||
3813      Bitfield->getBitWidth()->isTypeDependent() ||
3814      Init->isValueDependent() ||
3815      Init->isTypeDependent())
3816    return false;
3817
3818  Expr *OriginalInit = Init->IgnoreParenImpCasts();
3819
3820  llvm::APSInt Value;
3821  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
3822    return false;
3823
3824  unsigned OriginalWidth = Value.getBitWidth();
3825  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3826
3827  if (OriginalWidth <= FieldWidth)
3828    return false;
3829
3830  // Compute the value which the bitfield will contain.
3831  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3832  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
3833
3834  // Check whether the stored value is equal to the original value.
3835  TruncatedValue = TruncatedValue.extend(OriginalWidth);
3836  if (Value == TruncatedValue)
3837    return false;
3838
3839  // Special-case bitfields of width 1: booleans are naturally 0/1, and
3840  // therefore don't strictly fit into a signed bitfield of width 1.
3841  if (FieldWidth == 1 && Value == 1)
3842    return false;
3843
3844  std::string PrettyValue = Value.toString(10);
3845  std::string PrettyTrunc = TruncatedValue.toString(10);
3846
3847  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3848    << PrettyValue << PrettyTrunc << OriginalInit->getType()
3849    << Init->getSourceRange();
3850
3851  return true;
3852}
3853
3854/// Analyze the given simple or compound assignment for warning-worthy
3855/// operations.
3856static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3857  // Just recurse on the LHS.
3858  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3859
3860  // We want to recurse on the RHS as normal unless we're assigning to
3861  // a bitfield.
3862  if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3863    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3864                                  E->getOperatorLoc())) {
3865      // Recurse, ignoring any implicit conversions on the RHS.
3866      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3867                                        E->getOperatorLoc());
3868    }
3869  }
3870
3871  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3872}
3873
3874/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3875static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3876                            SourceLocation CContext, unsigned diag,
3877                            bool pruneControlFlow = false) {
3878  if (pruneControlFlow) {
3879    S.DiagRuntimeBehavior(E->getExprLoc(), E,
3880                          S.PDiag(diag)
3881                            << SourceType << T << E->getSourceRange()
3882                            << SourceRange(CContext));
3883    return;
3884  }
3885  S.Diag(E->getExprLoc(), diag)
3886    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3887}
3888
3889/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3890static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
3891                            SourceLocation CContext, unsigned diag,
3892                            bool pruneControlFlow = false) {
3893  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
3894}
3895
3896/// Diagnose an implicit cast from a literal expression. Does not warn when the
3897/// cast wouldn't lose information.
3898void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3899                                    SourceLocation CContext) {
3900  // Try to convert the literal exactly to an integer. If we can, don't warn.
3901  bool isExact = false;
3902  const llvm::APFloat &Value = FL->getValue();
3903  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3904                            T->hasUnsignedIntegerRepresentation());
3905  if (Value.convertToInteger(IntegerValue,
3906                             llvm::APFloat::rmTowardZero, &isExact)
3907      == llvm::APFloat::opOK && isExact)
3908    return;
3909
3910  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3911    << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3912}
3913
3914std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3915  if (!Range.Width) return "0";
3916
3917  llvm::APSInt ValueInRange = Value;
3918  ValueInRange.setIsSigned(!Range.NonNegative);
3919  ValueInRange = ValueInRange.trunc(Range.Width);
3920  return ValueInRange.toString(10);
3921}
3922
3923void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3924                             SourceLocation CC, bool *ICContext = 0) {
3925  if (E->isTypeDependent() || E->isValueDependent()) return;
3926
3927  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3928  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3929  if (Source == Target) return;
3930  if (Target->isDependentType()) return;
3931
3932  // If the conversion context location is invalid don't complain. We also
3933  // don't want to emit a warning if the issue occurs from the expansion of
3934  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3935  // delay this check as long as possible. Once we detect we are in that
3936  // scenario, we just return.
3937  if (CC.isInvalid())
3938    return;
3939
3940  // Diagnose implicit casts to bool.
3941  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3942    if (isa<StringLiteral>(E))
3943      // Warn on string literal to bool.  Checks for string literals in logical
3944      // expressions, for instances, assert(0 && "error here"), is prevented
3945      // by a check in AnalyzeImplicitConversions().
3946      return DiagnoseImpCast(S, E, T, CC,
3947                             diag::warn_impcast_string_literal_to_bool);
3948    if (Source->isFunctionType()) {
3949      // Warn on function to bool. Checks free functions and static member
3950      // functions. Weakly imported functions are excluded from the check,
3951      // since it's common to test their value to check whether the linker
3952      // found a definition for them.
3953      ValueDecl *D = 0;
3954      if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3955        D = R->getDecl();
3956      } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3957        D = M->getMemberDecl();
3958      }
3959
3960      if (D && !D->isWeak()) {
3961        if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3962          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3963            << F << E->getSourceRange() << SourceRange(CC);
3964          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3965            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3966          QualType ReturnType;
3967          UnresolvedSet<4> NonTemplateOverloads;
3968          S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3969          if (!ReturnType.isNull()
3970              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3971            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3972              << FixItHint::CreateInsertion(
3973                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
3974          return;
3975        }
3976      }
3977    }
3978    return; // Other casts to bool are not checked.
3979  }
3980
3981  // Strip vector types.
3982  if (isa<VectorType>(Source)) {
3983    if (!isa<VectorType>(Target)) {
3984      if (S.SourceMgr.isInSystemMacro(CC))
3985        return;
3986      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3987    }
3988
3989    // If the vector cast is cast between two vectors of the same size, it is
3990    // a bitcast, not a conversion.
3991    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3992      return;
3993
3994    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3995    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3996  }
3997
3998  // Strip complex types.
3999  if (isa<ComplexType>(Source)) {
4000    if (!isa<ComplexType>(Target)) {
4001      if (S.SourceMgr.isInSystemMacro(CC))
4002        return;
4003
4004      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
4005    }
4006
4007    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
4008    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
4009  }
4010
4011  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
4012  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
4013
4014  // If the source is floating point...
4015  if (SourceBT && SourceBT->isFloatingPoint()) {
4016    // ...and the target is floating point...
4017    if (TargetBT && TargetBT->isFloatingPoint()) {
4018      // ...then warn if we're dropping FP rank.
4019
4020      // Builtin FP kinds are ordered by increasing FP rank.
4021      if (SourceBT->getKind() > TargetBT->getKind()) {
4022        // Don't warn about float constants that are precisely
4023        // representable in the target type.
4024        Expr::EvalResult result;
4025        if (E->EvaluateAsRValue(result, S.Context)) {
4026          // Value might be a float, a float vector, or a float complex.
4027          if (IsSameFloatAfterCast(result.Val,
4028                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
4029                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
4030            return;
4031        }
4032
4033        if (S.SourceMgr.isInSystemMacro(CC))
4034          return;
4035
4036        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
4037      }
4038      return;
4039    }
4040
4041    // If the target is integral, always warn.
4042    if ((TargetBT && TargetBT->isInteger())) {
4043      if (S.SourceMgr.isInSystemMacro(CC))
4044        return;
4045
4046      Expr *InnerE = E->IgnoreParenImpCasts();
4047      // We also want to warn on, e.g., "int i = -1.234"
4048      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
4049        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
4050          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
4051
4052      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
4053        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
4054      } else {
4055        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
4056      }
4057    }
4058
4059    return;
4060  }
4061
4062  if (!Source->isIntegerType() || !Target->isIntegerType())
4063    return;
4064
4065  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
4066           == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
4067    S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
4068        << E->getSourceRange() << clang::SourceRange(CC);
4069    return;
4070  }
4071
4072  IntRange SourceRange = GetExprRange(S.Context, E);
4073  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
4074
4075  if (SourceRange.Width > TargetRange.Width) {
4076    // If the source is a constant, use a default-on diagnostic.
4077    // TODO: this should happen for bitfield stores, too.
4078    llvm::APSInt Value(32);
4079    if (E->isIntegerConstantExpr(Value, S.Context)) {
4080      if (S.SourceMgr.isInSystemMacro(CC))
4081        return;
4082
4083      std::string PrettySourceValue = Value.toString(10);
4084      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
4085
4086      S.DiagRuntimeBehavior(E->getExprLoc(), E,
4087        S.PDiag(diag::warn_impcast_integer_precision_constant)
4088            << PrettySourceValue << PrettyTargetValue
4089            << E->getType() << T << E->getSourceRange()
4090            << clang::SourceRange(CC));
4091      return;
4092    }
4093
4094    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
4095    if (S.SourceMgr.isInSystemMacro(CC))
4096      return;
4097
4098    if (SourceRange.Width == 64 && TargetRange.Width == 32)
4099      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
4100                             /* pruneControlFlow */ true);
4101    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
4102  }
4103
4104  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
4105      (!TargetRange.NonNegative && SourceRange.NonNegative &&
4106       SourceRange.Width == TargetRange.Width)) {
4107
4108    if (S.SourceMgr.isInSystemMacro(CC))
4109      return;
4110
4111    unsigned DiagID = diag::warn_impcast_integer_sign;
4112
4113    // Traditionally, gcc has warned about this under -Wsign-compare.
4114    // We also want to warn about it in -Wconversion.
4115    // So if -Wconversion is off, use a completely identical diagnostic
4116    // in the sign-compare group.
4117    // The conditional-checking code will
4118    if (ICContext) {
4119      DiagID = diag::warn_impcast_integer_sign_conditional;
4120      *ICContext = true;
4121    }
4122
4123    return DiagnoseImpCast(S, E, T, CC, DiagID);
4124  }
4125
4126  // Diagnose conversions between different enumeration types.
4127  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
4128  // type, to give us better diagnostics.
4129  QualType SourceType = E->getType();
4130  if (!S.getLangOptions().CPlusPlus) {
4131    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4132      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
4133        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
4134        SourceType = S.Context.getTypeDeclType(Enum);
4135        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
4136      }
4137  }
4138
4139  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
4140    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
4141      if ((SourceEnum->getDecl()->getIdentifier() ||
4142           SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4143          (TargetEnum->getDecl()->getIdentifier() ||
4144           TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
4145          SourceEnum != TargetEnum) {
4146        if (S.SourceMgr.isInSystemMacro(CC))
4147          return;
4148
4149        return DiagnoseImpCast(S, E, SourceType, T, CC,
4150                               diag::warn_impcast_different_enum_types);
4151      }
4152
4153  return;
4154}
4155
4156void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
4157
4158void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
4159                             SourceLocation CC, bool &ICContext) {
4160  E = E->IgnoreParenImpCasts();
4161
4162  if (isa<ConditionalOperator>(E))
4163    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4164
4165  AnalyzeImplicitConversions(S, E, CC);
4166  if (E->getType() != T)
4167    return CheckImplicitConversion(S, E, T, CC, &ICContext);
4168  return;
4169}
4170
4171void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
4172  SourceLocation CC = E->getQuestionLoc();
4173
4174  AnalyzeImplicitConversions(S, E->getCond(), CC);
4175
4176  bool Suspicious = false;
4177  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4178  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
4179
4180  // If -Wconversion would have warned about either of the candidates
4181  // for a signedness conversion to the context type...
4182  if (!Suspicious) return;
4183
4184  // ...but it's currently ignored...
4185  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4186                                 CC))
4187    return;
4188
4189  // ...then check whether it would have warned about either of the
4190  // candidates for a signedness conversion to the condition type.
4191  if (E->getType() == T) return;
4192
4193  Suspicious = false;
4194  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4195                          E->getType(), CC, &Suspicious);
4196  if (!Suspicious)
4197    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
4198                            E->getType(), CC, &Suspicious);
4199}
4200
4201/// AnalyzeImplicitConversions - Find and report any interesting
4202/// implicit conversions in the given expression.  There are a couple
4203/// of competing diagnostics here, -Wconversion and -Wsign-compare.
4204void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
4205  QualType T = OrigE->getType();
4206  Expr *E = OrigE->IgnoreParenImpCasts();
4207
4208  if (E->isTypeDependent() || E->isValueDependent())
4209    return;
4210
4211  // For conditional operators, we analyze the arguments as if they
4212  // were being fed directly into the output.
4213  if (isa<ConditionalOperator>(E)) {
4214    ConditionalOperator *CO = cast<ConditionalOperator>(E);
4215    CheckConditionalOperator(S, CO, T);
4216    return;
4217  }
4218
4219  // Go ahead and check any implicit conversions we might have skipped.
4220  // The non-canonical typecheck is just an optimization;
4221  // CheckImplicitConversion will filter out dead implicit conversions.
4222  if (E->getType() != T)
4223    CheckImplicitConversion(S, E, T, CC);
4224
4225  // Now continue drilling into this expression.
4226
4227  // Skip past explicit casts.
4228  if (isa<ExplicitCastExpr>(E)) {
4229    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
4230    return AnalyzeImplicitConversions(S, E, CC);
4231  }
4232
4233  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4234    // Do a somewhat different check with comparison operators.
4235    if (BO->isComparisonOp())
4236      return AnalyzeComparison(S, BO);
4237
4238    // And with simple assignments.
4239    if (BO->getOpcode() == BO_Assign)
4240      return AnalyzeAssignment(S, BO);
4241  }
4242
4243  // These break the otherwise-useful invariant below.  Fortunately,
4244  // we don't really need to recurse into them, because any internal
4245  // expressions should have been analyzed already when they were
4246  // built into statements.
4247  if (isa<StmtExpr>(E)) return;
4248
4249  // Don't descend into unevaluated contexts.
4250  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
4251
4252  // Now just recurse over the expression's children.
4253  CC = E->getExprLoc();
4254  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4255  bool IsLogicalOperator = BO && BO->isLogicalOp();
4256  for (Stmt::child_range I = E->children(); I; ++I) {
4257    Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
4258    if (!ChildExpr)
4259      continue;
4260
4261    if (IsLogicalOperator &&
4262        isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4263      // Ignore checking string literals that are in logical operators.
4264      continue;
4265    AnalyzeImplicitConversions(S, ChildExpr, CC);
4266  }
4267}
4268
4269} // end anonymous namespace
4270
4271/// Diagnoses "dangerous" implicit conversions within the given
4272/// expression (which is a full expression).  Implements -Wconversion
4273/// and -Wsign-compare.
4274///
4275/// \param CC the "context" location of the implicit conversion, i.e.
4276///   the most location of the syntactic entity requiring the implicit
4277///   conversion
4278void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
4279  // Don't diagnose in unevaluated contexts.
4280  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4281    return;
4282
4283  // Don't diagnose for value- or type-dependent expressions.
4284  if (E->isTypeDependent() || E->isValueDependent())
4285    return;
4286
4287  // Check for array bounds violations in cases where the check isn't triggered
4288  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4289  // ArraySubscriptExpr is on the RHS of a variable initialization.
4290  CheckArrayAccess(E);
4291
4292  // This is not the right CC for (e.g.) a variable initialization.
4293  AnalyzeImplicitConversions(*this, E, CC);
4294}
4295
4296void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4297                                       FieldDecl *BitField,
4298                                       Expr *Init) {
4299  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4300}
4301
4302/// CheckParmsForFunctionDef - Check that the parameters of the given
4303/// function are appropriate for the definition of a function. This
4304/// takes care of any checks that cannot be performed on the
4305/// declaration itself, e.g., that the types of each of the function
4306/// parameters are complete.
4307bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4308                                    bool CheckParameterNames) {
4309  bool HasInvalidParm = false;
4310  for (; P != PEnd; ++P) {
4311    ParmVarDecl *Param = *P;
4312
4313    // C99 6.7.5.3p4: the parameters in a parameter type list in a
4314    // function declarator that is part of a function definition of
4315    // that function shall not have incomplete type.
4316    //
4317    // This is also C++ [dcl.fct]p6.
4318    if (!Param->isInvalidDecl() &&
4319        RequireCompleteType(Param->getLocation(), Param->getType(),
4320                               diag::err_typecheck_decl_incomplete_type)) {
4321      Param->setInvalidDecl();
4322      HasInvalidParm = true;
4323    }
4324
4325    // C99 6.9.1p5: If the declarator includes a parameter type list, the
4326    // declaration of each parameter shall include an identifier.
4327    if (CheckParameterNames &&
4328        Param->getIdentifier() == 0 &&
4329        !Param->isImplicit() &&
4330        !getLangOptions().CPlusPlus)
4331      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
4332
4333    // C99 6.7.5.3p12:
4334    //   If the function declarator is not part of a definition of that
4335    //   function, parameters may have incomplete type and may use the [*]
4336    //   notation in their sequences of declarator specifiers to specify
4337    //   variable length array types.
4338    QualType PType = Param->getOriginalType();
4339    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4340      if (AT->getSizeModifier() == ArrayType::Star) {
4341        // FIXME: This diagnosic should point the the '[*]' if source-location
4342        // information is added for it.
4343        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4344      }
4345    }
4346  }
4347
4348  return HasInvalidParm;
4349}
4350
4351/// CheckCastAlign - Implements -Wcast-align, which warns when a
4352/// pointer cast increases the alignment requirements.
4353void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4354  // This is actually a lot of work to potentially be doing on every
4355  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
4356  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4357                                          TRange.getBegin())
4358        == DiagnosticsEngine::Ignored)
4359    return;
4360
4361  // Ignore dependent types.
4362  if (T->isDependentType() || Op->getType()->isDependentType())
4363    return;
4364
4365  // Require that the destination be a pointer type.
4366  const PointerType *DestPtr = T->getAs<PointerType>();
4367  if (!DestPtr) return;
4368
4369  // If the destination has alignment 1, we're done.
4370  QualType DestPointee = DestPtr->getPointeeType();
4371  if (DestPointee->isIncompleteType()) return;
4372  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4373  if (DestAlign.isOne()) return;
4374
4375  // Require that the source be a pointer type.
4376  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4377  if (!SrcPtr) return;
4378  QualType SrcPointee = SrcPtr->getPointeeType();
4379
4380  // Whitelist casts from cv void*.  We already implicitly
4381  // whitelisted casts to cv void*, since they have alignment 1.
4382  // Also whitelist casts involving incomplete types, which implicitly
4383  // includes 'void'.
4384  if (SrcPointee->isIncompleteType()) return;
4385
4386  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4387  if (SrcAlign >= DestAlign) return;
4388
4389  Diag(TRange.getBegin(), diag::warn_cast_align)
4390    << Op->getType() << T
4391    << static_cast<unsigned>(SrcAlign.getQuantity())
4392    << static_cast<unsigned>(DestAlign.getQuantity())
4393    << TRange << Op->getSourceRange();
4394}
4395
4396static const Type* getElementType(const Expr *BaseExpr) {
4397  const Type* EltType = BaseExpr->getType().getTypePtr();
4398  if (EltType->isAnyPointerType())
4399    return EltType->getPointeeType().getTypePtr();
4400  else if (EltType->isArrayType())
4401    return EltType->getBaseElementTypeUnsafe();
4402  return EltType;
4403}
4404
4405/// \brief Check whether this array fits the idiom of a size-one tail padded
4406/// array member of a struct.
4407///
4408/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4409/// commonly used to emulate flexible arrays in C89 code.
4410static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4411                                    const NamedDecl *ND) {
4412  if (Size != 1 || !ND) return false;
4413
4414  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4415  if (!FD) return false;
4416
4417  // Don't consider sizes resulting from macro expansions or template argument
4418  // substitution to form C89 tail-padded arrays.
4419  ConstantArrayTypeLoc TL =
4420    cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4421  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4422  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4423    return false;
4424
4425  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4426  if (!RD) return false;
4427  if (RD->isUnion()) return false;
4428  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4429    if (!CRD->isStandardLayout()) return false;
4430  }
4431
4432  // See if this is the last field decl in the record.
4433  const Decl *D = FD;
4434  while ((D = D->getNextDeclInContext()))
4435    if (isa<FieldDecl>(D))
4436      return false;
4437  return true;
4438}
4439
4440void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4441                            const ArraySubscriptExpr *ASE,
4442                            bool AllowOnePastEnd, bool IndexNegated) {
4443  IndexExpr = IndexExpr->IgnoreParenImpCasts();
4444  if (IndexExpr->isValueDependent())
4445    return;
4446
4447  const Type *EffectiveType = getElementType(BaseExpr);
4448  BaseExpr = BaseExpr->IgnoreParenCasts();
4449  const ConstantArrayType *ArrayTy =
4450    Context.getAsConstantArrayType(BaseExpr->getType());
4451  if (!ArrayTy)
4452    return;
4453
4454  llvm::APSInt index;
4455  if (!IndexExpr->EvaluateAsInt(index, Context))
4456    return;
4457  if (IndexNegated)
4458    index = -index;
4459
4460  const NamedDecl *ND = NULL;
4461  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4462    ND = dyn_cast<NamedDecl>(DRE->getDecl());
4463  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4464    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4465
4466  if (index.isUnsigned() || !index.isNegative()) {
4467    llvm::APInt size = ArrayTy->getSize();
4468    if (!size.isStrictlyPositive())
4469      return;
4470
4471    const Type* BaseType = getElementType(BaseExpr);
4472    if (BaseType != EffectiveType) {
4473      // Make sure we're comparing apples to apples when comparing index to size
4474      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4475      uint64_t array_typesize = Context.getTypeSize(BaseType);
4476      // Handle ptrarith_typesize being zero, such as when casting to void*
4477      if (!ptrarith_typesize) ptrarith_typesize = 1;
4478      if (ptrarith_typesize != array_typesize) {
4479        // There's a cast to a different size type involved
4480        uint64_t ratio = array_typesize / ptrarith_typesize;
4481        // TODO: Be smarter about handling cases where array_typesize is not a
4482        // multiple of ptrarith_typesize
4483        if (ptrarith_typesize * ratio == array_typesize)
4484          size *= llvm::APInt(size.getBitWidth(), ratio);
4485      }
4486    }
4487
4488    if (size.getBitWidth() > index.getBitWidth())
4489      index = index.zext(size.getBitWidth());
4490    else if (size.getBitWidth() < index.getBitWidth())
4491      size = size.zext(index.getBitWidth());
4492
4493    // For array subscripting the index must be less than size, but for pointer
4494    // arithmetic also allow the index (offset) to be equal to size since
4495    // computing the next address after the end of the array is legal and
4496    // commonly done e.g. in C++ iterators and range-based for loops.
4497    if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
4498      return;
4499
4500    // Also don't warn for arrays of size 1 which are members of some
4501    // structure. These are often used to approximate flexible arrays in C89
4502    // code.
4503    if (IsTailPaddedMemberArray(*this, size, ND))
4504      return;
4505
4506    // Suppress the warning if the subscript expression (as identified by the
4507    // ']' location) and the index expression are both from macro expansions
4508    // within a system header.
4509    if (ASE) {
4510      SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
4511          ASE->getRBracketLoc());
4512      if (SourceMgr.isInSystemHeader(RBracketLoc)) {
4513        SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
4514            IndexExpr->getLocStart());
4515        if (SourceMgr.isFromSameFile(RBracketLoc, IndexLoc))
4516          return;
4517      }
4518    }
4519
4520    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4521    if (ASE)
4522      DiagID = diag::warn_array_index_exceeds_bounds;
4523
4524    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4525                        PDiag(DiagID) << index.toString(10, true)
4526                          << size.toString(10, true)
4527                          << (unsigned)size.getLimitedValue(~0U)
4528                          << IndexExpr->getSourceRange());
4529  } else {
4530    unsigned DiagID = diag::warn_array_index_precedes_bounds;
4531    if (!ASE) {
4532      DiagID = diag::warn_ptr_arith_precedes_bounds;
4533      if (index.isNegative()) index = -index;
4534    }
4535
4536    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4537                        PDiag(DiagID) << index.toString(10, true)
4538                          << IndexExpr->getSourceRange());
4539  }
4540
4541  if (!ND) {
4542    // Try harder to find a NamedDecl to point at in the note.
4543    while (const ArraySubscriptExpr *ASE =
4544           dyn_cast<ArraySubscriptExpr>(BaseExpr))
4545      BaseExpr = ASE->getBase()->IgnoreParenCasts();
4546    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4547      ND = dyn_cast<NamedDecl>(DRE->getDecl());
4548    if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4549      ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4550  }
4551
4552  if (ND)
4553    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4554                        PDiag(diag::note_array_index_out_of_bounds)
4555                          << ND->getDeclName());
4556}
4557
4558void Sema::CheckArrayAccess(const Expr *expr) {
4559  int AllowOnePastEnd = 0;
4560  while (expr) {
4561    expr = expr->IgnoreParenImpCasts();
4562    switch (expr->getStmtClass()) {
4563      case Stmt::ArraySubscriptExprClass: {
4564        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4565        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
4566                         AllowOnePastEnd > 0);
4567        return;
4568      }
4569      case Stmt::UnaryOperatorClass: {
4570        // Only unwrap the * and & unary operators
4571        const UnaryOperator *UO = cast<UnaryOperator>(expr);
4572        expr = UO->getSubExpr();
4573        switch (UO->getOpcode()) {
4574          case UO_AddrOf:
4575            AllowOnePastEnd++;
4576            break;
4577          case UO_Deref:
4578            AllowOnePastEnd--;
4579            break;
4580          default:
4581            return;
4582        }
4583        break;
4584      }
4585      case Stmt::ConditionalOperatorClass: {
4586        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4587        if (const Expr *lhs = cond->getLHS())
4588          CheckArrayAccess(lhs);
4589        if (const Expr *rhs = cond->getRHS())
4590          CheckArrayAccess(rhs);
4591        return;
4592      }
4593      default:
4594        return;
4595    }
4596  }
4597}
4598
4599//===--- CHECK: Objective-C retain cycles ----------------------------------//
4600
4601namespace {
4602  struct RetainCycleOwner {
4603    RetainCycleOwner() : Variable(0), Indirect(false) {}
4604    VarDecl *Variable;
4605    SourceRange Range;
4606    SourceLocation Loc;
4607    bool Indirect;
4608
4609    void setLocsFrom(Expr *e) {
4610      Loc = e->getExprLoc();
4611      Range = e->getSourceRange();
4612    }
4613  };
4614}
4615
4616/// Consider whether capturing the given variable can possibly lead to
4617/// a retain cycle.
4618static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4619  // In ARC, it's captured strongly iff the variable has __strong
4620  // lifetime.  In MRR, it's captured strongly if the variable is
4621  // __block and has an appropriate type.
4622  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4623    return false;
4624
4625  owner.Variable = var;
4626  owner.setLocsFrom(ref);
4627  return true;
4628}
4629
4630static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
4631  while (true) {
4632    e = e->IgnoreParens();
4633    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4634      switch (cast->getCastKind()) {
4635      case CK_BitCast:
4636      case CK_LValueBitCast:
4637      case CK_LValueToRValue:
4638      case CK_ARCReclaimReturnedObject:
4639        e = cast->getSubExpr();
4640        continue;
4641
4642      default:
4643        return false;
4644      }
4645    }
4646
4647    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4648      ObjCIvarDecl *ivar = ref->getDecl();
4649      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4650        return false;
4651
4652      // Try to find a retain cycle in the base.
4653      if (!findRetainCycleOwner(S, ref->getBase(), owner))
4654        return false;
4655
4656      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4657      owner.Indirect = true;
4658      return true;
4659    }
4660
4661    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4662      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4663      if (!var) return false;
4664      return considerVariable(var, ref, owner);
4665    }
4666
4667    if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4668      owner.Variable = ref->getDecl();
4669      owner.setLocsFrom(ref);
4670      return true;
4671    }
4672
4673    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4674      if (member->isArrow()) return false;
4675
4676      // Don't count this as an indirect ownership.
4677      e = member->getBase();
4678      continue;
4679    }
4680
4681    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4682      // Only pay attention to pseudo-objects on property references.
4683      ObjCPropertyRefExpr *pre
4684        = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4685                                              ->IgnoreParens());
4686      if (!pre) return false;
4687      if (pre->isImplicitProperty()) return false;
4688      ObjCPropertyDecl *property = pre->getExplicitProperty();
4689      if (!property->isRetaining() &&
4690          !(property->getPropertyIvarDecl() &&
4691            property->getPropertyIvarDecl()->getType()
4692              .getObjCLifetime() == Qualifiers::OCL_Strong))
4693          return false;
4694
4695      owner.Indirect = true;
4696      if (pre->isSuperReceiver()) {
4697        owner.Variable = S.getCurMethodDecl()->getSelfDecl();
4698        if (!owner.Variable)
4699          return false;
4700        owner.Loc = pre->getLocation();
4701        owner.Range = pre->getSourceRange();
4702        return true;
4703      }
4704      e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4705                              ->getSourceExpr());
4706      continue;
4707    }
4708
4709    // Array ivars?
4710
4711    return false;
4712  }
4713}
4714
4715namespace {
4716  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4717    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4718      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4719        Variable(variable), Capturer(0) {}
4720
4721    VarDecl *Variable;
4722    Expr *Capturer;
4723
4724    void VisitDeclRefExpr(DeclRefExpr *ref) {
4725      if (ref->getDecl() == Variable && !Capturer)
4726        Capturer = ref;
4727    }
4728
4729    void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4730      if (ref->getDecl() == Variable && !Capturer)
4731        Capturer = ref;
4732    }
4733
4734    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4735      if (Capturer) return;
4736      Visit(ref->getBase());
4737      if (Capturer && ref->isFreeIvar())
4738        Capturer = ref;
4739    }
4740
4741    void VisitBlockExpr(BlockExpr *block) {
4742      // Look inside nested blocks
4743      if (block->getBlockDecl()->capturesVariable(Variable))
4744        Visit(block->getBlockDecl()->getBody());
4745    }
4746  };
4747}
4748
4749/// Check whether the given argument is a block which captures a
4750/// variable.
4751static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4752  assert(owner.Variable && owner.Loc.isValid());
4753
4754  e = e->IgnoreParenCasts();
4755  BlockExpr *block = dyn_cast<BlockExpr>(e);
4756  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4757    return 0;
4758
4759  FindCaptureVisitor visitor(S.Context, owner.Variable);
4760  visitor.Visit(block->getBlockDecl()->getBody());
4761  return visitor.Capturer;
4762}
4763
4764static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4765                                RetainCycleOwner &owner) {
4766  assert(capturer);
4767  assert(owner.Variable && owner.Loc.isValid());
4768
4769  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4770    << owner.Variable << capturer->getSourceRange();
4771  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4772    << owner.Indirect << owner.Range;
4773}
4774
4775/// Check for a keyword selector that starts with the word 'add' or
4776/// 'set'.
4777static bool isSetterLikeSelector(Selector sel) {
4778  if (sel.isUnarySelector()) return false;
4779
4780  StringRef str = sel.getNameForSlot(0);
4781  while (!str.empty() && str.front() == '_') str = str.substr(1);
4782  if (str.startswith("set"))
4783    str = str.substr(3);
4784  else if (str.startswith("add")) {
4785    // Specially whitelist 'addOperationWithBlock:'.
4786    if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4787      return false;
4788    str = str.substr(3);
4789  }
4790  else
4791    return false;
4792
4793  if (str.empty()) return true;
4794  return !islower(str.front());
4795}
4796
4797/// Check a message send to see if it's likely to cause a retain cycle.
4798void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4799  // Only check instance methods whose selector looks like a setter.
4800  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4801    return;
4802
4803  // Try to find a variable that the receiver is strongly owned by.
4804  RetainCycleOwner owner;
4805  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4806    if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
4807      return;
4808  } else {
4809    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4810    owner.Variable = getCurMethodDecl()->getSelfDecl();
4811    owner.Loc = msg->getSuperLoc();
4812    owner.Range = msg->getSuperLoc();
4813  }
4814
4815  // Check whether the receiver is captured by any of the arguments.
4816  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4817    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4818      return diagnoseRetainCycle(*this, capturer, owner);
4819}
4820
4821/// Check a property assign to see if it's likely to cause a retain cycle.
4822void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4823  RetainCycleOwner owner;
4824  if (!findRetainCycleOwner(*this, receiver, owner))
4825    return;
4826
4827  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4828    diagnoseRetainCycle(*this, capturer, owner);
4829}
4830
4831bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4832                              QualType LHS, Expr *RHS) {
4833  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4834  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4835    return false;
4836  // strip off any implicit cast added to get to the one arc-specific
4837  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4838    if (cast->getCastKind() == CK_ARCConsumeObject) {
4839      Diag(Loc, diag::warn_arc_retained_assign)
4840        << (LT == Qualifiers::OCL_ExplicitNone)
4841        << RHS->getSourceRange();
4842      return true;
4843    }
4844    RHS = cast->getSubExpr();
4845  }
4846  return false;
4847}
4848
4849void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4850                              Expr *LHS, Expr *RHS) {
4851  QualType LHSType;
4852  // PropertyRef on LHS type need be directly obtained from
4853  // its declaration as it has a PsuedoType.
4854  ObjCPropertyRefExpr *PRE
4855    = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
4856  if (PRE && !PRE->isImplicitProperty()) {
4857    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4858    if (PD)
4859      LHSType = PD->getType();
4860  }
4861
4862  if (LHSType.isNull())
4863    LHSType = LHS->getType();
4864  if (checkUnsafeAssigns(Loc, LHSType, RHS))
4865    return;
4866  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4867  // FIXME. Check for other life times.
4868  if (LT != Qualifiers::OCL_None)
4869    return;
4870
4871  if (PRE) {
4872    if (PRE->isImplicitProperty())
4873      return;
4874    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4875    if (!PD)
4876      return;
4877
4878    unsigned Attributes = PD->getPropertyAttributes();
4879    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
4880      // when 'assign' attribute was not explicitly specified
4881      // by user, ignore it and rely on property type itself
4882      // for lifetime info.
4883      unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
4884      if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
4885          LHSType->isObjCRetainableType())
4886        return;
4887
4888      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4889        if (cast->getCastKind() == CK_ARCConsumeObject) {
4890          Diag(Loc, diag::warn_arc_retained_property_assign)
4891          << RHS->getSourceRange();
4892          return;
4893        }
4894        RHS = cast->getSubExpr();
4895      }
4896    }
4897  }
4898}
4899
4900//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
4901
4902namespace {
4903bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
4904                                 SourceLocation StmtLoc,
4905                                 const NullStmt *Body) {
4906  // Do not warn if the body is a macro that expands to nothing, e.g:
4907  //
4908  // #define CALL(x)
4909  // if (condition)
4910  //   CALL(0);
4911  //
4912  if (Body->hasLeadingEmptyMacro())
4913    return false;
4914
4915  // Get line numbers of statement and body.
4916  bool StmtLineInvalid;
4917  unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
4918                                                      &StmtLineInvalid);
4919  if (StmtLineInvalid)
4920    return false;
4921
4922  bool BodyLineInvalid;
4923  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
4924                                                      &BodyLineInvalid);
4925  if (BodyLineInvalid)
4926    return false;
4927
4928  // Warn if null statement and body are on the same line.
4929  if (StmtLine != BodyLine)
4930    return false;
4931
4932  return true;
4933}
4934} // Unnamed namespace
4935
4936void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
4937                                 const Stmt *Body,
4938                                 unsigned DiagID) {
4939  // Since this is a syntactic check, don't emit diagnostic for template
4940  // instantiations, this just adds noise.
4941  if (CurrentInstantiationScope)
4942    return;
4943
4944  // The body should be a null statement.
4945  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4946  if (!NBody)
4947    return;
4948
4949  // Do the usual checks.
4950  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4951    return;
4952
4953  Diag(NBody->getSemiLoc(), DiagID);
4954  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
4955}
4956
4957void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
4958                                 const Stmt *PossibleBody) {
4959  assert(!CurrentInstantiationScope); // Ensured by caller
4960
4961  SourceLocation StmtLoc;
4962  const Stmt *Body;
4963  unsigned DiagID;
4964  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
4965    StmtLoc = FS->getRParenLoc();
4966    Body = FS->getBody();
4967    DiagID = diag::warn_empty_for_body;
4968  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
4969    StmtLoc = WS->getCond()->getSourceRange().getEnd();
4970    Body = WS->getBody();
4971    DiagID = diag::warn_empty_while_body;
4972  } else
4973    return; // Neither `for' nor `while'.
4974
4975  // The body should be a null statement.
4976  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
4977  if (!NBody)
4978    return;
4979
4980  // Skip expensive checks if diagnostic is disabled.
4981  if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
4982          DiagnosticsEngine::Ignored)
4983    return;
4984
4985  // Do the usual checks.
4986  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
4987    return;
4988
4989  // `for(...);' and `while(...);' are popular idioms, so in order to keep
4990  // noise level low, emit diagnostics only if for/while is followed by a
4991  // CompoundStmt, e.g.:
4992  //    for (int i = 0; i < n; i++);
4993  //    {
4994  //      a(i);
4995  //    }
4996  // or if for/while is followed by a statement with more indentation
4997  // than for/while itself:
4998  //    for (int i = 0; i < n; i++);
4999  //      a(i);
5000  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
5001  if (!ProbableTypo) {
5002    bool BodyColInvalid;
5003    unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
5004                             PossibleBody->getLocStart(),
5005                             &BodyColInvalid);
5006    if (BodyColInvalid)
5007      return;
5008
5009    bool StmtColInvalid;
5010    unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
5011                             S->getLocStart(),
5012                             &StmtColInvalid);
5013    if (StmtColInvalid)
5014      return;
5015
5016    if (BodyCol > StmtCol)
5017      ProbableTypo = true;
5018  }
5019
5020  if (ProbableTypo) {
5021    Diag(NBody->getSemiLoc(), DiagID);
5022    Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
5023  }
5024}
5025