SemaChecking.cpp revision 6fcd932dfd6835f70cc00d6f7c6789793f6d7b66
1f79470583759d20c20268711e6111461aefa8461Jim Grosbach//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
22440fb1f91557912f8c43cb72201170254ae09f4Amara Emerson//
32440fb1f91557912f8c43cb72201170254ae09f4Amara Emerson//                     The LLVM Compiler Infrastructure
416a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//
593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin// This file is distributed under the University of Illinois Open Source
693ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin// License. See LICENSE.TXT for details.
716a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//
816a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//===----------------------------------------------------------------------===//
916a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//
1016a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//  This file implements extra semantic analysis beyond what is enforced
1193ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin//  by the C type system.
1293ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin//
1316a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar//===----------------------------------------------------------------------===//
1416a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar
1516a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Sema/Initialization.h"
1693ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/Sema/Sema.h"
1793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/Sema/SemaInternal.h"
1816a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Sema/Initialization.h"
1916a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Sema/ScopeInfo.h"
2016a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Analysis/Analyses/FormatString.h"
2193ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/AST/ASTContext.h"
2293ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/AST/CharUnits.h"
2316a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/DeclCXX.h"
2416a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/DeclObjC.h"
2516a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/ExprCXX.h"
2693ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/AST/ExprObjC.h"
2793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/AST/EvaluatedExprVisitor.h"
2816a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/DeclObjC.h"
2916a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/StmtCXX.h"
3016a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/AST/StmtObjC.h"
3193ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/Lex/Preprocessor.h"
325e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling#include "llvm/ADT/BitVector.h"
3393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "llvm/ADT/STLExtras.h"
3416a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "llvm/Support/raw_ostream.h"
3516a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Basic/TargetBuiltins.h"
3616a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar#include "clang/Basic/TargetInfo.h"
3793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin#include "clang/Basic/ConvertUTF.h"
385e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling#include <limits>
3993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Linusing namespace clang;
4016a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbarusing namespace sema;
4116a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar
4216a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel DunbarSourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
4393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin                                                    unsigned ByteNo) const {
4493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
4516a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar                               PP.getLangOptions(), PP.getTargetInfo());
4616a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar}
4716a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar
4893ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin
495e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling/// CheckablePrintfAttr - does a function call have a "printf" attribute
5093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin/// and arguments that merit checking?
5116a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbarbool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
5216a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar  if (Format->getType() == "printf") return true;
5316a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar  if (Format->getType() == "printf0") {
5493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    // printf0 allows null "format" string; if so don't check format/args
5593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    unsigned format_idx = Format->getFormatIdx() - 1;
5616a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar    // Does the index refer to the implicit object argument?
5716a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar    if (isa<CXXMemberCallExpr>(TheCall)) {
5816a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar      if (format_idx == 0)
5993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin        return false;
6093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin      --format_idx;
6116a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar    }
6216a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar    if (format_idx < TheCall->getNumArgs()) {
6316a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar      Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
6493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin      if (!Format->isNullPointerConstant(Context,
655e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling                                         Expr::NPC_ValueDependentIsNull))
6693ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin        return true;
6716a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar    }
6816a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar  }
6916a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar  return false;
7093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin}
7193ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin
7216a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar/// Checks that a call expression's argument count is the desired number.
7316a0808b7992db2c2ba78b387e1732bbb0fb371bDaniel Dunbar/// This is useful when doing custom type-checking.  Returns true on error.
74b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbarstatic bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
7593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  unsigned argCount = call->getNumArgs();
765e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  if (argCount == desiredArgCount) return false;
77b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar
78b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar  if (argCount < desiredArgCount)
7975d0f82e50565cc4cf71140ecf2141a40a3a5af9Rafael Espindola    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar        << 0 /*function call*/ << desiredArgCount << argCount
81b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar        << call->getSourceRange();
82b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar
8393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  // Highlight all the excess arguments.
845e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
8593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin                    call->getArg(argCount - 1)->getLocEnd());
86b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar
87b0d58196808aba4b3d1a7488bd5566f3c0a83e89Daniel Dunbar  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88420255710694e958fa04bed1d80d96508949879eDaniel Dunbar    << 0 /*function call*/ << desiredArgCount << argCount
8993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    << call->getArg(1)->getSourceRange();
9093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin}
91420255710694e958fa04bed1d80d96508949879eDaniel Dunbar
92420255710694e958fa04bed1d80d96508949879eDaniel Dunbar/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
9393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin/// annotation is a non wide string literal.
9493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Linstatic bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95420255710694e958fa04bed1d80d96508949879eDaniel Dunbar  Arg = Arg->IgnoreParenCasts();
96679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
9793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  if (!Literal || !Literal->isAscii()) {
9893ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar      << Arg->getSourceRange();
100679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar    return true;
101679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  }
10293ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  return false;
10393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin}
104679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar
105679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel DunbarExprResult
106679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel DunbarSema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
10793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  ExprResult TheCallResult(Owned(TheCall));
1085e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling
10993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  // Find out if any arguments are required to be integer constant expressions.
110679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  unsigned ICEArguments = 0;
111679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  ASTContext::GetBuiltinTypeError Error;
112679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
11393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  if (Error != ASTContext::GE_None)
1145e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
11593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin
116679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  // If any arguments are required to be ICE's, check and diagnose.
117679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar    // Skip arguments not required to be ICE's.
11993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
12093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin
121679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar    llvm::APSInt Result;
122679855a6e14fbc6c6838c566aa74c32f52f4f946Daniel Dunbar    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1234cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar      return true;
12493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    ICEArguments &= ~(1 << ArgNo);
12593ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  }
12693ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin
12793ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  switch (BuiltinID) {
12893ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  case Builtin::BI__builtin___CFStringMakeConstantString:
12993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    assert(TheCall->getNumArgs() == 1 &&
13093ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin           "Wrong # arguments to builtin CFStringMakeConstantString");
13193ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    if (CheckObjCString(TheCall->getArg(0)))
1325e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling      return ExprError();
1335e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling    break;
1345e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  case Builtin::BI__builtin_stdarg_start:
1355e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  case Builtin::BI__builtin_va_start:
1364cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar    if (SemaBuiltinVAStart(TheCall))
1374cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar      return ExprError();
1384cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar    break;
1394cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar  case Builtin::BI__builtin_isgreater:
1404cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar  case Builtin::BI__builtin_isgreaterequal:
1414cc753f4503931763cfb762a95928b44fcbe64e9Daniel Dunbar  case Builtin::BI__builtin_isless:
1424581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar  case Builtin::BI__builtin_islessequal:
14393ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  case Builtin::BI__builtin_islessgreater:
14493ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  case Builtin::BI__builtin_isunordered:
1454581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar    if (SemaBuiltinUnorderedCompare(TheCall))
1464581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar      return ExprError();
1474581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar    break;
14893ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin  case Builtin::BI__builtin_fpclassify:
14993ab6bf534fb6c26563c00f28a8fc5581bb71dfdStephen Lin    if (SemaBuiltinFPClassification(TheCall, 6))
1504581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar      return ExprError();
1514581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar    break;
1524581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar  case Builtin::BI__builtin_isfinite:
1535e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  case Builtin::BI__builtin_isinf:
1545e31474b9c8348e8d0404264ae6a8775e34df6acBill Wendling  case Builtin::BI__builtin_isinf_sign:
1554581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar  case Builtin::BI__builtin_isnan:
1564581581881d3f7349bf5a4b39d761bce688f9164Daniel Dunbar  case Builtin::BI__builtin_isnormal:
157a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov    if (SemaBuiltinFPClassification(TheCall, 1))
158a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov      return ExprError();
159a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov    break;
160a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov  case Builtin::BI__builtin_shufflevector:
161a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov    return SemaBuiltinShuffleVector(TheCall);
162a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov    // TheCall will be freed by the smart pointer here, but that's fine, since
1631067d05041db25301cd923712870bcf97db6d8bcEvgeniy Stepanov    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1641067d05041db25301cd923712870bcf97db6d8bcEvgeniy Stepanov  case Builtin::BI__builtin_prefetch:
165a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov    if (SemaBuiltinPrefetch(TheCall))
166a6ce20ea10b1788ed1f266d5809a7ac2bca7bf1bEvgeniy Stepanov      return ExprError();
1671067d05041db25301cd923712870bcf97db6d8bcEvgeniy Stepanov    break;
1681067d05041db25301cd923712870bcf97db6d8bcEvgeniy Stepanov  case Builtin::BI__builtin_object_size:
16979f30981fcd25c6ff88807372a2744af02a7690eEli Friedman    if (SemaBuiltinObjectSize(TheCall))
17079f30981fcd25c6ff88807372a2744af02a7690eEli Friedman      return ExprError();
17179f30981fcd25c6ff88807372a2744af02a7690eEli Friedman    break;
17279f30981fcd25c6ff88807372a2744af02a7690eEli Friedman  case Builtin::BI__builtin_longjmp:
17379f30981fcd25c6ff88807372a2744af02a7690eEli Friedman    if (SemaBuiltinLongjmp(TheCall))
17479f30981fcd25c6ff88807372a2744af02a7690eEli Friedman      return ExprError();
17516ba7c8498933781cff103058612e76e8045c798Manman Ren    break;
17616ba7c8498933781cff103058612e76e8045c798Manman Ren
17716ba7c8498933781cff103058612e76e8045c798Manman Ren  case Builtin::BI__builtin_classify_type:
17816ba7c8498933781cff103058612e76e8045c798Manman Ren    if (checkArgCount(*this, TheCall, 1)) return true;
179651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    TheCall->setType(Context.IntTy);
180651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines    break;
181f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__builtin_constant_p:
182f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth    if (checkArgCount(*this, TheCall, 1)) return true;
183f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth    TheCall->setType(Context.IntTy);
184f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth    break;
185f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add:
186f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add_1:
187f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add_2:
188f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add_4:
189f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add_8:
190f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_add_16:
191f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_sub:
192f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_sub_1:
193f82232c8b73851337b83b954ba1292cf6475c7c5Chandler Carruth  case Builtin::BI__sync_fetch_and_sub_2:
194885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_sub_4:
195885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_sub_8:
196885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_sub_16:
197885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or:
198885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or_1:
199885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or_2:
200885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or_4:
201885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or_8:
202885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_or_16:
203885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and:
204885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and_1:
205885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and_2:
206885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and_4:
207885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and_8:
208885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_and_16:
209885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_xor:
210885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_xor_1:
211885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_xor_2:
212651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  case Builtin::BI__sync_fetch_and_xor_4:
213885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_xor_8:
214885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_fetch_and_xor_16:
215885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_add_and_fetch:
216885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_add_and_fetch_1:
217885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_add_and_fetch_2:
218885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_add_and_fetch_4:
219651f13cea278ec967336033dd032faef0e9fc2ecStephen Hines  case Builtin::BI__sync_add_and_fetch_8:
220885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_add_and_fetch_16:
221885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_sub_and_fetch:
222885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_sub_and_fetch_1:
223885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_sub_and_fetch_2:
224885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_sub_and_fetch_4:
225885ad6928f8aca8e9f66eeece53e00364e14ea75Manman Ren  case Builtin::BI__sync_sub_and_fetch_8:
226  case Builtin::BI__sync_sub_and_fetch_16:
227  case Builtin::BI__sync_and_and_fetch:
228  case Builtin::BI__sync_and_and_fetch_1:
229  case Builtin::BI__sync_and_and_fetch_2:
230  case Builtin::BI__sync_and_and_fetch_4:
231  case Builtin::BI__sync_and_and_fetch_8:
232  case Builtin::BI__sync_and_and_fetch_16:
233  case Builtin::BI__sync_or_and_fetch:
234  case Builtin::BI__sync_or_and_fetch_1:
235  case Builtin::BI__sync_or_and_fetch_2:
236  case Builtin::BI__sync_or_and_fetch_4:
237  case Builtin::BI__sync_or_and_fetch_8:
238  case Builtin::BI__sync_or_and_fetch_16:
239  case Builtin::BI__sync_xor_and_fetch:
240  case Builtin::BI__sync_xor_and_fetch_1:
241  case Builtin::BI__sync_xor_and_fetch_2:
242  case Builtin::BI__sync_xor_and_fetch_4:
243  case Builtin::BI__sync_xor_and_fetch_8:
244  case Builtin::BI__sync_xor_and_fetch_16:
245  case Builtin::BI__sync_val_compare_and_swap:
246  case Builtin::BI__sync_val_compare_and_swap_1:
247  case Builtin::BI__sync_val_compare_and_swap_2:
248  case Builtin::BI__sync_val_compare_and_swap_4:
249  case Builtin::BI__sync_val_compare_and_swap_8:
250  case Builtin::BI__sync_val_compare_and_swap_16:
251  case Builtin::BI__sync_bool_compare_and_swap:
252  case Builtin::BI__sync_bool_compare_and_swap_1:
253  case Builtin::BI__sync_bool_compare_and_swap_2:
254  case Builtin::BI__sync_bool_compare_and_swap_4:
255  case Builtin::BI__sync_bool_compare_and_swap_8:
256  case Builtin::BI__sync_bool_compare_and_swap_16:
257  case Builtin::BI__sync_lock_test_and_set:
258  case Builtin::BI__sync_lock_test_and_set_1:
259  case Builtin::BI__sync_lock_test_and_set_2:
260  case Builtin::BI__sync_lock_test_and_set_4:
261  case Builtin::BI__sync_lock_test_and_set_8:
262  case Builtin::BI__sync_lock_test_and_set_16:
263  case Builtin::BI__sync_lock_release:
264  case Builtin::BI__sync_lock_release_1:
265  case Builtin::BI__sync_lock_release_2:
266  case Builtin::BI__sync_lock_release_4:
267  case Builtin::BI__sync_lock_release_8:
268  case Builtin::BI__sync_lock_release_16:
269  case Builtin::BI__sync_swap:
270  case Builtin::BI__sync_swap_1:
271  case Builtin::BI__sync_swap_2:
272  case Builtin::BI__sync_swap_4:
273  case Builtin::BI__sync_swap_8:
274  case Builtin::BI__sync_swap_16:
275    return SemaBuiltinAtomicOverloaded(move(TheCallResult));
276  case Builtin::BI__atomic_load:
277    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
278  case Builtin::BI__atomic_store:
279    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
280  case Builtin::BI__atomic_exchange:
281    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
282  case Builtin::BI__atomic_compare_exchange_strong:
283    return SemaAtomicOpsOverloaded(move(TheCallResult),
284                                   AtomicExpr::CmpXchgStrong);
285  case Builtin::BI__atomic_compare_exchange_weak:
286    return SemaAtomicOpsOverloaded(move(TheCallResult),
287                                   AtomicExpr::CmpXchgWeak);
288  case Builtin::BI__atomic_fetch_add:
289    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
290  case Builtin::BI__atomic_fetch_sub:
291    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
292  case Builtin::BI__atomic_fetch_and:
293    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
294  case Builtin::BI__atomic_fetch_or:
295    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
296  case Builtin::BI__atomic_fetch_xor:
297    return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
298  case Builtin::BI__builtin_annotation:
299    if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
300      return ExprError();
301    break;
302  }
303
304  // Since the target specific builtins for each arch overlap, only check those
305  // of the arch we are compiling for.
306  if (BuiltinID >= Builtin::FirstTSBuiltin) {
307    switch (Context.getTargetInfo().getTriple().getArch()) {
308      case llvm::Triple::arm:
309      case llvm::Triple::thumb:
310        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
311          return ExprError();
312        break;
313      default:
314        break;
315    }
316  }
317
318  return move(TheCallResult);
319}
320
321// Get the valid immediate range for the specified NEON type code.
322static unsigned RFT(unsigned t, bool shift = false) {
323  NeonTypeFlags Type(t);
324  int IsQuad = Type.isQuad();
325  switch (Type.getEltType()) {
326  case NeonTypeFlags::Int8:
327  case NeonTypeFlags::Poly8:
328    return shift ? 7 : (8 << IsQuad) - 1;
329  case NeonTypeFlags::Int16:
330  case NeonTypeFlags::Poly16:
331    return shift ? 15 : (4 << IsQuad) - 1;
332  case NeonTypeFlags::Int32:
333    return shift ? 31 : (2 << IsQuad) - 1;
334  case NeonTypeFlags::Int64:
335    return shift ? 63 : (1 << IsQuad) - 1;
336  case NeonTypeFlags::Float16:
337    assert(!shift && "cannot shift float types!");
338    return (4 << IsQuad) - 1;
339  case NeonTypeFlags::Float32:
340    assert(!shift && "cannot shift float types!");
341    return (2 << IsQuad) - 1;
342  }
343  return 0;
344}
345
346/// getNeonEltType - Return the QualType corresponding to the elements of
347/// the vector type specified by the NeonTypeFlags.  This is used to check
348/// the pointer arguments for Neon load/store intrinsics.
349static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
350  switch (Flags.getEltType()) {
351  case NeonTypeFlags::Int8:
352    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
353  case NeonTypeFlags::Int16:
354    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
355  case NeonTypeFlags::Int32:
356    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
357  case NeonTypeFlags::Int64:
358    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
359  case NeonTypeFlags::Poly8:
360    return Context.SignedCharTy;
361  case NeonTypeFlags::Poly16:
362    return Context.ShortTy;
363  case NeonTypeFlags::Float16:
364    return Context.UnsignedShortTy;
365  case NeonTypeFlags::Float32:
366    return Context.FloatTy;
367  }
368  return QualType();
369}
370
371bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
372  llvm::APSInt Result;
373
374  unsigned mask = 0;
375  unsigned TV = 0;
376  int PtrArgNum = -1;
377  bool HasConstPtr = false;
378  switch (BuiltinID) {
379#define GET_NEON_OVERLOAD_CHECK
380#include "clang/Basic/arm_neon.inc"
381#undef GET_NEON_OVERLOAD_CHECK
382  }
383
384  // For NEON intrinsics which are overloaded on vector element type, validate
385  // the immediate which specifies which variant to emit.
386  unsigned ImmArg = TheCall->getNumArgs()-1;
387  if (mask) {
388    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
389      return true;
390
391    TV = Result.getLimitedValue(64);
392    if ((TV > 63) || (mask & (1 << TV)) == 0)
393      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
394        << TheCall->getArg(ImmArg)->getSourceRange();
395  }
396
397  if (PtrArgNum >= 0) {
398    // Check that pointer arguments have the specified type.
399    Expr *Arg = TheCall->getArg(PtrArgNum);
400    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
401      Arg = ICE->getSubExpr();
402    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
403    QualType RHSTy = RHS.get()->getType();
404    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
405    if (HasConstPtr)
406      EltTy = EltTy.withConst();
407    QualType LHSTy = Context.getPointerType(EltTy);
408    AssignConvertType ConvTy;
409    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
410    if (RHS.isInvalid())
411      return true;
412    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
413                                 RHS.get(), AA_Assigning))
414      return true;
415  }
416
417  // For NEON intrinsics which take an immediate value as part of the
418  // instruction, range check them here.
419  unsigned i = 0, l = 0, u = 0;
420  switch (BuiltinID) {
421  default: return false;
422  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
423  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
424  case ARM::BI__builtin_arm_vcvtr_f:
425  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
426#define GET_NEON_IMMEDIATE_CHECK
427#include "clang/Basic/arm_neon.inc"
428#undef GET_NEON_IMMEDIATE_CHECK
429  };
430
431  // Check that the immediate argument is actually a constant.
432  if (SemaBuiltinConstantArg(TheCall, i, Result))
433    return true;
434
435  // Range check against the upper/lower values for this isntruction.
436  unsigned Val = Result.getZExtValue();
437  if (Val < l || Val > (u + l))
438    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
439      << l << u+l << TheCall->getArg(i)->getSourceRange();
440
441  // FIXME: VFP Intrinsics should error if VFP not present.
442  return false;
443}
444
445/// CheckFunctionCall - Check a direct function call for various correctness
446/// and safety properties not strictly enforced by the C type system.
447bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
448  // Get the IdentifierInfo* for the called function.
449  IdentifierInfo *FnInfo = FDecl->getIdentifier();
450
451  // None of the checks below are needed for functions that don't have
452  // simple names (e.g., C++ conversion functions).
453  if (!FnInfo)
454    return false;
455
456  // FIXME: This mechanism should be abstracted to be less fragile and
457  // more efficient. For example, just map function ids to custom
458  // handlers.
459
460  // Printf and scanf checking.
461  for (specific_attr_iterator<FormatAttr>
462         i = FDecl->specific_attr_begin<FormatAttr>(),
463         e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
464
465    const FormatAttr *Format = *i;
466    const bool b = Format->getType() == "scanf";
467    if (b || CheckablePrintfAttr(Format, TheCall)) {
468      bool HasVAListArg = Format->getFirstArg() == 0;
469      CheckPrintfScanfArguments(TheCall, HasVAListArg,
470                                Format->getFormatIdx() - 1,
471                                HasVAListArg ? 0 : Format->getFirstArg() - 1,
472                                !b);
473    }
474  }
475
476  for (specific_attr_iterator<NonNullAttr>
477         i = FDecl->specific_attr_begin<NonNullAttr>(),
478         e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
479    CheckNonNullArguments(*i, TheCall->getArgs(),
480                          TheCall->getCallee()->getLocStart());
481  }
482
483  // Builtin handling
484  int CMF = -1;
485  switch (FDecl->getBuiltinID()) {
486  case Builtin::BI__builtin_memset:
487  case Builtin::BI__builtin___memset_chk:
488  case Builtin::BImemset:
489    CMF = CMF_Memset;
490    break;
491
492  case Builtin::BI__builtin_memcpy:
493  case Builtin::BI__builtin___memcpy_chk:
494  case Builtin::BImemcpy:
495    CMF = CMF_Memcpy;
496    break;
497
498  case Builtin::BI__builtin_memmove:
499  case Builtin::BI__builtin___memmove_chk:
500  case Builtin::BImemmove:
501    CMF = CMF_Memmove;
502    break;
503
504  case Builtin::BIstrlcpy:
505  case Builtin::BIstrlcat:
506    CheckStrlcpycatArguments(TheCall, FnInfo);
507    break;
508
509  case Builtin::BI__builtin_memcmp:
510    CMF = CMF_Memcmp;
511    break;
512
513  case Builtin::BI__builtin_strncpy:
514  case Builtin::BI__builtin___strncpy_chk:
515  case Builtin::BIstrncpy:
516    CMF = CMF_Strncpy;
517    break;
518
519  case Builtin::BI__builtin_strncmp:
520    CMF = CMF_Strncmp;
521    break;
522
523  case Builtin::BI__builtin_strncasecmp:
524    CMF = CMF_Strncasecmp;
525    break;
526
527  case Builtin::BI__builtin_strncat:
528  case Builtin::BIstrncat:
529    CMF = CMF_Strncat;
530    break;
531
532  case Builtin::BI__builtin_strndup:
533  case Builtin::BIstrndup:
534    CMF = CMF_Strndup;
535    break;
536
537  default:
538    if (FDecl->getLinkage() == ExternalLinkage &&
539        (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
540      if (FnInfo->isStr("memset"))
541        CMF = CMF_Memset;
542      else if (FnInfo->isStr("memcpy"))
543        CMF = CMF_Memcpy;
544      else if (FnInfo->isStr("memmove"))
545        CMF = CMF_Memmove;
546      else if (FnInfo->isStr("memcmp"))
547        CMF = CMF_Memcmp;
548      else if (FnInfo->isStr("strncpy"))
549        CMF = CMF_Strncpy;
550      else if (FnInfo->isStr("strncmp"))
551        CMF = CMF_Strncmp;
552      else if (FnInfo->isStr("strncasecmp"))
553        CMF = CMF_Strncasecmp;
554      else if (FnInfo->isStr("strncat"))
555        CMF = CMF_Strncat;
556      else if (FnInfo->isStr("strndup"))
557        CMF = CMF_Strndup;
558    }
559    break;
560  }
561
562  // Memset/memcpy/memmove handling
563  if (CMF != -1)
564    CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
565
566  return false;
567}
568
569bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
570  // Printf checking.
571  const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
572  if (!Format)
573    return false;
574
575  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
576  if (!V)
577    return false;
578
579  QualType Ty = V->getType();
580  if (!Ty->isBlockPointerType())
581    return false;
582
583  const bool b = Format->getType() == "scanf";
584  if (!b && !CheckablePrintfAttr(Format, TheCall))
585    return false;
586
587  bool HasVAListArg = Format->getFirstArg() == 0;
588  CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
589                            HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
590
591  return false;
592}
593
594ExprResult
595Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
596  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
597  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
598
599  // All these operations take one of the following four forms:
600  // T   __atomic_load(_Atomic(T)*, int)                              (loads)
601  // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
602  // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
603  //                                                                (cmpxchg)
604  // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
605  // where T is an appropriate type, and the int paremeterss are for orderings.
606  unsigned NumVals = 1;
607  unsigned NumOrders = 1;
608  if (Op == AtomicExpr::Load) {
609    NumVals = 0;
610  } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
611    NumVals = 2;
612    NumOrders = 2;
613  }
614
615  if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
616    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
617      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
618      << TheCall->getCallee()->getSourceRange();
619    return ExprError();
620  } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
621    Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
622         diag::err_typecheck_call_too_many_args)
623      << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
624      << TheCall->getCallee()->getSourceRange();
625    return ExprError();
626  }
627
628  // Inspect the first argument of the atomic operation.  This should always be
629  // a pointer to an _Atomic type.
630  Expr *Ptr = TheCall->getArg(0);
631  Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
632  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
633  if (!pointerType) {
634    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
635      << Ptr->getType() << Ptr->getSourceRange();
636    return ExprError();
637  }
638
639  QualType AtomTy = pointerType->getPointeeType();
640  if (!AtomTy->isAtomicType()) {
641    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
642      << Ptr->getType() << Ptr->getSourceRange();
643    return ExprError();
644  }
645  QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
646
647  if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
648      !ValType->isIntegerType() && !ValType->isPointerType()) {
649    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
650      << Ptr->getType() << Ptr->getSourceRange();
651    return ExprError();
652  }
653
654  if (!ValType->isIntegerType() &&
655      (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
656    Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
657      << Ptr->getType() << Ptr->getSourceRange();
658    return ExprError();
659  }
660
661  switch (ValType.getObjCLifetime()) {
662  case Qualifiers::OCL_None:
663  case Qualifiers::OCL_ExplicitNone:
664    // okay
665    break;
666
667  case Qualifiers::OCL_Weak:
668  case Qualifiers::OCL_Strong:
669  case Qualifiers::OCL_Autoreleasing:
670    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
671      << ValType << Ptr->getSourceRange();
672    return ExprError();
673  }
674
675  QualType ResultType = ValType;
676  if (Op == AtomicExpr::Store)
677    ResultType = Context.VoidTy;
678  else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
679    ResultType = Context.BoolTy;
680
681  // The first argument --- the pointer --- has a fixed type; we
682  // deduce the types of the rest of the arguments accordingly.  Walk
683  // the remaining arguments, converting them to the deduced value type.
684  for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
685    ExprResult Arg = TheCall->getArg(i);
686    QualType Ty;
687    if (i < NumVals+1) {
688      // The second argument to a cmpxchg is a pointer to the data which will
689      // be exchanged. The second argument to a pointer add/subtract is the
690      // amount to add/subtract, which must be a ptrdiff_t.  The third
691      // argument to a cmpxchg and the second argument in all other cases
692      // is the type of the value.
693      if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
694                     Op == AtomicExpr::CmpXchgStrong))
695         Ty = Context.getPointerType(ValType.getUnqualifiedType());
696      else if (!ValType->isIntegerType() &&
697               (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
698        Ty = Context.getPointerDiffType();
699      else
700        Ty = ValType;
701    } else {
702      // The order(s) are always converted to int.
703      Ty = Context.IntTy;
704    }
705    InitializedEntity Entity =
706        InitializedEntity::InitializeParameter(Context, Ty, false);
707    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
708    if (Arg.isInvalid())
709      return true;
710    TheCall->setArg(i, Arg.get());
711  }
712
713  SmallVector<Expr*, 5> SubExprs;
714  SubExprs.push_back(Ptr);
715  if (Op == AtomicExpr::Load) {
716    SubExprs.push_back(TheCall->getArg(1)); // Order
717  } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
718    SubExprs.push_back(TheCall->getArg(2)); // Order
719    SubExprs.push_back(TheCall->getArg(1)); // Val1
720  } else {
721    SubExprs.push_back(TheCall->getArg(3)); // Order
722    SubExprs.push_back(TheCall->getArg(1)); // Val1
723    SubExprs.push_back(TheCall->getArg(2)); // Val2
724    SubExprs.push_back(TheCall->getArg(4)); // OrderFail
725  }
726
727  return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
728                                        SubExprs.data(), SubExprs.size(),
729                                        ResultType, Op,
730                                        TheCall->getRParenLoc()));
731}
732
733
734/// checkBuiltinArgument - Given a call to a builtin function, perform
735/// normal type-checking on the given argument, updating the call in
736/// place.  This is useful when a builtin function requires custom
737/// type-checking for some of its arguments but not necessarily all of
738/// them.
739///
740/// Returns true on error.
741static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
742  FunctionDecl *Fn = E->getDirectCallee();
743  assert(Fn && "builtin call without direct callee!");
744
745  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
746  InitializedEntity Entity =
747    InitializedEntity::InitializeParameter(S.Context, Param);
748
749  ExprResult Arg = E->getArg(0);
750  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
751  if (Arg.isInvalid())
752    return true;
753
754  E->setArg(ArgIndex, Arg.take());
755  return false;
756}
757
758/// SemaBuiltinAtomicOverloaded - We have a call to a function like
759/// __sync_fetch_and_add, which is an overloaded function based on the pointer
760/// type of its first argument.  The main ActOnCallExpr routines have already
761/// promoted the types of arguments because all of these calls are prototyped as
762/// void(...).
763///
764/// This function goes through and does final semantic checking for these
765/// builtins,
766ExprResult
767Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
768  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
769  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
770  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
771
772  // Ensure that we have at least one argument to do type inference from.
773  if (TheCall->getNumArgs() < 1) {
774    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
775      << 0 << 1 << TheCall->getNumArgs()
776      << TheCall->getCallee()->getSourceRange();
777    return ExprError();
778  }
779
780  // Inspect the first argument of the atomic builtin.  This should always be
781  // a pointer type, whose element is an integral scalar or pointer type.
782  // Because it is a pointer type, we don't have to worry about any implicit
783  // casts here.
784  // FIXME: We don't allow floating point scalars as input.
785  Expr *FirstArg = TheCall->getArg(0);
786  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
787  if (!pointerType) {
788    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
789      << FirstArg->getType() << FirstArg->getSourceRange();
790    return ExprError();
791  }
792
793  QualType ValType = pointerType->getPointeeType();
794  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
795      !ValType->isBlockPointerType()) {
796    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
797      << FirstArg->getType() << FirstArg->getSourceRange();
798    return ExprError();
799  }
800
801  switch (ValType.getObjCLifetime()) {
802  case Qualifiers::OCL_None:
803  case Qualifiers::OCL_ExplicitNone:
804    // okay
805    break;
806
807  case Qualifiers::OCL_Weak:
808  case Qualifiers::OCL_Strong:
809  case Qualifiers::OCL_Autoreleasing:
810    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
811      << ValType << FirstArg->getSourceRange();
812    return ExprError();
813  }
814
815  // Strip any qualifiers off ValType.
816  ValType = ValType.getUnqualifiedType();
817
818  // The majority of builtins return a value, but a few have special return
819  // types, so allow them to override appropriately below.
820  QualType ResultType = ValType;
821
822  // We need to figure out which concrete builtin this maps onto.  For example,
823  // __sync_fetch_and_add with a 2 byte object turns into
824  // __sync_fetch_and_add_2.
825#define BUILTIN_ROW(x) \
826  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
827    Builtin::BI##x##_8, Builtin::BI##x##_16 }
828
829  static const unsigned BuiltinIndices[][5] = {
830    BUILTIN_ROW(__sync_fetch_and_add),
831    BUILTIN_ROW(__sync_fetch_and_sub),
832    BUILTIN_ROW(__sync_fetch_and_or),
833    BUILTIN_ROW(__sync_fetch_and_and),
834    BUILTIN_ROW(__sync_fetch_and_xor),
835
836    BUILTIN_ROW(__sync_add_and_fetch),
837    BUILTIN_ROW(__sync_sub_and_fetch),
838    BUILTIN_ROW(__sync_and_and_fetch),
839    BUILTIN_ROW(__sync_or_and_fetch),
840    BUILTIN_ROW(__sync_xor_and_fetch),
841
842    BUILTIN_ROW(__sync_val_compare_and_swap),
843    BUILTIN_ROW(__sync_bool_compare_and_swap),
844    BUILTIN_ROW(__sync_lock_test_and_set),
845    BUILTIN_ROW(__sync_lock_release),
846    BUILTIN_ROW(__sync_swap)
847  };
848#undef BUILTIN_ROW
849
850  // Determine the index of the size.
851  unsigned SizeIndex;
852  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
853  case 1: SizeIndex = 0; break;
854  case 2: SizeIndex = 1; break;
855  case 4: SizeIndex = 2; break;
856  case 8: SizeIndex = 3; break;
857  case 16: SizeIndex = 4; break;
858  default:
859    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
860      << FirstArg->getType() << FirstArg->getSourceRange();
861    return ExprError();
862  }
863
864  // Each of these builtins has one pointer argument, followed by some number of
865  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
866  // that we ignore.  Find out which row of BuiltinIndices to read from as well
867  // as the number of fixed args.
868  unsigned BuiltinID = FDecl->getBuiltinID();
869  unsigned BuiltinIndex, NumFixed = 1;
870  switch (BuiltinID) {
871  default: llvm_unreachable("Unknown overloaded atomic builtin!");
872  case Builtin::BI__sync_fetch_and_add:
873  case Builtin::BI__sync_fetch_and_add_1:
874  case Builtin::BI__sync_fetch_and_add_2:
875  case Builtin::BI__sync_fetch_and_add_4:
876  case Builtin::BI__sync_fetch_and_add_8:
877  case Builtin::BI__sync_fetch_and_add_16:
878    BuiltinIndex = 0;
879    break;
880
881  case Builtin::BI__sync_fetch_and_sub:
882  case Builtin::BI__sync_fetch_and_sub_1:
883  case Builtin::BI__sync_fetch_and_sub_2:
884  case Builtin::BI__sync_fetch_and_sub_4:
885  case Builtin::BI__sync_fetch_and_sub_8:
886  case Builtin::BI__sync_fetch_and_sub_16:
887    BuiltinIndex = 1;
888    break;
889
890  case Builtin::BI__sync_fetch_and_or:
891  case Builtin::BI__sync_fetch_and_or_1:
892  case Builtin::BI__sync_fetch_and_or_2:
893  case Builtin::BI__sync_fetch_and_or_4:
894  case Builtin::BI__sync_fetch_and_or_8:
895  case Builtin::BI__sync_fetch_and_or_16:
896    BuiltinIndex = 2;
897    break;
898
899  case Builtin::BI__sync_fetch_and_and:
900  case Builtin::BI__sync_fetch_and_and_1:
901  case Builtin::BI__sync_fetch_and_and_2:
902  case Builtin::BI__sync_fetch_and_and_4:
903  case Builtin::BI__sync_fetch_and_and_8:
904  case Builtin::BI__sync_fetch_and_and_16:
905    BuiltinIndex = 3;
906    break;
907
908  case Builtin::BI__sync_fetch_and_xor:
909  case Builtin::BI__sync_fetch_and_xor_1:
910  case Builtin::BI__sync_fetch_and_xor_2:
911  case Builtin::BI__sync_fetch_and_xor_4:
912  case Builtin::BI__sync_fetch_and_xor_8:
913  case Builtin::BI__sync_fetch_and_xor_16:
914    BuiltinIndex = 4;
915    break;
916
917  case Builtin::BI__sync_add_and_fetch:
918  case Builtin::BI__sync_add_and_fetch_1:
919  case Builtin::BI__sync_add_and_fetch_2:
920  case Builtin::BI__sync_add_and_fetch_4:
921  case Builtin::BI__sync_add_and_fetch_8:
922  case Builtin::BI__sync_add_and_fetch_16:
923    BuiltinIndex = 5;
924    break;
925
926  case Builtin::BI__sync_sub_and_fetch:
927  case Builtin::BI__sync_sub_and_fetch_1:
928  case Builtin::BI__sync_sub_and_fetch_2:
929  case Builtin::BI__sync_sub_and_fetch_4:
930  case Builtin::BI__sync_sub_and_fetch_8:
931  case Builtin::BI__sync_sub_and_fetch_16:
932    BuiltinIndex = 6;
933    break;
934
935  case Builtin::BI__sync_and_and_fetch:
936  case Builtin::BI__sync_and_and_fetch_1:
937  case Builtin::BI__sync_and_and_fetch_2:
938  case Builtin::BI__sync_and_and_fetch_4:
939  case Builtin::BI__sync_and_and_fetch_8:
940  case Builtin::BI__sync_and_and_fetch_16:
941    BuiltinIndex = 7;
942    break;
943
944  case Builtin::BI__sync_or_and_fetch:
945  case Builtin::BI__sync_or_and_fetch_1:
946  case Builtin::BI__sync_or_and_fetch_2:
947  case Builtin::BI__sync_or_and_fetch_4:
948  case Builtin::BI__sync_or_and_fetch_8:
949  case Builtin::BI__sync_or_and_fetch_16:
950    BuiltinIndex = 8;
951    break;
952
953  case Builtin::BI__sync_xor_and_fetch:
954  case Builtin::BI__sync_xor_and_fetch_1:
955  case Builtin::BI__sync_xor_and_fetch_2:
956  case Builtin::BI__sync_xor_and_fetch_4:
957  case Builtin::BI__sync_xor_and_fetch_8:
958  case Builtin::BI__sync_xor_and_fetch_16:
959    BuiltinIndex = 9;
960    break;
961
962  case Builtin::BI__sync_val_compare_and_swap:
963  case Builtin::BI__sync_val_compare_and_swap_1:
964  case Builtin::BI__sync_val_compare_and_swap_2:
965  case Builtin::BI__sync_val_compare_and_swap_4:
966  case Builtin::BI__sync_val_compare_and_swap_8:
967  case Builtin::BI__sync_val_compare_and_swap_16:
968    BuiltinIndex = 10;
969    NumFixed = 2;
970    break;
971
972  case Builtin::BI__sync_bool_compare_and_swap:
973  case Builtin::BI__sync_bool_compare_and_swap_1:
974  case Builtin::BI__sync_bool_compare_and_swap_2:
975  case Builtin::BI__sync_bool_compare_and_swap_4:
976  case Builtin::BI__sync_bool_compare_and_swap_8:
977  case Builtin::BI__sync_bool_compare_and_swap_16:
978    BuiltinIndex = 11;
979    NumFixed = 2;
980    ResultType = Context.BoolTy;
981    break;
982
983  case Builtin::BI__sync_lock_test_and_set:
984  case Builtin::BI__sync_lock_test_and_set_1:
985  case Builtin::BI__sync_lock_test_and_set_2:
986  case Builtin::BI__sync_lock_test_and_set_4:
987  case Builtin::BI__sync_lock_test_and_set_8:
988  case Builtin::BI__sync_lock_test_and_set_16:
989    BuiltinIndex = 12;
990    break;
991
992  case Builtin::BI__sync_lock_release:
993  case Builtin::BI__sync_lock_release_1:
994  case Builtin::BI__sync_lock_release_2:
995  case Builtin::BI__sync_lock_release_4:
996  case Builtin::BI__sync_lock_release_8:
997  case Builtin::BI__sync_lock_release_16:
998    BuiltinIndex = 13;
999    NumFixed = 0;
1000    ResultType = Context.VoidTy;
1001    break;
1002
1003  case Builtin::BI__sync_swap:
1004  case Builtin::BI__sync_swap_1:
1005  case Builtin::BI__sync_swap_2:
1006  case Builtin::BI__sync_swap_4:
1007  case Builtin::BI__sync_swap_8:
1008  case Builtin::BI__sync_swap_16:
1009    BuiltinIndex = 14;
1010    break;
1011  }
1012
1013  // Now that we know how many fixed arguments we expect, first check that we
1014  // have at least that many.
1015  if (TheCall->getNumArgs() < 1+NumFixed) {
1016    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1017      << 0 << 1+NumFixed << TheCall->getNumArgs()
1018      << TheCall->getCallee()->getSourceRange();
1019    return ExprError();
1020  }
1021
1022  // Get the decl for the concrete builtin from this, we can tell what the
1023  // concrete integer type we should convert to is.
1024  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1025  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1026  IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
1027  FunctionDecl *NewBuiltinDecl =
1028    cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
1029                                           TUScope, false, DRE->getLocStart()));
1030
1031  // The first argument --- the pointer --- has a fixed type; we
1032  // deduce the types of the rest of the arguments accordingly.  Walk
1033  // the remaining arguments, converting them to the deduced value type.
1034  for (unsigned i = 0; i != NumFixed; ++i) {
1035    ExprResult Arg = TheCall->getArg(i+1);
1036
1037    // GCC does an implicit conversion to the pointer or integer ValType.  This
1038    // can fail in some cases (1i -> int**), check for this error case now.
1039    // Initialize the argument.
1040    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1041                                                   ValType, /*consume*/ false);
1042    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1043    if (Arg.isInvalid())
1044      return ExprError();
1045
1046    // Okay, we have something that *can* be converted to the right type.  Check
1047    // to see if there is a potentially weird extension going on here.  This can
1048    // happen when you do an atomic operation on something like an char* and
1049    // pass in 42.  The 42 gets converted to char.  This is even more strange
1050    // for things like 45.123 -> char, etc.
1051    // FIXME: Do this check.
1052    TheCall->setArg(i+1, Arg.take());
1053  }
1054
1055  ASTContext& Context = this->getASTContext();
1056
1057  // Create a new DeclRefExpr to refer to the new decl.
1058  DeclRefExpr* NewDRE = DeclRefExpr::Create(
1059      Context,
1060      DRE->getQualifierLoc(),
1061      NewBuiltinDecl,
1062      DRE->getLocation(),
1063      NewBuiltinDecl->getType(),
1064      DRE->getValueKind());
1065
1066  // Set the callee in the CallExpr.
1067  // FIXME: This leaks the original parens and implicit casts.
1068  ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
1069  if (PromotedCall.isInvalid())
1070    return ExprError();
1071  TheCall->setCallee(PromotedCall.take());
1072
1073  // Change the result type of the call to match the original value type. This
1074  // is arbitrary, but the codegen for these builtins ins design to handle it
1075  // gracefully.
1076  TheCall->setType(ResultType);
1077
1078  return move(TheCallResult);
1079}
1080
1081/// CheckObjCString - Checks that the argument to the builtin
1082/// CFString constructor is correct
1083/// Note: It might also make sense to do the UTF-16 conversion here (would
1084/// simplify the backend).
1085bool Sema::CheckObjCString(Expr *Arg) {
1086  Arg = Arg->IgnoreParenCasts();
1087  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1088
1089  if (!Literal || !Literal->isAscii()) {
1090    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1091      << Arg->getSourceRange();
1092    return true;
1093  }
1094
1095  if (Literal->containsNonAsciiOrNull()) {
1096    StringRef String = Literal->getString();
1097    unsigned NumBytes = String.size();
1098    SmallVector<UTF16, 128> ToBuf(NumBytes);
1099    const UTF8 *FromPtr = (UTF8 *)String.data();
1100    UTF16 *ToPtr = &ToBuf[0];
1101
1102    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1103                                                 &ToPtr, ToPtr + NumBytes,
1104                                                 strictConversion);
1105    // Check for conversion failure.
1106    if (Result != conversionOK)
1107      Diag(Arg->getLocStart(),
1108           diag::warn_cfstring_truncated) << Arg->getSourceRange();
1109  }
1110  return false;
1111}
1112
1113/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1114/// Emit an error and return true on failure, return false on success.
1115bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1116  Expr *Fn = TheCall->getCallee();
1117  if (TheCall->getNumArgs() > 2) {
1118    Diag(TheCall->getArg(2)->getLocStart(),
1119         diag::err_typecheck_call_too_many_args)
1120      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1121      << Fn->getSourceRange()
1122      << SourceRange(TheCall->getArg(2)->getLocStart(),
1123                     (*(TheCall->arg_end()-1))->getLocEnd());
1124    return true;
1125  }
1126
1127  if (TheCall->getNumArgs() < 2) {
1128    return Diag(TheCall->getLocEnd(),
1129      diag::err_typecheck_call_too_few_args_at_least)
1130      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1131  }
1132
1133  // Type-check the first argument normally.
1134  if (checkBuiltinArgument(*this, TheCall, 0))
1135    return true;
1136
1137  // Determine whether the current function is variadic or not.
1138  BlockScopeInfo *CurBlock = getCurBlock();
1139  bool isVariadic;
1140  if (CurBlock)
1141    isVariadic = CurBlock->TheDecl->isVariadic();
1142  else if (FunctionDecl *FD = getCurFunctionDecl())
1143    isVariadic = FD->isVariadic();
1144  else
1145    isVariadic = getCurMethodDecl()->isVariadic();
1146
1147  if (!isVariadic) {
1148    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1149    return true;
1150  }
1151
1152  // Verify that the second argument to the builtin is the last argument of the
1153  // current function or method.
1154  bool SecondArgIsLastNamedArgument = false;
1155  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1156
1157  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1158    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1159      // FIXME: This isn't correct for methods (results in bogus warning).
1160      // Get the last formal in the current function.
1161      const ParmVarDecl *LastArg;
1162      if (CurBlock)
1163        LastArg = *(CurBlock->TheDecl->param_end()-1);
1164      else if (FunctionDecl *FD = getCurFunctionDecl())
1165        LastArg = *(FD->param_end()-1);
1166      else
1167        LastArg = *(getCurMethodDecl()->param_end()-1);
1168      SecondArgIsLastNamedArgument = PV == LastArg;
1169    }
1170  }
1171
1172  if (!SecondArgIsLastNamedArgument)
1173    Diag(TheCall->getArg(1)->getLocStart(),
1174         diag::warn_second_parameter_of_va_start_not_last_named_argument);
1175  return false;
1176}
1177
1178/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1179/// friends.  This is declared to take (...), so we have to check everything.
1180bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1181  if (TheCall->getNumArgs() < 2)
1182    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1183      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1184  if (TheCall->getNumArgs() > 2)
1185    return Diag(TheCall->getArg(2)->getLocStart(),
1186                diag::err_typecheck_call_too_many_args)
1187      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1188      << SourceRange(TheCall->getArg(2)->getLocStart(),
1189                     (*(TheCall->arg_end()-1))->getLocEnd());
1190
1191  ExprResult OrigArg0 = TheCall->getArg(0);
1192  ExprResult OrigArg1 = TheCall->getArg(1);
1193
1194  // Do standard promotions between the two arguments, returning their common
1195  // type.
1196  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1197  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1198    return true;
1199
1200  // Make sure any conversions are pushed back into the call; this is
1201  // type safe since unordered compare builtins are declared as "_Bool
1202  // foo(...)".
1203  TheCall->setArg(0, OrigArg0.get());
1204  TheCall->setArg(1, OrigArg1.get());
1205
1206  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1207    return false;
1208
1209  // If the common type isn't a real floating type, then the arguments were
1210  // invalid for this operation.
1211  if (!Res->isRealFloatingType())
1212    return Diag(OrigArg0.get()->getLocStart(),
1213                diag::err_typecheck_call_invalid_ordered_compare)
1214      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1215      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1216
1217  return false;
1218}
1219
1220/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1221/// __builtin_isnan and friends.  This is declared to take (...), so we have
1222/// to check everything. We expect the last argument to be a floating point
1223/// value.
1224bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1225  if (TheCall->getNumArgs() < NumArgs)
1226    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1227      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1228  if (TheCall->getNumArgs() > NumArgs)
1229    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1230                diag::err_typecheck_call_too_many_args)
1231      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1232      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1233                     (*(TheCall->arg_end()-1))->getLocEnd());
1234
1235  Expr *OrigArg = TheCall->getArg(NumArgs-1);
1236
1237  if (OrigArg->isTypeDependent())
1238    return false;
1239
1240  // This operation requires a non-_Complex floating-point number.
1241  if (!OrigArg->getType()->isRealFloatingType())
1242    return Diag(OrigArg->getLocStart(),
1243                diag::err_typecheck_call_invalid_unary_fp)
1244      << OrigArg->getType() << OrigArg->getSourceRange();
1245
1246  // If this is an implicit conversion from float -> double, remove it.
1247  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1248    Expr *CastArg = Cast->getSubExpr();
1249    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1250      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1251             "promotion from float to double is the only expected cast here");
1252      Cast->setSubExpr(0);
1253      TheCall->setArg(NumArgs-1, CastArg);
1254      OrigArg = CastArg;
1255    }
1256  }
1257
1258  return false;
1259}
1260
1261/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1262// This is declared to take (...), so we have to check everything.
1263ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1264  if (TheCall->getNumArgs() < 2)
1265    return ExprError(Diag(TheCall->getLocEnd(),
1266                          diag::err_typecheck_call_too_few_args_at_least)
1267      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1268      << TheCall->getSourceRange());
1269
1270  // Determine which of the following types of shufflevector we're checking:
1271  // 1) unary, vector mask: (lhs, mask)
1272  // 2) binary, vector mask: (lhs, rhs, mask)
1273  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1274  QualType resType = TheCall->getArg(0)->getType();
1275  unsigned numElements = 0;
1276
1277  if (!TheCall->getArg(0)->isTypeDependent() &&
1278      !TheCall->getArg(1)->isTypeDependent()) {
1279    QualType LHSType = TheCall->getArg(0)->getType();
1280    QualType RHSType = TheCall->getArg(1)->getType();
1281
1282    if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1283      Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1284        << SourceRange(TheCall->getArg(0)->getLocStart(),
1285                       TheCall->getArg(1)->getLocEnd());
1286      return ExprError();
1287    }
1288
1289    numElements = LHSType->getAs<VectorType>()->getNumElements();
1290    unsigned numResElements = TheCall->getNumArgs() - 2;
1291
1292    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1293    // with mask.  If so, verify that RHS is an integer vector type with the
1294    // same number of elts as lhs.
1295    if (TheCall->getNumArgs() == 2) {
1296      if (!RHSType->hasIntegerRepresentation() ||
1297          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1298        Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1299          << SourceRange(TheCall->getArg(1)->getLocStart(),
1300                         TheCall->getArg(1)->getLocEnd());
1301      numResElements = numElements;
1302    }
1303    else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1304      Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1305        << SourceRange(TheCall->getArg(0)->getLocStart(),
1306                       TheCall->getArg(1)->getLocEnd());
1307      return ExprError();
1308    } else if (numElements != numResElements) {
1309      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1310      resType = Context.getVectorType(eltType, numResElements,
1311                                      VectorType::GenericVector);
1312    }
1313  }
1314
1315  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1316    if (TheCall->getArg(i)->isTypeDependent() ||
1317        TheCall->getArg(i)->isValueDependent())
1318      continue;
1319
1320    llvm::APSInt Result(32);
1321    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1322      return ExprError(Diag(TheCall->getLocStart(),
1323                  diag::err_shufflevector_nonconstant_argument)
1324                << TheCall->getArg(i)->getSourceRange());
1325
1326    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1327      return ExprError(Diag(TheCall->getLocStart(),
1328                  diag::err_shufflevector_argument_too_large)
1329               << TheCall->getArg(i)->getSourceRange());
1330  }
1331
1332  SmallVector<Expr*, 32> exprs;
1333
1334  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1335    exprs.push_back(TheCall->getArg(i));
1336    TheCall->setArg(i, 0);
1337  }
1338
1339  return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1340                                            exprs.size(), resType,
1341                                            TheCall->getCallee()->getLocStart(),
1342                                            TheCall->getRParenLoc()));
1343}
1344
1345/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1346// This is declared to take (const void*, ...) and can take two
1347// optional constant int args.
1348bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1349  unsigned NumArgs = TheCall->getNumArgs();
1350
1351  if (NumArgs > 3)
1352    return Diag(TheCall->getLocEnd(),
1353             diag::err_typecheck_call_too_many_args_at_most)
1354             << 0 /*function call*/ << 3 << NumArgs
1355             << TheCall->getSourceRange();
1356
1357  // Argument 0 is checked for us and the remaining arguments must be
1358  // constant integers.
1359  for (unsigned i = 1; i != NumArgs; ++i) {
1360    Expr *Arg = TheCall->getArg(i);
1361
1362    llvm::APSInt Result;
1363    if (SemaBuiltinConstantArg(TheCall, i, Result))
1364      return true;
1365
1366    // FIXME: gcc issues a warning and rewrites these to 0. These
1367    // seems especially odd for the third argument since the default
1368    // is 3.
1369    if (i == 1) {
1370      if (Result.getLimitedValue() > 1)
1371        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1372             << "0" << "1" << Arg->getSourceRange();
1373    } else {
1374      if (Result.getLimitedValue() > 3)
1375        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1376            << "0" << "3" << Arg->getSourceRange();
1377    }
1378  }
1379
1380  return false;
1381}
1382
1383/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1384/// TheCall is a constant expression.
1385bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1386                                  llvm::APSInt &Result) {
1387  Expr *Arg = TheCall->getArg(ArgNum);
1388  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1389  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1390
1391  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1392
1393  if (!Arg->isIntegerConstantExpr(Result, Context))
1394    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1395                << FDecl->getDeclName() <<  Arg->getSourceRange();
1396
1397  return false;
1398}
1399
1400/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1401/// int type). This simply type checks that type is one of the defined
1402/// constants (0-3).
1403// For compatibility check 0-3, llvm only handles 0 and 2.
1404bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1405  llvm::APSInt Result;
1406
1407  // Check constant-ness first.
1408  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1409    return true;
1410
1411  Expr *Arg = TheCall->getArg(1);
1412  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1413    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1414             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1415  }
1416
1417  return false;
1418}
1419
1420/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1421/// This checks that val is a constant 1.
1422bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1423  Expr *Arg = TheCall->getArg(1);
1424  llvm::APSInt Result;
1425
1426  // TODO: This is less than ideal. Overload this to take a value.
1427  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1428    return true;
1429
1430  if (Result != 1)
1431    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1432             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1433
1434  return false;
1435}
1436
1437// Handle i > 1 ? "x" : "y", recursively.
1438bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1439                                  bool HasVAListArg,
1440                                  unsigned format_idx, unsigned firstDataArg,
1441                                  bool isPrintf, bool inFunctionCall) {
1442 tryAgain:
1443  if (E->isTypeDependent() || E->isValueDependent())
1444    return false;
1445
1446  E = E->IgnoreParens();
1447
1448  switch (E->getStmtClass()) {
1449  case Stmt::BinaryConditionalOperatorClass:
1450  case Stmt::ConditionalOperatorClass: {
1451    const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1452    return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1453                                  format_idx, firstDataArg, isPrintf,
1454                                  inFunctionCall)
1455        && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1456                                  format_idx, firstDataArg, isPrintf,
1457                                  inFunctionCall);
1458  }
1459
1460  case Stmt::IntegerLiteralClass:
1461    // Technically -Wformat-nonliteral does not warn about this case.
1462    // The behavior of printf and friends in this case is implementation
1463    // dependent.  Ideally if the format string cannot be null then
1464    // it should have a 'nonnull' attribute in the function prototype.
1465    return true;
1466
1467  case Stmt::ImplicitCastExprClass: {
1468    E = cast<ImplicitCastExpr>(E)->getSubExpr();
1469    goto tryAgain;
1470  }
1471
1472  case Stmt::OpaqueValueExprClass:
1473    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1474      E = src;
1475      goto tryAgain;
1476    }
1477    return false;
1478
1479  case Stmt::PredefinedExprClass:
1480    // While __func__, etc., are technically not string literals, they
1481    // cannot contain format specifiers and thus are not a security
1482    // liability.
1483    return true;
1484
1485  case Stmt::DeclRefExprClass: {
1486    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1487
1488    // As an exception, do not flag errors for variables binding to
1489    // const string literals.
1490    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1491      bool isConstant = false;
1492      QualType T = DR->getType();
1493
1494      if (const ArrayType *AT = Context.getAsArrayType(T)) {
1495        isConstant = AT->getElementType().isConstant(Context);
1496      } else if (const PointerType *PT = T->getAs<PointerType>()) {
1497        isConstant = T.isConstant(Context) &&
1498                     PT->getPointeeType().isConstant(Context);
1499      }
1500
1501      if (isConstant) {
1502        if (const Expr *Init = VD->getAnyInitializer())
1503          return SemaCheckStringLiteral(Init, TheCall,
1504                                        HasVAListArg, format_idx, firstDataArg,
1505                                        isPrintf, /*inFunctionCall*/false);
1506      }
1507
1508      // For vprintf* functions (i.e., HasVAListArg==true), we add a
1509      // special check to see if the format string is a function parameter
1510      // of the function calling the printf function.  If the function
1511      // has an attribute indicating it is a printf-like function, then we
1512      // should suppress warnings concerning non-literals being used in a call
1513      // to a vprintf function.  For example:
1514      //
1515      // void
1516      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1517      //      va_list ap;
1518      //      va_start(ap, fmt);
1519      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1520      //      ...
1521      //
1522      //
1523      //  FIXME: We don't have full attribute support yet, so just check to see
1524      //    if the argument is a DeclRefExpr that references a parameter.  We'll
1525      //    add proper support for checking the attribute later.
1526      if (HasVAListArg)
1527        if (isa<ParmVarDecl>(VD))
1528          return true;
1529    }
1530
1531    return false;
1532  }
1533
1534  case Stmt::CallExprClass: {
1535    const CallExpr *CE = cast<CallExpr>(E);
1536    if (const ImplicitCastExpr *ICE
1537          = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1538      if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1539        if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1540          if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1541            unsigned ArgIndex = FA->getFormatIdx();
1542            const Expr *Arg = CE->getArg(ArgIndex - 1);
1543
1544            return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1545                                          format_idx, firstDataArg, isPrintf,
1546                                          inFunctionCall);
1547          }
1548        }
1549      }
1550    }
1551
1552    return false;
1553  }
1554  case Stmt::ObjCStringLiteralClass:
1555  case Stmt::StringLiteralClass: {
1556    const StringLiteral *StrE = NULL;
1557
1558    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1559      StrE = ObjCFExpr->getString();
1560    else
1561      StrE = cast<StringLiteral>(E);
1562
1563    if (StrE) {
1564      CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1565                        firstDataArg, isPrintf, inFunctionCall);
1566      return true;
1567    }
1568
1569    return false;
1570  }
1571
1572  default:
1573    return false;
1574  }
1575}
1576
1577void
1578Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1579                            const Expr * const *ExprArgs,
1580                            SourceLocation CallSiteLoc) {
1581  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1582                                  e = NonNull->args_end();
1583       i != e; ++i) {
1584    const Expr *ArgExpr = ExprArgs[*i];
1585    if (ArgExpr->isNullPointerConstant(Context,
1586                                       Expr::NPC_ValueDependentIsNotNull))
1587      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1588  }
1589}
1590
1591/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1592/// functions) for correct use of format strings.
1593void
1594Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1595                                unsigned format_idx, unsigned firstDataArg,
1596                                bool isPrintf) {
1597
1598  const Expr *Fn = TheCall->getCallee();
1599
1600  // The way the format attribute works in GCC, the implicit this argument
1601  // of member functions is counted. However, it doesn't appear in our own
1602  // lists, so decrement format_idx in that case.
1603  if (isa<CXXMemberCallExpr>(TheCall)) {
1604    const CXXMethodDecl *method_decl =
1605      dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1606    if (method_decl && method_decl->isInstance()) {
1607      // Catch a format attribute mistakenly referring to the object argument.
1608      if (format_idx == 0)
1609        return;
1610      --format_idx;
1611      if(firstDataArg != 0)
1612        --firstDataArg;
1613    }
1614  }
1615
1616  // CHECK: printf/scanf-like function is called with no format string.
1617  if (format_idx >= TheCall->getNumArgs()) {
1618    Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1619      << Fn->getSourceRange();
1620    return;
1621  }
1622
1623  const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1624
1625  // CHECK: format string is not a string literal.
1626  //
1627  // Dynamically generated format strings are difficult to
1628  // automatically vet at compile time.  Requiring that format strings
1629  // are string literals: (1) permits the checking of format strings by
1630  // the compiler and thereby (2) can practically remove the source of
1631  // many format string exploits.
1632
1633  // Format string can be either ObjC string (e.g. @"%d") or
1634  // C string (e.g. "%d")
1635  // ObjC string uses the same format specifiers as C string, so we can use
1636  // the same format string checking logic for both ObjC and C strings.
1637  if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1638                             firstDataArg, isPrintf))
1639    return;  // Literal format string found, check done!
1640
1641  // If there are no arguments specified, warn with -Wformat-security, otherwise
1642  // warn only with -Wformat-nonliteral.
1643  if (TheCall->getNumArgs() == format_idx+1)
1644    Diag(TheCall->getArg(format_idx)->getLocStart(),
1645         diag::warn_format_nonliteral_noargs)
1646      << OrigFormatExpr->getSourceRange();
1647  else
1648    Diag(TheCall->getArg(format_idx)->getLocStart(),
1649         diag::warn_format_nonliteral)
1650           << OrigFormatExpr->getSourceRange();
1651}
1652
1653namespace {
1654class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1655protected:
1656  Sema &S;
1657  const StringLiteral *FExpr;
1658  const Expr *OrigFormatExpr;
1659  const unsigned FirstDataArg;
1660  const unsigned NumDataArgs;
1661  const bool IsObjCLiteral;
1662  const char *Beg; // Start of format string.
1663  const bool HasVAListArg;
1664  const CallExpr *TheCall;
1665  unsigned FormatIdx;
1666  llvm::BitVector CoveredArgs;
1667  bool usesPositionalArgs;
1668  bool atFirstArg;
1669  bool inFunctionCall;
1670public:
1671  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1672                     const Expr *origFormatExpr, unsigned firstDataArg,
1673                     unsigned numDataArgs, bool isObjCLiteral,
1674                     const char *beg, bool hasVAListArg,
1675                     const CallExpr *theCall, unsigned formatIdx,
1676                     bool inFunctionCall)
1677    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1678      FirstDataArg(firstDataArg),
1679      NumDataArgs(numDataArgs),
1680      IsObjCLiteral(isObjCLiteral), Beg(beg),
1681      HasVAListArg(hasVAListArg),
1682      TheCall(theCall), FormatIdx(formatIdx),
1683      usesPositionalArgs(false), atFirstArg(true),
1684      inFunctionCall(inFunctionCall) {
1685        CoveredArgs.resize(numDataArgs);
1686        CoveredArgs.reset();
1687      }
1688
1689  void DoneProcessing();
1690
1691  void HandleIncompleteSpecifier(const char *startSpecifier,
1692                                 unsigned specifierLen);
1693
1694  virtual void HandleInvalidPosition(const char *startSpecifier,
1695                                     unsigned specifierLen,
1696                                     analyze_format_string::PositionContext p);
1697
1698  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1699
1700  void HandleNullChar(const char *nullCharacter);
1701
1702  template <typename Range>
1703  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1704                                   const Expr *ArgumentExpr,
1705                                   PartialDiagnostic PDiag,
1706                                   SourceLocation StringLoc,
1707                                   bool IsStringLocation, Range StringRange,
1708                                   FixItHint Fixit = FixItHint());
1709
1710protected:
1711  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1712                                        const char *startSpec,
1713                                        unsigned specifierLen,
1714                                        const char *csStart, unsigned csLen);
1715
1716  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1717                                         const char *startSpec,
1718                                         unsigned specifierLen);
1719
1720  SourceRange getFormatStringRange();
1721  CharSourceRange getSpecifierRange(const char *startSpecifier,
1722                                    unsigned specifierLen);
1723  SourceLocation getLocationOfByte(const char *x);
1724
1725  const Expr *getDataArg(unsigned i) const;
1726
1727  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1728                    const analyze_format_string::ConversionSpecifier &CS,
1729                    const char *startSpecifier, unsigned specifierLen,
1730                    unsigned argIndex);
1731
1732  template <typename Range>
1733  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1734                            bool IsStringLocation, Range StringRange,
1735                            FixItHint Fixit = FixItHint());
1736
1737  void CheckPositionalAndNonpositionalArgs(
1738      const analyze_format_string::FormatSpecifier *FS);
1739};
1740}
1741
1742SourceRange CheckFormatHandler::getFormatStringRange() {
1743  return OrigFormatExpr->getSourceRange();
1744}
1745
1746CharSourceRange CheckFormatHandler::
1747getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1748  SourceLocation Start = getLocationOfByte(startSpecifier);
1749  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1750
1751  // Advance the end SourceLocation by one due to half-open ranges.
1752  End = End.getLocWithOffset(1);
1753
1754  return CharSourceRange::getCharRange(Start, End);
1755}
1756
1757SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1758  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1759}
1760
1761void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1762                                                   unsigned specifierLen){
1763  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1764                       getLocationOfByte(startSpecifier),
1765                       /*IsStringLocation*/true,
1766                       getSpecifierRange(startSpecifier, specifierLen));
1767}
1768
1769void
1770CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1771                                     analyze_format_string::PositionContext p) {
1772  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1773                         << (unsigned) p,
1774                       getLocationOfByte(startPos), /*IsStringLocation*/true,
1775                       getSpecifierRange(startPos, posLen));
1776}
1777
1778void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1779                                            unsigned posLen) {
1780  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1781                               getLocationOfByte(startPos),
1782                               /*IsStringLocation*/true,
1783                               getSpecifierRange(startPos, posLen));
1784}
1785
1786void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1787  if (!IsObjCLiteral) {
1788    // The presence of a null character is likely an error.
1789    EmitFormatDiagnostic(
1790      S.PDiag(diag::warn_printf_format_string_contains_null_char),
1791      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1792      getFormatStringRange());
1793  }
1794}
1795
1796const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1797  return TheCall->getArg(FirstDataArg + i);
1798}
1799
1800void CheckFormatHandler::DoneProcessing() {
1801    // Does the number of data arguments exceed the number of
1802    // format conversions in the format string?
1803  if (!HasVAListArg) {
1804      // Find any arguments that weren't covered.
1805    CoveredArgs.flip();
1806    signed notCoveredArg = CoveredArgs.find_first();
1807    if (notCoveredArg >= 0) {
1808      assert((unsigned)notCoveredArg < NumDataArgs);
1809      EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1810                           getDataArg((unsigned) notCoveredArg)->getLocStart(),
1811                           /*IsStringLocation*/false, getFormatStringRange());
1812    }
1813  }
1814}
1815
1816bool
1817CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1818                                                     SourceLocation Loc,
1819                                                     const char *startSpec,
1820                                                     unsigned specifierLen,
1821                                                     const char *csStart,
1822                                                     unsigned csLen) {
1823
1824  bool keepGoing = true;
1825  if (argIndex < NumDataArgs) {
1826    // Consider the argument coverered, even though the specifier doesn't
1827    // make sense.
1828    CoveredArgs.set(argIndex);
1829  }
1830  else {
1831    // If argIndex exceeds the number of data arguments we
1832    // don't issue a warning because that is just a cascade of warnings (and
1833    // they may have intended '%%' anyway). We don't want to continue processing
1834    // the format string after this point, however, as we will like just get
1835    // gibberish when trying to match arguments.
1836    keepGoing = false;
1837  }
1838
1839  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1840                         << StringRef(csStart, csLen),
1841                       Loc, /*IsStringLocation*/true,
1842                       getSpecifierRange(startSpec, specifierLen));
1843
1844  return keepGoing;
1845}
1846
1847void
1848CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1849                                                      const char *startSpec,
1850                                                      unsigned specifierLen) {
1851  EmitFormatDiagnostic(
1852    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1853    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1854}
1855
1856bool
1857CheckFormatHandler::CheckNumArgs(
1858  const analyze_format_string::FormatSpecifier &FS,
1859  const analyze_format_string::ConversionSpecifier &CS,
1860  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1861
1862  if (argIndex >= NumDataArgs) {
1863    PartialDiagnostic PDiag = FS.usesPositionalArg()
1864      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1865           << (argIndex+1) << NumDataArgs)
1866      : S.PDiag(diag::warn_printf_insufficient_data_args);
1867    EmitFormatDiagnostic(
1868      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1869      getSpecifierRange(startSpecifier, specifierLen));
1870    return false;
1871  }
1872  return true;
1873}
1874
1875template<typename Range>
1876void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1877                                              SourceLocation Loc,
1878                                              bool IsStringLocation,
1879                                              Range StringRange,
1880                                              FixItHint FixIt) {
1881  EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1882                       Loc, IsStringLocation, StringRange, FixIt);
1883}
1884
1885/// \brief If the format string is not within the funcion call, emit a note
1886/// so that the function call and string are in diagnostic messages.
1887///
1888/// \param inFunctionCall if true, the format string is within the function
1889/// call and only one diagnostic message will be produced.  Otherwise, an
1890/// extra note will be emitted pointing to location of the format string.
1891///
1892/// \param ArgumentExpr the expression that is passed as the format string
1893/// argument in the function call.  Used for getting locations when two
1894/// diagnostics are emitted.
1895///
1896/// \param PDiag the callee should already have provided any strings for the
1897/// diagnostic message.  This function only adds locations and fixits
1898/// to diagnostics.
1899///
1900/// \param Loc primary location for diagnostic.  If two diagnostics are
1901/// required, one will be at Loc and a new SourceLocation will be created for
1902/// the other one.
1903///
1904/// \param IsStringLocation if true, Loc points to the format string should be
1905/// used for the note.  Otherwise, Loc points to the argument list and will
1906/// be used with PDiag.
1907///
1908/// \param StringRange some or all of the string to highlight.  This is
1909/// templated so it can accept either a CharSourceRange or a SourceRange.
1910///
1911/// \param Fixit optional fix it hint for the format string.
1912template<typename Range>
1913void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1914                                              const Expr *ArgumentExpr,
1915                                              PartialDiagnostic PDiag,
1916                                              SourceLocation Loc,
1917                                              bool IsStringLocation,
1918                                              Range StringRange,
1919                                              FixItHint FixIt) {
1920  if (InFunctionCall)
1921    S.Diag(Loc, PDiag) << StringRange << FixIt;
1922  else {
1923    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1924      << ArgumentExpr->getSourceRange();
1925    S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1926           diag::note_format_string_defined)
1927      << StringRange << FixIt;
1928  }
1929}
1930
1931//===--- CHECK: Printf format string checking ------------------------------===//
1932
1933namespace {
1934class CheckPrintfHandler : public CheckFormatHandler {
1935public:
1936  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1937                     const Expr *origFormatExpr, unsigned firstDataArg,
1938                     unsigned numDataArgs, bool isObjCLiteral,
1939                     const char *beg, bool hasVAListArg,
1940                     const CallExpr *theCall, unsigned formatIdx,
1941                     bool inFunctionCall)
1942  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1943                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
1944                       theCall, formatIdx, inFunctionCall) {}
1945
1946
1947  bool HandleInvalidPrintfConversionSpecifier(
1948                                      const analyze_printf::PrintfSpecifier &FS,
1949                                      const char *startSpecifier,
1950                                      unsigned specifierLen);
1951
1952  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1953                             const char *startSpecifier,
1954                             unsigned specifierLen);
1955
1956  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1957                    const char *startSpecifier, unsigned specifierLen);
1958  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1959                           const analyze_printf::OptionalAmount &Amt,
1960                           unsigned type,
1961                           const char *startSpecifier, unsigned specifierLen);
1962  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1963                  const analyze_printf::OptionalFlag &flag,
1964                  const char *startSpecifier, unsigned specifierLen);
1965  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1966                         const analyze_printf::OptionalFlag &ignoredFlag,
1967                         const analyze_printf::OptionalFlag &flag,
1968                         const char *startSpecifier, unsigned specifierLen);
1969};
1970}
1971
1972bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1973                                      const analyze_printf::PrintfSpecifier &FS,
1974                                      const char *startSpecifier,
1975                                      unsigned specifierLen) {
1976  const analyze_printf::PrintfConversionSpecifier &CS =
1977    FS.getConversionSpecifier();
1978
1979  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1980                                          getLocationOfByte(CS.getStart()),
1981                                          startSpecifier, specifierLen,
1982                                          CS.getStart(), CS.getLength());
1983}
1984
1985bool CheckPrintfHandler::HandleAmount(
1986                               const analyze_format_string::OptionalAmount &Amt,
1987                               unsigned k, const char *startSpecifier,
1988                               unsigned specifierLen) {
1989
1990  if (Amt.hasDataArgument()) {
1991    if (!HasVAListArg) {
1992      unsigned argIndex = Amt.getArgIndex();
1993      if (argIndex >= NumDataArgs) {
1994        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1995                               << k,
1996                             getLocationOfByte(Amt.getStart()),
1997                             /*IsStringLocation*/true,
1998                             getSpecifierRange(startSpecifier, specifierLen));
1999        // Don't do any more checking.  We will just emit
2000        // spurious errors.
2001        return false;
2002      }
2003
2004      // Type check the data argument.  It should be an 'int'.
2005      // Although not in conformance with C99, we also allow the argument to be
2006      // an 'unsigned int' as that is a reasonably safe case.  GCC also
2007      // doesn't emit a warning for that case.
2008      CoveredArgs.set(argIndex);
2009      const Expr *Arg = getDataArg(argIndex);
2010      QualType T = Arg->getType();
2011
2012      const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
2013      assert(ATR.isValid());
2014
2015      if (!ATR.matchesType(S.Context, T)) {
2016        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2017                               << k << ATR.getRepresentativeTypeName(S.Context)
2018                               << T << Arg->getSourceRange(),
2019                             getLocationOfByte(Amt.getStart()),
2020                             /*IsStringLocation*/true,
2021                             getSpecifierRange(startSpecifier, specifierLen));
2022        // Don't do any more checking.  We will just emit
2023        // spurious errors.
2024        return false;
2025      }
2026    }
2027  }
2028  return true;
2029}
2030
2031void CheckPrintfHandler::HandleInvalidAmount(
2032                                      const analyze_printf::PrintfSpecifier &FS,
2033                                      const analyze_printf::OptionalAmount &Amt,
2034                                      unsigned type,
2035                                      const char *startSpecifier,
2036                                      unsigned specifierLen) {
2037  const analyze_printf::PrintfConversionSpecifier &CS =
2038    FS.getConversionSpecifier();
2039
2040  FixItHint fixit =
2041    Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2042      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2043                                 Amt.getConstantLength()))
2044      : FixItHint();
2045
2046  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2047                         << type << CS.toString(),
2048                       getLocationOfByte(Amt.getStart()),
2049                       /*IsStringLocation*/true,
2050                       getSpecifierRange(startSpecifier, specifierLen),
2051                       fixit);
2052}
2053
2054void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2055                                    const analyze_printf::OptionalFlag &flag,
2056                                    const char *startSpecifier,
2057                                    unsigned specifierLen) {
2058  // Warn about pointless flag with a fixit removal.
2059  const analyze_printf::PrintfConversionSpecifier &CS =
2060    FS.getConversionSpecifier();
2061  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2062                         << flag.toString() << CS.toString(),
2063                       getLocationOfByte(flag.getPosition()),
2064                       /*IsStringLocation*/true,
2065                       getSpecifierRange(startSpecifier, specifierLen),
2066                       FixItHint::CreateRemoval(
2067                         getSpecifierRange(flag.getPosition(), 1)));
2068}
2069
2070void CheckPrintfHandler::HandleIgnoredFlag(
2071                                const analyze_printf::PrintfSpecifier &FS,
2072                                const analyze_printf::OptionalFlag &ignoredFlag,
2073                                const analyze_printf::OptionalFlag &flag,
2074                                const char *startSpecifier,
2075                                unsigned specifierLen) {
2076  // Warn about ignored flag with a fixit removal.
2077  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2078                         << ignoredFlag.toString() << flag.toString(),
2079                       getLocationOfByte(ignoredFlag.getPosition()),
2080                       /*IsStringLocation*/true,
2081                       getSpecifierRange(startSpecifier, specifierLen),
2082                       FixItHint::CreateRemoval(
2083                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
2084}
2085
2086bool
2087CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2088                                            &FS,
2089                                          const char *startSpecifier,
2090                                          unsigned specifierLen) {
2091
2092  using namespace analyze_format_string;
2093  using namespace analyze_printf;
2094  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2095
2096  if (FS.consumesDataArgument()) {
2097    if (atFirstArg) {
2098        atFirstArg = false;
2099        usesPositionalArgs = FS.usesPositionalArg();
2100    }
2101    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2102      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2103                                        startSpecifier, specifierLen);
2104      return false;
2105    }
2106  }
2107
2108  // First check if the field width, precision, and conversion specifier
2109  // have matching data arguments.
2110  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2111                    startSpecifier, specifierLen)) {
2112    return false;
2113  }
2114
2115  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2116                    startSpecifier, specifierLen)) {
2117    return false;
2118  }
2119
2120  if (!CS.consumesDataArgument()) {
2121    // FIXME: Technically specifying a precision or field width here
2122    // makes no sense.  Worth issuing a warning at some point.
2123    return true;
2124  }
2125
2126  // Consume the argument.
2127  unsigned argIndex = FS.getArgIndex();
2128  if (argIndex < NumDataArgs) {
2129    // The check to see if the argIndex is valid will come later.
2130    // We set the bit here because we may exit early from this
2131    // function if we encounter some other error.
2132    CoveredArgs.set(argIndex);
2133  }
2134
2135  // Check for using an Objective-C specific conversion specifier
2136  // in a non-ObjC literal.
2137  if (!IsObjCLiteral && CS.isObjCArg()) {
2138    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2139                                                  specifierLen);
2140  }
2141
2142  // Check for invalid use of field width
2143  if (!FS.hasValidFieldWidth()) {
2144    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2145        startSpecifier, specifierLen);
2146  }
2147
2148  // Check for invalid use of precision
2149  if (!FS.hasValidPrecision()) {
2150    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2151        startSpecifier, specifierLen);
2152  }
2153
2154  // Check each flag does not conflict with any other component.
2155  if (!FS.hasValidThousandsGroupingPrefix())
2156    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
2157  if (!FS.hasValidLeadingZeros())
2158    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
2159  if (!FS.hasValidPlusPrefix())
2160    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
2161  if (!FS.hasValidSpacePrefix())
2162    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
2163  if (!FS.hasValidAlternativeForm())
2164    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
2165  if (!FS.hasValidLeftJustified())
2166    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
2167
2168  // Check that flags are not ignored by another flag
2169  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
2170    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
2171        startSpecifier, specifierLen);
2172  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
2173    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2174            startSpecifier, specifierLen);
2175
2176  // Check the length modifier is valid with the given conversion specifier.
2177  const LengthModifier &LM = FS.getLengthModifier();
2178  if (!FS.hasValidLengthModifier())
2179    EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2180                           << LM.toString() << CS.toString(),
2181                         getLocationOfByte(LM.getStart()),
2182                         /*IsStringLocation*/true,
2183                         getSpecifierRange(startSpecifier, specifierLen),
2184                         FixItHint::CreateRemoval(
2185                           getSpecifierRange(LM.getStart(),
2186                                             LM.getLength())));
2187
2188  // Are we using '%n'?
2189  if (CS.getKind() == ConversionSpecifier::nArg) {
2190    // Issue a warning about this being a possible security issue.
2191    EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2192                         getLocationOfByte(CS.getStart()),
2193                         /*IsStringLocation*/true,
2194                         getSpecifierRange(startSpecifier, specifierLen));
2195    // Continue checking the other format specifiers.
2196    return true;
2197  }
2198
2199  // The remaining checks depend on the data arguments.
2200  if (HasVAListArg)
2201    return true;
2202
2203  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2204    return false;
2205
2206  // Now type check the data expression that matches the
2207  // format specifier.
2208  const Expr *Ex = getDataArg(argIndex);
2209  const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2210  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2211    // Check if we didn't match because of an implicit cast from a 'char'
2212    // or 'short' to an 'int'.  This is done because printf is a varargs
2213    // function.
2214    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
2215      if (ICE->getType() == S.Context.IntTy) {
2216        // All further checking is done on the subexpression.
2217        Ex = ICE->getSubExpr();
2218        if (ATR.matchesType(S.Context, Ex->getType()))
2219          return true;
2220      }
2221
2222    // We may be able to offer a FixItHint if it is a supported type.
2223    PrintfSpecifier fixedFS = FS;
2224    bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2225
2226    if (success) {
2227      // Get the fix string from the fixed format specifier
2228      llvm::SmallString<128> buf;
2229      llvm::raw_svector_ostream os(buf);
2230      fixedFS.toString(os);
2231
2232      EmitFormatDiagnostic(
2233        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2234          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2235          << Ex->getSourceRange(),
2236        getLocationOfByte(CS.getStart()),
2237        /*IsStringLocation*/true,
2238        getSpecifierRange(startSpecifier, specifierLen),
2239        FixItHint::CreateReplacement(
2240          getSpecifierRange(startSpecifier, specifierLen),
2241          os.str()));
2242    }
2243    else {
2244      S.Diag(getLocationOfByte(CS.getStart()),
2245             diag::warn_printf_conversion_argument_type_mismatch)
2246        << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2247        << getSpecifierRange(startSpecifier, specifierLen)
2248        << Ex->getSourceRange();
2249    }
2250  }
2251
2252  return true;
2253}
2254
2255//===--- CHECK: Scanf format string checking ------------------------------===//
2256
2257namespace {
2258class CheckScanfHandler : public CheckFormatHandler {
2259public:
2260  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2261                    const Expr *origFormatExpr, unsigned firstDataArg,
2262                    unsigned numDataArgs, bool isObjCLiteral,
2263                    const char *beg, bool hasVAListArg,
2264                    const CallExpr *theCall, unsigned formatIdx,
2265                    bool inFunctionCall)
2266  : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2267                       numDataArgs, isObjCLiteral, beg, hasVAListArg,
2268                       theCall, formatIdx, inFunctionCall) {}
2269
2270  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2271                            const char *startSpecifier,
2272                            unsigned specifierLen);
2273
2274  bool HandleInvalidScanfConversionSpecifier(
2275          const analyze_scanf::ScanfSpecifier &FS,
2276          const char *startSpecifier,
2277          unsigned specifierLen);
2278
2279  void HandleIncompleteScanList(const char *start, const char *end);
2280};
2281}
2282
2283void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2284                                                 const char *end) {
2285  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2286                       getLocationOfByte(end), /*IsStringLocation*/true,
2287                       getSpecifierRange(start, end - start));
2288}
2289
2290bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2291                                        const analyze_scanf::ScanfSpecifier &FS,
2292                                        const char *startSpecifier,
2293                                        unsigned specifierLen) {
2294
2295  const analyze_scanf::ScanfConversionSpecifier &CS =
2296    FS.getConversionSpecifier();
2297
2298  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2299                                          getLocationOfByte(CS.getStart()),
2300                                          startSpecifier, specifierLen,
2301                                          CS.getStart(), CS.getLength());
2302}
2303
2304bool CheckScanfHandler::HandleScanfSpecifier(
2305                                       const analyze_scanf::ScanfSpecifier &FS,
2306                                       const char *startSpecifier,
2307                                       unsigned specifierLen) {
2308
2309  using namespace analyze_scanf;
2310  using namespace analyze_format_string;
2311
2312  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2313
2314  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2315  // be used to decide if we are using positional arguments consistently.
2316  if (FS.consumesDataArgument()) {
2317    if (atFirstArg) {
2318      atFirstArg = false;
2319      usesPositionalArgs = FS.usesPositionalArg();
2320    }
2321    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2322      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2323                                        startSpecifier, specifierLen);
2324      return false;
2325    }
2326  }
2327
2328  // Check if the field with is non-zero.
2329  const OptionalAmount &Amt = FS.getFieldWidth();
2330  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2331    if (Amt.getConstantAmount() == 0) {
2332      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2333                                                   Amt.getConstantLength());
2334      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2335                           getLocationOfByte(Amt.getStart()),
2336                           /*IsStringLocation*/true, R,
2337                           FixItHint::CreateRemoval(R));
2338    }
2339  }
2340
2341  if (!FS.consumesDataArgument()) {
2342    // FIXME: Technically specifying a precision or field width here
2343    // makes no sense.  Worth issuing a warning at some point.
2344    return true;
2345  }
2346
2347  // Consume the argument.
2348  unsigned argIndex = FS.getArgIndex();
2349  if (argIndex < NumDataArgs) {
2350      // The check to see if the argIndex is valid will come later.
2351      // We set the bit here because we may exit early from this
2352      // function if we encounter some other error.
2353    CoveredArgs.set(argIndex);
2354  }
2355
2356  // Check the length modifier is valid with the given conversion specifier.
2357  const LengthModifier &LM = FS.getLengthModifier();
2358  if (!FS.hasValidLengthModifier()) {
2359    S.Diag(getLocationOfByte(LM.getStart()),
2360           diag::warn_format_nonsensical_length)
2361      << LM.toString() << CS.toString()
2362      << getSpecifierRange(startSpecifier, specifierLen)
2363      << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2364                                                    LM.getLength()));
2365  }
2366
2367  // The remaining checks depend on the data arguments.
2368  if (HasVAListArg)
2369    return true;
2370
2371  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2372    return false;
2373
2374  // Check that the argument type matches the format specifier.
2375  const Expr *Ex = getDataArg(argIndex);
2376  const analyze_scanf::ScanfArgTypeResult &ATR = FS.getArgType(S.Context);
2377  if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2378    ScanfSpecifier fixedFS = FS;
2379    bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
2380
2381    if (success) {
2382      // Get the fix string from the fixed format specifier.
2383      llvm::SmallString<128> buf;
2384      llvm::raw_svector_ostream os(buf);
2385      fixedFS.toString(os);
2386
2387      EmitFormatDiagnostic(
2388        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2389          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2390          << Ex->getSourceRange(),
2391        getLocationOfByte(CS.getStart()),
2392        /*IsStringLocation*/true,
2393        getSpecifierRange(startSpecifier, specifierLen),
2394        FixItHint::CreateReplacement(
2395          getSpecifierRange(startSpecifier, specifierLen),
2396          os.str()));
2397    } else {
2398      S.Diag(getLocationOfByte(CS.getStart()),
2399             diag::warn_printf_conversion_argument_type_mismatch)
2400          << ATR.getRepresentativeTypeName(S.Context) << Ex->getType()
2401          << getSpecifierRange(startSpecifier, specifierLen)
2402          << Ex->getSourceRange();
2403    }
2404  }
2405
2406  return true;
2407}
2408
2409void Sema::CheckFormatString(const StringLiteral *FExpr,
2410                             const Expr *OrigFormatExpr,
2411                             const CallExpr *TheCall, bool HasVAListArg,
2412                             unsigned format_idx, unsigned firstDataArg,
2413                             bool isPrintf, bool inFunctionCall) {
2414
2415  // CHECK: is the format string a wide literal?
2416  if (!FExpr->isAscii()) {
2417    CheckFormatHandler::EmitFormatDiagnostic(
2418      *this, inFunctionCall, TheCall->getArg(format_idx),
2419      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2420      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2421    return;
2422  }
2423
2424  // Str - The format string.  NOTE: this is NOT null-terminated!
2425  StringRef StrRef = FExpr->getString();
2426  const char *Str = StrRef.data();
2427  unsigned StrLen = StrRef.size();
2428  const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
2429
2430  // CHECK: empty format string?
2431  if (StrLen == 0 && numDataArgs > 0) {
2432    CheckFormatHandler::EmitFormatDiagnostic(
2433      *this, inFunctionCall, TheCall->getArg(format_idx),
2434      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2435      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
2436    return;
2437  }
2438
2439  if (isPrintf) {
2440    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2441                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2442                         Str, HasVAListArg, TheCall, format_idx,
2443                         inFunctionCall);
2444
2445    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2446      H.DoneProcessing();
2447  }
2448  else {
2449    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2450                        numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2451                        Str, HasVAListArg, TheCall, format_idx,
2452                        inFunctionCall);
2453
2454    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2455      H.DoneProcessing();
2456  }
2457}
2458
2459//===--- CHECK: Standard memory functions ---------------------------------===//
2460
2461/// \brief Determine whether the given type is a dynamic class type (e.g.,
2462/// whether it has a vtable).
2463static bool isDynamicClassType(QualType T) {
2464  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2465    if (CXXRecordDecl *Definition = Record->getDefinition())
2466      if (Definition->isDynamicClass())
2467        return true;
2468
2469  return false;
2470}
2471
2472/// \brief If E is a sizeof expression, returns its argument expression,
2473/// otherwise returns NULL.
2474static const Expr *getSizeOfExprArg(const Expr* E) {
2475  if (const UnaryExprOrTypeTraitExpr *SizeOf =
2476      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2477    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2478      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2479
2480  return 0;
2481}
2482
2483/// \brief If E is a sizeof expression, returns its argument type.
2484static QualType getSizeOfArgType(const Expr* E) {
2485  if (const UnaryExprOrTypeTraitExpr *SizeOf =
2486      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2487    if (SizeOf->getKind() == clang::UETT_SizeOf)
2488      return SizeOf->getTypeOfArgument();
2489
2490  return QualType();
2491}
2492
2493/// \brief Check for dangerous or invalid arguments to memset().
2494///
2495/// This issues warnings on known problematic, dangerous or unspecified
2496/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2497/// function calls.
2498///
2499/// \param Call The call expression to diagnose.
2500void Sema::CheckMemaccessArguments(const CallExpr *Call,
2501                                   CheckedMemoryFunction CMF,
2502                                   IdentifierInfo *FnName) {
2503  // It is possible to have a non-standard definition of memset.  Validate
2504  // we have enough arguments, and if not, abort further checking.
2505  unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2506  if (Call->getNumArgs() < ExpectedNumArgs)
2507    return;
2508
2509  unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2510  unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2511  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2512
2513  // We have special checking when the length is a sizeof expression.
2514  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2515  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2516  llvm::FoldingSetNodeID SizeOfArgID;
2517
2518  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2519    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2520    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2521
2522    QualType DestTy = Dest->getType();
2523    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2524      QualType PointeeTy = DestPtrTy->getPointeeType();
2525
2526      // Never warn about void type pointers. This can be used to suppress
2527      // false positives.
2528      if (PointeeTy->isVoidType())
2529        continue;
2530
2531      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2532      // actually comparing the expressions for equality. Because computing the
2533      // expression IDs can be expensive, we only do this if the diagnostic is
2534      // enabled.
2535      if (SizeOfArg &&
2536          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2537                                   SizeOfArg->getExprLoc())) {
2538        // We only compute IDs for expressions if the warning is enabled, and
2539        // cache the sizeof arg's ID.
2540        if (SizeOfArgID == llvm::FoldingSetNodeID())
2541          SizeOfArg->Profile(SizeOfArgID, Context, true);
2542        llvm::FoldingSetNodeID DestID;
2543        Dest->Profile(DestID, Context, true);
2544        if (DestID == SizeOfArgID) {
2545          // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2546          //       over sizeof(src) as well.
2547          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2548          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2549            if (UnaryOp->getOpcode() == UO_AddrOf)
2550              ActionIdx = 1; // If its an address-of operator, just remove it.
2551          if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2552            ActionIdx = 2; // If the pointee's size is sizeof(char),
2553                           // suggest an explicit length.
2554          unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
2555          DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2556                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2557                                << FnName << DestSrcSelect << ActionIdx
2558                                << Dest->getSourceRange()
2559                                << SizeOfArg->getSourceRange());
2560          break;
2561        }
2562      }
2563
2564      // Also check for cases where the sizeof argument is the exact same
2565      // type as the memory argument, and where it points to a user-defined
2566      // record type.
2567      if (SizeOfArgTy != QualType()) {
2568        if (PointeeTy->isRecordType() &&
2569            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2570          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2571                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
2572                                << FnName << SizeOfArgTy << ArgIdx
2573                                << PointeeTy << Dest->getSourceRange()
2574                                << LenExpr->getSourceRange());
2575          break;
2576        }
2577      }
2578
2579      // Always complain about dynamic classes.
2580      if (isDynamicClassType(PointeeTy))
2581        DiagRuntimeBehavior(
2582          Dest->getExprLoc(), Dest,
2583          PDiag(diag::warn_dyn_class_memaccess)
2584            << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2585            // "overwritten" if we're warning about the destination for any call
2586            // but memcmp; otherwise a verb appropriate to the call.
2587            << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2588            << Call->getCallee()->getSourceRange());
2589      else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2590        DiagRuntimeBehavior(
2591          Dest->getExprLoc(), Dest,
2592          PDiag(diag::warn_arc_object_memaccess)
2593            << ArgIdx << FnName << PointeeTy
2594            << Call->getCallee()->getSourceRange());
2595      else
2596        continue;
2597
2598      DiagRuntimeBehavior(
2599        Dest->getExprLoc(), Dest,
2600        PDiag(diag::note_bad_memaccess_silence)
2601          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2602      break;
2603    }
2604  }
2605}
2606
2607// A little helper routine: ignore addition and subtraction of integer literals.
2608// This intentionally does not ignore all integer constant expressions because
2609// we don't want to remove sizeof().
2610static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2611  Ex = Ex->IgnoreParenCasts();
2612
2613  for (;;) {
2614    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2615    if (!BO || !BO->isAdditiveOp())
2616      break;
2617
2618    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2619    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2620
2621    if (isa<IntegerLiteral>(RHS))
2622      Ex = LHS;
2623    else if (isa<IntegerLiteral>(LHS))
2624      Ex = RHS;
2625    else
2626      break;
2627  }
2628
2629  return Ex;
2630}
2631
2632// Warn if the user has made the 'size' argument to strlcpy or strlcat
2633// be the size of the source, instead of the destination.
2634void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2635                                    IdentifierInfo *FnName) {
2636
2637  // Don't crash if the user has the wrong number of arguments
2638  if (Call->getNumArgs() != 3)
2639    return;
2640
2641  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2642  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2643  const Expr *CompareWithSrc = NULL;
2644
2645  // Look for 'strlcpy(dst, x, sizeof(x))'
2646  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2647    CompareWithSrc = Ex;
2648  else {
2649    // Look for 'strlcpy(dst, x, strlen(x))'
2650    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2651      if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
2652          && SizeCall->getNumArgs() == 1)
2653        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2654    }
2655  }
2656
2657  if (!CompareWithSrc)
2658    return;
2659
2660  // Determine if the argument to sizeof/strlen is equal to the source
2661  // argument.  In principle there's all kinds of things you could do
2662  // here, for instance creating an == expression and evaluating it with
2663  // EvaluateAsBooleanCondition, but this uses a more direct technique:
2664  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2665  if (!SrcArgDRE)
2666    return;
2667
2668  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2669  if (!CompareWithSrcDRE ||
2670      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2671    return;
2672
2673  const Expr *OriginalSizeArg = Call->getArg(2);
2674  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2675    << OriginalSizeArg->getSourceRange() << FnName;
2676
2677  // Output a FIXIT hint if the destination is an array (rather than a
2678  // pointer to an array).  This could be enhanced to handle some
2679  // pointers if we know the actual size, like if DstArg is 'array+2'
2680  // we could say 'sizeof(array)-2'.
2681  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2682  QualType DstArgTy = DstArg->getType();
2683
2684  // Only handle constant-sized or VLAs, but not flexible members.
2685  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2686    // Only issue the FIXIT for arrays of size > 1.
2687    if (CAT->getSize().getSExtValue() <= 1)
2688      return;
2689  } else if (!DstArgTy->isVariableArrayType()) {
2690    return;
2691  }
2692
2693  llvm::SmallString<128> sizeString;
2694  llvm::raw_svector_ostream OS(sizeString);
2695  OS << "sizeof(";
2696  DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2697  OS << ")";
2698
2699  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2700    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2701                                    OS.str());
2702}
2703
2704//===--- CHECK: Return Address of Stack Variable --------------------------===//
2705
2706static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2707static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2708
2709/// CheckReturnStackAddr - Check if a return statement returns the address
2710///   of a stack variable.
2711void
2712Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2713                           SourceLocation ReturnLoc) {
2714
2715  Expr *stackE = 0;
2716  SmallVector<DeclRefExpr *, 8> refVars;
2717
2718  // Perform checking for returned stack addresses, local blocks,
2719  // label addresses or references to temporaries.
2720  if (lhsType->isPointerType() ||
2721      (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2722    stackE = EvalAddr(RetValExp, refVars);
2723  } else if (lhsType->isReferenceType()) {
2724    stackE = EvalVal(RetValExp, refVars);
2725  }
2726
2727  if (stackE == 0)
2728    return; // Nothing suspicious was found.
2729
2730  SourceLocation diagLoc;
2731  SourceRange diagRange;
2732  if (refVars.empty()) {
2733    diagLoc = stackE->getLocStart();
2734    diagRange = stackE->getSourceRange();
2735  } else {
2736    // We followed through a reference variable. 'stackE' contains the
2737    // problematic expression but we will warn at the return statement pointing
2738    // at the reference variable. We will later display the "trail" of
2739    // reference variables using notes.
2740    diagLoc = refVars[0]->getLocStart();
2741    diagRange = refVars[0]->getSourceRange();
2742  }
2743
2744  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2745    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2746                                             : diag::warn_ret_stack_addr)
2747     << DR->getDecl()->getDeclName() << diagRange;
2748  } else if (isa<BlockExpr>(stackE)) { // local block.
2749    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2750  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2751    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2752  } else { // local temporary.
2753    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2754                                             : diag::warn_ret_local_temp_addr)
2755     << diagRange;
2756  }
2757
2758  // Display the "trail" of reference variables that we followed until we
2759  // found the problematic expression using notes.
2760  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2761    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2762    // If this var binds to another reference var, show the range of the next
2763    // var, otherwise the var binds to the problematic expression, in which case
2764    // show the range of the expression.
2765    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2766                                  : stackE->getSourceRange();
2767    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2768      << VD->getDeclName() << range;
2769  }
2770}
2771
2772/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2773///  check if the expression in a return statement evaluates to an address
2774///  to a location on the stack, a local block, an address of a label, or a
2775///  reference to local temporary. The recursion is used to traverse the
2776///  AST of the return expression, with recursion backtracking when we
2777///  encounter a subexpression that (1) clearly does not lead to one of the
2778///  above problematic expressions (2) is something we cannot determine leads to
2779///  a problematic expression based on such local checking.
2780///
2781///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2782///  the expression that they point to. Such variables are added to the
2783///  'refVars' vector so that we know what the reference variable "trail" was.
2784///
2785///  EvalAddr processes expressions that are pointers that are used as
2786///  references (and not L-values).  EvalVal handles all other values.
2787///  At the base case of the recursion is a check for the above problematic
2788///  expressions.
2789///
2790///  This implementation handles:
2791///
2792///   * pointer-to-pointer casts
2793///   * implicit conversions from array references to pointers
2794///   * taking the address of fields
2795///   * arbitrary interplay between "&" and "*" operators
2796///   * pointer arithmetic from an address of a stack variable
2797///   * taking the address of an array element where the array is on the stack
2798static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2799  if (E->isTypeDependent())
2800      return NULL;
2801
2802  // We should only be called for evaluating pointer expressions.
2803  assert((E->getType()->isAnyPointerType() ||
2804          E->getType()->isBlockPointerType() ||
2805          E->getType()->isObjCQualifiedIdType()) &&
2806         "EvalAddr only works on pointers");
2807
2808  E = E->IgnoreParens();
2809
2810  // Our "symbolic interpreter" is just a dispatch off the currently
2811  // viewed AST node.  We then recursively traverse the AST by calling
2812  // EvalAddr and EvalVal appropriately.
2813  switch (E->getStmtClass()) {
2814  case Stmt::DeclRefExprClass: {
2815    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2816
2817    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2818      // If this is a reference variable, follow through to the expression that
2819      // it points to.
2820      if (V->hasLocalStorage() &&
2821          V->getType()->isReferenceType() && V->hasInit()) {
2822        // Add the reference variable to the "trail".
2823        refVars.push_back(DR);
2824        return EvalAddr(V->getInit(), refVars);
2825      }
2826
2827    return NULL;
2828  }
2829
2830  case Stmt::UnaryOperatorClass: {
2831    // The only unary operator that make sense to handle here
2832    // is AddrOf.  All others don't make sense as pointers.
2833    UnaryOperator *U = cast<UnaryOperator>(E);
2834
2835    if (U->getOpcode() == UO_AddrOf)
2836      return EvalVal(U->getSubExpr(), refVars);
2837    else
2838      return NULL;
2839  }
2840
2841  case Stmt::BinaryOperatorClass: {
2842    // Handle pointer arithmetic.  All other binary operators are not valid
2843    // in this context.
2844    BinaryOperator *B = cast<BinaryOperator>(E);
2845    BinaryOperatorKind op = B->getOpcode();
2846
2847    if (op != BO_Add && op != BO_Sub)
2848      return NULL;
2849
2850    Expr *Base = B->getLHS();
2851
2852    // Determine which argument is the real pointer base.  It could be
2853    // the RHS argument instead of the LHS.
2854    if (!Base->getType()->isPointerType()) Base = B->getRHS();
2855
2856    assert (Base->getType()->isPointerType());
2857    return EvalAddr(Base, refVars);
2858  }
2859
2860  // For conditional operators we need to see if either the LHS or RHS are
2861  // valid DeclRefExpr*s.  If one of them is valid, we return it.
2862  case Stmt::ConditionalOperatorClass: {
2863    ConditionalOperator *C = cast<ConditionalOperator>(E);
2864
2865    // Handle the GNU extension for missing LHS.
2866    if (Expr *lhsExpr = C->getLHS()) {
2867    // In C++, we can have a throw-expression, which has 'void' type.
2868      if (!lhsExpr->getType()->isVoidType())
2869        if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2870          return LHS;
2871    }
2872
2873    // In C++, we can have a throw-expression, which has 'void' type.
2874    if (C->getRHS()->getType()->isVoidType())
2875      return NULL;
2876
2877    return EvalAddr(C->getRHS(), refVars);
2878  }
2879
2880  case Stmt::BlockExprClass:
2881    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2882      return E; // local block.
2883    return NULL;
2884
2885  case Stmt::AddrLabelExprClass:
2886    return E; // address of label.
2887
2888  case Stmt::ExprWithCleanupsClass:
2889    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2890
2891  // For casts, we need to handle conversions from arrays to
2892  // pointer values, and pointer-to-pointer conversions.
2893  case Stmt::ImplicitCastExprClass:
2894  case Stmt::CStyleCastExprClass:
2895  case Stmt::CXXFunctionalCastExprClass:
2896  case Stmt::ObjCBridgedCastExprClass: {
2897    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2898    QualType T = SubExpr->getType();
2899
2900    if (SubExpr->getType()->isPointerType() ||
2901        SubExpr->getType()->isBlockPointerType() ||
2902        SubExpr->getType()->isObjCQualifiedIdType())
2903      return EvalAddr(SubExpr, refVars);
2904    else if (T->isArrayType())
2905      return EvalVal(SubExpr, refVars);
2906    else
2907      return 0;
2908  }
2909
2910  // C++ casts.  For dynamic casts, static casts, and const casts, we
2911  // are always converting from a pointer-to-pointer, so we just blow
2912  // through the cast.  In the case the dynamic cast doesn't fail (and
2913  // return NULL), we take the conservative route and report cases
2914  // where we return the address of a stack variable.  For Reinterpre
2915  // FIXME: The comment about is wrong; we're not always converting
2916  // from pointer to pointer. I'm guessing that this code should also
2917  // handle references to objects.
2918  case Stmt::CXXStaticCastExprClass:
2919  case Stmt::CXXDynamicCastExprClass:
2920  case Stmt::CXXConstCastExprClass:
2921  case Stmt::CXXReinterpretCastExprClass: {
2922      Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2923      if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2924        return EvalAddr(S, refVars);
2925      else
2926        return NULL;
2927  }
2928
2929  case Stmt::MaterializeTemporaryExprClass:
2930    if (Expr *Result = EvalAddr(
2931                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2932                                refVars))
2933      return Result;
2934
2935    return E;
2936
2937  // Everything else: we simply don't reason about them.
2938  default:
2939    return NULL;
2940  }
2941}
2942
2943
2944///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2945///   See the comments for EvalAddr for more details.
2946static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2947do {
2948  // We should only be called for evaluating non-pointer expressions, or
2949  // expressions with a pointer type that are not used as references but instead
2950  // are l-values (e.g., DeclRefExpr with a pointer type).
2951
2952  // Our "symbolic interpreter" is just a dispatch off the currently
2953  // viewed AST node.  We then recursively traverse the AST by calling
2954  // EvalAddr and EvalVal appropriately.
2955
2956  E = E->IgnoreParens();
2957  switch (E->getStmtClass()) {
2958  case Stmt::ImplicitCastExprClass: {
2959    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2960    if (IE->getValueKind() == VK_LValue) {
2961      E = IE->getSubExpr();
2962      continue;
2963    }
2964    return NULL;
2965  }
2966
2967  case Stmt::ExprWithCleanupsClass:
2968    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars);
2969
2970  case Stmt::DeclRefExprClass: {
2971    // When we hit a DeclRefExpr we are looking at code that refers to a
2972    // variable's name. If it's not a reference variable we check if it has
2973    // local storage within the function, and if so, return the expression.
2974    DeclRefExpr *DR = cast<DeclRefExpr>(E);
2975
2976    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2977      if (V->hasLocalStorage()) {
2978        if (!V->getType()->isReferenceType())
2979          return DR;
2980
2981        // Reference variable, follow through to the expression that
2982        // it points to.
2983        if (V->hasInit()) {
2984          // Add the reference variable to the "trail".
2985          refVars.push_back(DR);
2986          return EvalVal(V->getInit(), refVars);
2987        }
2988      }
2989
2990    return NULL;
2991  }
2992
2993  case Stmt::UnaryOperatorClass: {
2994    // The only unary operator that make sense to handle here
2995    // is Deref.  All others don't resolve to a "name."  This includes
2996    // handling all sorts of rvalues passed to a unary operator.
2997    UnaryOperator *U = cast<UnaryOperator>(E);
2998
2999    if (U->getOpcode() == UO_Deref)
3000      return EvalAddr(U->getSubExpr(), refVars);
3001
3002    return NULL;
3003  }
3004
3005  case Stmt::ArraySubscriptExprClass: {
3006    // Array subscripts are potential references to data on the stack.  We
3007    // retrieve the DeclRefExpr* for the array variable if it indeed
3008    // has local storage.
3009    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
3010  }
3011
3012  case Stmt::ConditionalOperatorClass: {
3013    // For conditional operators we need to see if either the LHS or RHS are
3014    // non-NULL Expr's.  If one is non-NULL, we return it.
3015    ConditionalOperator *C = cast<ConditionalOperator>(E);
3016
3017    // Handle the GNU extension for missing LHS.
3018    if (Expr *lhsExpr = C->getLHS())
3019      if (Expr *LHS = EvalVal(lhsExpr, refVars))
3020        return LHS;
3021
3022    return EvalVal(C->getRHS(), refVars);
3023  }
3024
3025  // Accesses to members are potential references to data on the stack.
3026  case Stmt::MemberExprClass: {
3027    MemberExpr *M = cast<MemberExpr>(E);
3028
3029    // Check for indirect access.  We only want direct field accesses.
3030    if (M->isArrow())
3031      return NULL;
3032
3033    // Check whether the member type is itself a reference, in which case
3034    // we're not going to refer to the member, but to what the member refers to.
3035    if (M->getMemberDecl()->getType()->isReferenceType())
3036      return NULL;
3037
3038    return EvalVal(M->getBase(), refVars);
3039  }
3040
3041  case Stmt::MaterializeTemporaryExprClass:
3042    if (Expr *Result = EvalVal(
3043                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
3044                               refVars))
3045      return Result;
3046
3047    return E;
3048
3049  default:
3050    // Check that we don't return or take the address of a reference to a
3051    // temporary. This is only useful in C++.
3052    if (!E->isTypeDependent() && E->isRValue())
3053      return E;
3054
3055    // Everything else: we simply don't reason about them.
3056    return NULL;
3057  }
3058} while (true);
3059}
3060
3061//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
3062
3063/// Check for comparisons of floating point operands using != and ==.
3064/// Issue a warning if these are no self-comparisons, as they are not likely
3065/// to do what the programmer intended.
3066void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
3067  bool EmitWarning = true;
3068
3069  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
3070  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
3071
3072  // Special case: check for x == x (which is OK).
3073  // Do not emit warnings for such cases.
3074  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
3075    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
3076      if (DRL->getDecl() == DRR->getDecl())
3077        EmitWarning = false;
3078
3079
3080  // Special case: check for comparisons against literals that can be exactly
3081  //  represented by APFloat.  In such cases, do not emit a warning.  This
3082  //  is a heuristic: often comparison against such literals are used to
3083  //  detect if a value in a variable has not changed.  This clearly can
3084  //  lead to false negatives.
3085  if (EmitWarning) {
3086    if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
3087      if (FLL->isExact())
3088        EmitWarning = false;
3089    } else
3090      if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
3091        if (FLR->isExact())
3092          EmitWarning = false;
3093    }
3094  }
3095
3096  // Check for comparisons with builtin types.
3097  if (EmitWarning)
3098    if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
3099      if (CL->isBuiltinCall())
3100        EmitWarning = false;
3101
3102  if (EmitWarning)
3103    if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
3104      if (CR->isBuiltinCall())
3105        EmitWarning = false;
3106
3107  // Emit the diagnostic.
3108  if (EmitWarning)
3109    Diag(Loc, diag::warn_floatingpoint_eq)
3110      << LHS->getSourceRange() << RHS->getSourceRange();
3111}
3112
3113//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
3114//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
3115
3116namespace {
3117
3118/// Structure recording the 'active' range of an integer-valued
3119/// expression.
3120struct IntRange {
3121  /// The number of bits active in the int.
3122  unsigned Width;
3123
3124  /// True if the int is known not to have negative values.
3125  bool NonNegative;
3126
3127  IntRange(unsigned Width, bool NonNegative)
3128    : Width(Width), NonNegative(NonNegative)
3129  {}
3130
3131  /// Returns the range of the bool type.
3132  static IntRange forBoolType() {
3133    return IntRange(1, true);
3134  }
3135
3136  /// Returns the range of an opaque value of the given integral type.
3137  static IntRange forValueOfType(ASTContext &C, QualType T) {
3138    return forValueOfCanonicalType(C,
3139                          T->getCanonicalTypeInternal().getTypePtr());
3140  }
3141
3142  /// Returns the range of an opaque value of a canonical integral type.
3143  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
3144    assert(T->isCanonicalUnqualified());
3145
3146    if (const VectorType *VT = dyn_cast<VectorType>(T))
3147      T = VT->getElementType().getTypePtr();
3148    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3149      T = CT->getElementType().getTypePtr();
3150
3151    // For enum types, use the known bit width of the enumerators.
3152    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
3153      EnumDecl *Enum = ET->getDecl();
3154      if (!Enum->isCompleteDefinition())
3155        return IntRange(C.getIntWidth(QualType(T, 0)), false);
3156
3157      unsigned NumPositive = Enum->getNumPositiveBits();
3158      unsigned NumNegative = Enum->getNumNegativeBits();
3159
3160      return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
3161    }
3162
3163    const BuiltinType *BT = cast<BuiltinType>(T);
3164    assert(BT->isInteger());
3165
3166    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3167  }
3168
3169  /// Returns the "target" range of a canonical integral type, i.e.
3170  /// the range of values expressible in the type.
3171  ///
3172  /// This matches forValueOfCanonicalType except that enums have the
3173  /// full range of their type, not the range of their enumerators.
3174  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
3175    assert(T->isCanonicalUnqualified());
3176
3177    if (const VectorType *VT = dyn_cast<VectorType>(T))
3178      T = VT->getElementType().getTypePtr();
3179    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
3180      T = CT->getElementType().getTypePtr();
3181    if (const EnumType *ET = dyn_cast<EnumType>(T))
3182      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
3183
3184    const BuiltinType *BT = cast<BuiltinType>(T);
3185    assert(BT->isInteger());
3186
3187    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
3188  }
3189
3190  /// Returns the supremum of two ranges: i.e. their conservative merge.
3191  static IntRange join(IntRange L, IntRange R) {
3192    return IntRange(std::max(L.Width, R.Width),
3193                    L.NonNegative && R.NonNegative);
3194  }
3195
3196  /// Returns the infinum of two ranges: i.e. their aggressive merge.
3197  static IntRange meet(IntRange L, IntRange R) {
3198    return IntRange(std::min(L.Width, R.Width),
3199                    L.NonNegative || R.NonNegative);
3200  }
3201};
3202
3203IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
3204  if (value.isSigned() && value.isNegative())
3205    return IntRange(value.getMinSignedBits(), false);
3206
3207  if (value.getBitWidth() > MaxWidth)
3208    value = value.trunc(MaxWidth);
3209
3210  // isNonNegative() just checks the sign bit without considering
3211  // signedness.
3212  return IntRange(value.getActiveBits(), true);
3213}
3214
3215IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
3216                       unsigned MaxWidth) {
3217  if (result.isInt())
3218    return GetValueRange(C, result.getInt(), MaxWidth);
3219
3220  if (result.isVector()) {
3221    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3222    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3223      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3224      R = IntRange::join(R, El);
3225    }
3226    return R;
3227  }
3228
3229  if (result.isComplexInt()) {
3230    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3231    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3232    return IntRange::join(R, I);
3233  }
3234
3235  // This can happen with lossless casts to intptr_t of "based" lvalues.
3236  // Assume it might use arbitrary bits.
3237  // FIXME: The only reason we need to pass the type in here is to get
3238  // the sign right on this one case.  It would be nice if APValue
3239  // preserved this.
3240  assert(result.isLValue());
3241  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
3242}
3243
3244/// Pseudo-evaluate the given integer expression, estimating the
3245/// range of values it might take.
3246///
3247/// \param MaxWidth - the width to which the value will be truncated
3248IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3249  E = E->IgnoreParens();
3250
3251  // Try a full evaluation first.
3252  Expr::EvalResult result;
3253  if (E->EvaluateAsRValue(result, C))
3254    return GetValueRange(C, result.Val, E->getType(), MaxWidth);
3255
3256  // I think we only want to look through implicit casts here; if the
3257  // user has an explicit widening cast, we should treat the value as
3258  // being of the new, wider type.
3259  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
3260    if (CE->getCastKind() == CK_NoOp)
3261      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3262
3263    IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
3264
3265    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
3266
3267    // Assume that non-integer casts can span the full range of the type.
3268    if (!isIntegerCast)
3269      return OutputTypeRange;
3270
3271    IntRange SubRange
3272      = GetExprRange(C, CE->getSubExpr(),
3273                     std::min(MaxWidth, OutputTypeRange.Width));
3274
3275    // Bail out if the subexpr's range is as wide as the cast type.
3276    if (SubRange.Width >= OutputTypeRange.Width)
3277      return OutputTypeRange;
3278
3279    // Otherwise, we take the smaller width, and we're non-negative if
3280    // either the output type or the subexpr is.
3281    return IntRange(SubRange.Width,
3282                    SubRange.NonNegative || OutputTypeRange.NonNegative);
3283  }
3284
3285  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3286    // If we can fold the condition, just take that operand.
3287    bool CondResult;
3288    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3289      return GetExprRange(C, CondResult ? CO->getTrueExpr()
3290                                        : CO->getFalseExpr(),
3291                          MaxWidth);
3292
3293    // Otherwise, conservatively merge.
3294    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3295    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3296    return IntRange::join(L, R);
3297  }
3298
3299  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3300    switch (BO->getOpcode()) {
3301
3302    // Boolean-valued operations are single-bit and positive.
3303    case BO_LAnd:
3304    case BO_LOr:
3305    case BO_LT:
3306    case BO_GT:
3307    case BO_LE:
3308    case BO_GE:
3309    case BO_EQ:
3310    case BO_NE:
3311      return IntRange::forBoolType();
3312
3313    // The type of the assignments is the type of the LHS, so the RHS
3314    // is not necessarily the same type.
3315    case BO_MulAssign:
3316    case BO_DivAssign:
3317    case BO_RemAssign:
3318    case BO_AddAssign:
3319    case BO_SubAssign:
3320    case BO_XorAssign:
3321    case BO_OrAssign:
3322      // TODO: bitfields?
3323      return IntRange::forValueOfType(C, E->getType());
3324
3325    // Simple assignments just pass through the RHS, which will have
3326    // been coerced to the LHS type.
3327    case BO_Assign:
3328      // TODO: bitfields?
3329      return GetExprRange(C, BO->getRHS(), MaxWidth);
3330
3331    // Operations with opaque sources are black-listed.
3332    case BO_PtrMemD:
3333    case BO_PtrMemI:
3334      return IntRange::forValueOfType(C, E->getType());
3335
3336    // Bitwise-and uses the *infinum* of the two source ranges.
3337    case BO_And:
3338    case BO_AndAssign:
3339      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3340                            GetExprRange(C, BO->getRHS(), MaxWidth));
3341
3342    // Left shift gets black-listed based on a judgement call.
3343    case BO_Shl:
3344      // ...except that we want to treat '1 << (blah)' as logically
3345      // positive.  It's an important idiom.
3346      if (IntegerLiteral *I
3347            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3348        if (I->getValue() == 1) {
3349          IntRange R = IntRange::forValueOfType(C, E->getType());
3350          return IntRange(R.Width, /*NonNegative*/ true);
3351        }
3352      }
3353      // fallthrough
3354
3355    case BO_ShlAssign:
3356      return IntRange::forValueOfType(C, E->getType());
3357
3358    // Right shift by a constant can narrow its left argument.
3359    case BO_Shr:
3360    case BO_ShrAssign: {
3361      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3362
3363      // If the shift amount is a positive constant, drop the width by
3364      // that much.
3365      llvm::APSInt shift;
3366      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3367          shift.isNonNegative()) {
3368        unsigned zext = shift.getZExtValue();
3369        if (zext >= L.Width)
3370          L.Width = (L.NonNegative ? 0 : 1);
3371        else
3372          L.Width -= zext;
3373      }
3374
3375      return L;
3376    }
3377
3378    // Comma acts as its right operand.
3379    case BO_Comma:
3380      return GetExprRange(C, BO->getRHS(), MaxWidth);
3381
3382    // Black-list pointer subtractions.
3383    case BO_Sub:
3384      if (BO->getLHS()->getType()->isPointerType())
3385        return IntRange::forValueOfType(C, E->getType());
3386      break;
3387
3388    // The width of a division result is mostly determined by the size
3389    // of the LHS.
3390    case BO_Div: {
3391      // Don't 'pre-truncate' the operands.
3392      unsigned opWidth = C.getIntWidth(E->getType());
3393      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3394
3395      // If the divisor is constant, use that.
3396      llvm::APSInt divisor;
3397      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3398        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3399        if (log2 >= L.Width)
3400          L.Width = (L.NonNegative ? 0 : 1);
3401        else
3402          L.Width = std::min(L.Width - log2, MaxWidth);
3403        return L;
3404      }
3405
3406      // Otherwise, just use the LHS's width.
3407      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3408      return IntRange(L.Width, L.NonNegative && R.NonNegative);
3409    }
3410
3411    // The result of a remainder can't be larger than the result of
3412    // either side.
3413    case BO_Rem: {
3414      // Don't 'pre-truncate' the operands.
3415      unsigned opWidth = C.getIntWidth(E->getType());
3416      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3417      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3418
3419      IntRange meet = IntRange::meet(L, R);
3420      meet.Width = std::min(meet.Width, MaxWidth);
3421      return meet;
3422    }
3423
3424    // The default behavior is okay for these.
3425    case BO_Mul:
3426    case BO_Add:
3427    case BO_Xor:
3428    case BO_Or:
3429      break;
3430    }
3431
3432    // The default case is to treat the operation as if it were closed
3433    // on the narrowest type that encompasses both operands.
3434    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3435    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3436    return IntRange::join(L, R);
3437  }
3438
3439  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3440    switch (UO->getOpcode()) {
3441    // Boolean-valued operations are white-listed.
3442    case UO_LNot:
3443      return IntRange::forBoolType();
3444
3445    // Operations with opaque sources are black-listed.
3446    case UO_Deref:
3447    case UO_AddrOf: // should be impossible
3448      return IntRange::forValueOfType(C, E->getType());
3449
3450    default:
3451      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3452    }
3453  }
3454
3455  if (dyn_cast<OffsetOfExpr>(E)) {
3456    IntRange::forValueOfType(C, E->getType());
3457  }
3458
3459  if (FieldDecl *BitField = E->getBitField())
3460    return IntRange(BitField->getBitWidthValue(C),
3461                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
3462
3463  return IntRange::forValueOfType(C, E->getType());
3464}
3465
3466IntRange GetExprRange(ASTContext &C, Expr *E) {
3467  return GetExprRange(C, E, C.getIntWidth(E->getType()));
3468}
3469
3470/// Checks whether the given value, which currently has the given
3471/// source semantics, has the same value when coerced through the
3472/// target semantics.
3473bool IsSameFloatAfterCast(const llvm::APFloat &value,
3474                          const llvm::fltSemantics &Src,
3475                          const llvm::fltSemantics &Tgt) {
3476  llvm::APFloat truncated = value;
3477
3478  bool ignored;
3479  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3480  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3481
3482  return truncated.bitwiseIsEqual(value);
3483}
3484
3485/// Checks whether the given value, which currently has the given
3486/// source semantics, has the same value when coerced through the
3487/// target semantics.
3488///
3489/// The value might be a vector of floats (or a complex number).
3490bool IsSameFloatAfterCast(const APValue &value,
3491                          const llvm::fltSemantics &Src,
3492                          const llvm::fltSemantics &Tgt) {
3493  if (value.isFloat())
3494    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3495
3496  if (value.isVector()) {
3497    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3498      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3499        return false;
3500    return true;
3501  }
3502
3503  assert(value.isComplexFloat());
3504  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3505          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3506}
3507
3508void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3509
3510static bool IsZero(Sema &S, Expr *E) {
3511  // Suppress cases where we are comparing against an enum constant.
3512  if (const DeclRefExpr *DR =
3513      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3514    if (isa<EnumConstantDecl>(DR->getDecl()))
3515      return false;
3516
3517  // Suppress cases where the '0' value is expanded from a macro.
3518  if (E->getLocStart().isMacroID())
3519    return false;
3520
3521  llvm::APSInt Value;
3522  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3523}
3524
3525static bool HasEnumType(Expr *E) {
3526  // Strip off implicit integral promotions.
3527  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3528    if (ICE->getCastKind() != CK_IntegralCast &&
3529        ICE->getCastKind() != CK_NoOp)
3530      break;
3531    E = ICE->getSubExpr();
3532  }
3533
3534  return E->getType()->isEnumeralType();
3535}
3536
3537void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3538  BinaryOperatorKind op = E->getOpcode();
3539  if (E->isValueDependent())
3540    return;
3541
3542  if (op == BO_LT && IsZero(S, E->getRHS())) {
3543    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3544      << "< 0" << "false" << HasEnumType(E->getLHS())
3545      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3546  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3547    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3548      << ">= 0" << "true" << HasEnumType(E->getLHS())
3549      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3550  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3551    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3552      << "0 >" << "false" << HasEnumType(E->getRHS())
3553      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3554  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3555    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3556      << "0 <=" << "true" << HasEnumType(E->getRHS())
3557      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3558  }
3559}
3560
3561/// Analyze the operands of the given comparison.  Implements the
3562/// fallback case from AnalyzeComparison.
3563void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3564  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3565  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3566}
3567
3568/// \brief Implements -Wsign-compare.
3569///
3570/// \param E the binary operator to check for warnings
3571void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3572  // The type the comparison is being performed in.
3573  QualType T = E->getLHS()->getType();
3574  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3575         && "comparison with mismatched types");
3576
3577  // We don't do anything special if this isn't an unsigned integral
3578  // comparison:  we're only interested in integral comparisons, and
3579  // signed comparisons only happen in cases we don't care to warn about.
3580  //
3581  // We also don't care about value-dependent expressions or expressions
3582  // whose result is a constant.
3583  if (!T->hasUnsignedIntegerRepresentation()
3584      || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3585    return AnalyzeImpConvsInComparison(S, E);
3586
3587  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3588  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3589
3590  // Check to see if one of the (unmodified) operands is of different
3591  // signedness.
3592  Expr *signedOperand, *unsignedOperand;
3593  if (LHS->getType()->hasSignedIntegerRepresentation()) {
3594    assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3595           "unsigned comparison between two signed integer expressions?");
3596    signedOperand = LHS;
3597    unsignedOperand = RHS;
3598  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3599    signedOperand = RHS;
3600    unsignedOperand = LHS;
3601  } else {
3602    CheckTrivialUnsignedComparison(S, E);
3603    return AnalyzeImpConvsInComparison(S, E);
3604  }
3605
3606  // Otherwise, calculate the effective range of the signed operand.
3607  IntRange signedRange = GetExprRange(S.Context, signedOperand);
3608
3609  // Go ahead and analyze implicit conversions in the operands.  Note
3610  // that we skip the implicit conversions on both sides.
3611  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3612  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3613
3614  // If the signed range is non-negative, -Wsign-compare won't fire,
3615  // but we should still check for comparisons which are always true
3616  // or false.
3617  if (signedRange.NonNegative)
3618    return CheckTrivialUnsignedComparison(S, E);
3619
3620  // For (in)equality comparisons, if the unsigned operand is a
3621  // constant which cannot collide with a overflowed signed operand,
3622  // then reinterpreting the signed operand as unsigned will not
3623  // change the result of the comparison.
3624  if (E->isEqualityOp()) {
3625    unsigned comparisonWidth = S.Context.getIntWidth(T);
3626    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3627
3628    // We should never be unable to prove that the unsigned operand is
3629    // non-negative.
3630    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3631
3632    if (unsignedRange.Width < comparisonWidth)
3633      return;
3634  }
3635
3636  S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3637    << LHS->getType() << RHS->getType()
3638    << LHS->getSourceRange() << RHS->getSourceRange();
3639}
3640
3641/// Analyzes an attempt to assign the given value to a bitfield.
3642///
3643/// Returns true if there was something fishy about the attempt.
3644bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3645                               SourceLocation InitLoc) {
3646  assert(Bitfield->isBitField());
3647  if (Bitfield->isInvalidDecl())
3648    return false;
3649
3650  // White-list bool bitfields.
3651  if (Bitfield->getType()->isBooleanType())
3652    return false;
3653
3654  // Ignore value- or type-dependent expressions.
3655  if (Bitfield->getBitWidth()->isValueDependent() ||
3656      Bitfield->getBitWidth()->isTypeDependent() ||
3657      Init->isValueDependent() ||
3658      Init->isTypeDependent())
3659    return false;
3660
3661  Expr *OriginalInit = Init->IgnoreParenImpCasts();
3662
3663  Expr::EvalResult InitValue;
3664  if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
3665      !InitValue.Val.isInt())
3666    return false;
3667
3668  const llvm::APSInt &Value = InitValue.Val.getInt();
3669  unsigned OriginalWidth = Value.getBitWidth();
3670  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3671
3672  if (OriginalWidth <= FieldWidth)
3673    return false;
3674
3675  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3676
3677  // It's fairly common to write values into signed bitfields
3678  // that, if sign-extended, would end up becoming a different
3679  // value.  We don't want to warn about that.
3680  if (Value.isSigned() && Value.isNegative())
3681    TruncatedValue = TruncatedValue.sext(OriginalWidth);
3682  else
3683    TruncatedValue = TruncatedValue.zext(OriginalWidth);
3684
3685  if (Value == TruncatedValue)
3686    return false;
3687
3688  std::string PrettyValue = Value.toString(10);
3689  std::string PrettyTrunc = TruncatedValue.toString(10);
3690
3691  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3692    << PrettyValue << PrettyTrunc << OriginalInit->getType()
3693    << Init->getSourceRange();
3694
3695  return true;
3696}
3697
3698/// Analyze the given simple or compound assignment for warning-worthy
3699/// operations.
3700void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3701  // Just recurse on the LHS.
3702  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3703
3704  // We want to recurse on the RHS as normal unless we're assigning to
3705  // a bitfield.
3706  if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3707    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3708                                  E->getOperatorLoc())) {
3709      // Recurse, ignoring any implicit conversions on the RHS.
3710      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3711                                        E->getOperatorLoc());
3712    }
3713  }
3714
3715  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3716}
3717
3718/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3719void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3720                     SourceLocation CContext, unsigned diag) {
3721  S.Diag(E->getExprLoc(), diag)
3722    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3723}
3724
3725/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3726void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3727                     unsigned diag) {
3728  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3729}
3730
3731/// Diagnose an implicit cast from a literal expression. Does not warn when the
3732/// cast wouldn't lose information.
3733void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3734                                    SourceLocation CContext) {
3735  // Try to convert the literal exactly to an integer. If we can, don't warn.
3736  bool isExact = false;
3737  const llvm::APFloat &Value = FL->getValue();
3738  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3739                            T->hasUnsignedIntegerRepresentation());
3740  if (Value.convertToInteger(IntegerValue,
3741                             llvm::APFloat::rmTowardZero, &isExact)
3742      == llvm::APFloat::opOK && isExact)
3743    return;
3744
3745  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3746    << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3747}
3748
3749std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3750  if (!Range.Width) return "0";
3751
3752  llvm::APSInt ValueInRange = Value;
3753  ValueInRange.setIsSigned(!Range.NonNegative);
3754  ValueInRange = ValueInRange.trunc(Range.Width);
3755  return ValueInRange.toString(10);
3756}
3757
3758static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3759  SourceManager &smgr = S.Context.getSourceManager();
3760  return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3761}
3762
3763void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3764                             SourceLocation CC, bool *ICContext = 0) {
3765  if (E->isTypeDependent() || E->isValueDependent()) return;
3766
3767  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3768  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3769  if (Source == Target) return;
3770  if (Target->isDependentType()) return;
3771
3772  // If the conversion context location is invalid don't complain. We also
3773  // don't want to emit a warning if the issue occurs from the expansion of
3774  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3775  // delay this check as long as possible. Once we detect we are in that
3776  // scenario, we just return.
3777  if (CC.isInvalid())
3778    return;
3779
3780  // Diagnose implicit casts to bool.
3781  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3782    if (isa<StringLiteral>(E))
3783      // Warn on string literal to bool.  Checks for string literals in logical
3784      // expressions, for instances, assert(0 && "error here"), is prevented
3785      // by a check in AnalyzeImplicitConversions().
3786      return DiagnoseImpCast(S, E, T, CC,
3787                             diag::warn_impcast_string_literal_to_bool);
3788    if (Source->isFunctionType()) {
3789      // Warn on function to bool. Checks free functions and static member
3790      // functions. Weakly imported functions are excluded from the check,
3791      // since it's common to test their value to check whether the linker
3792      // found a definition for them.
3793      ValueDecl *D = 0;
3794      if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
3795        D = R->getDecl();
3796      } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
3797        D = M->getMemberDecl();
3798      }
3799
3800      if (D && !D->isWeak()) {
3801        if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
3802          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
3803            << F << E->getSourceRange() << SourceRange(CC);
3804          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
3805            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
3806          QualType ReturnType;
3807          UnresolvedSet<4> NonTemplateOverloads;
3808          S.isExprCallable(*E, ReturnType, NonTemplateOverloads);
3809          if (!ReturnType.isNull()
3810              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
3811            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
3812              << FixItHint::CreateInsertion(
3813                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
3814          return;
3815        }
3816      }
3817    }
3818    return; // Other casts to bool are not checked.
3819  }
3820
3821  // Strip vector types.
3822  if (isa<VectorType>(Source)) {
3823    if (!isa<VectorType>(Target)) {
3824      if (isFromSystemMacro(S, CC))
3825        return;
3826      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3827    }
3828
3829    // If the vector cast is cast between two vectors of the same size, it is
3830    // a bitcast, not a conversion.
3831    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3832      return;
3833
3834    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3835    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3836  }
3837
3838  // Strip complex types.
3839  if (isa<ComplexType>(Source)) {
3840    if (!isa<ComplexType>(Target)) {
3841      if (isFromSystemMacro(S, CC))
3842        return;
3843
3844      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3845    }
3846
3847    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3848    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3849  }
3850
3851  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3852  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3853
3854  // If the source is floating point...
3855  if (SourceBT && SourceBT->isFloatingPoint()) {
3856    // ...and the target is floating point...
3857    if (TargetBT && TargetBT->isFloatingPoint()) {
3858      // ...then warn if we're dropping FP rank.
3859
3860      // Builtin FP kinds are ordered by increasing FP rank.
3861      if (SourceBT->getKind() > TargetBT->getKind()) {
3862        // Don't warn about float constants that are precisely
3863        // representable in the target type.
3864        Expr::EvalResult result;
3865        if (E->EvaluateAsRValue(result, S.Context)) {
3866          // Value might be a float, a float vector, or a float complex.
3867          if (IsSameFloatAfterCast(result.Val,
3868                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3869                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3870            return;
3871        }
3872
3873        if (isFromSystemMacro(S, CC))
3874          return;
3875
3876        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3877      }
3878      return;
3879    }
3880
3881    // If the target is integral, always warn.
3882    if ((TargetBT && TargetBT->isInteger())) {
3883      if (isFromSystemMacro(S, CC))
3884        return;
3885
3886      Expr *InnerE = E->IgnoreParenImpCasts();
3887      // We also want to warn on, e.g., "int i = -1.234"
3888      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3889        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3890          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3891
3892      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3893        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3894      } else {
3895        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3896      }
3897    }
3898
3899    return;
3900  }
3901
3902  if (!Source->isIntegerType() || !Target->isIntegerType())
3903    return;
3904
3905  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3906           == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3907    S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3908        << E->getSourceRange() << clang::SourceRange(CC);
3909    return;
3910  }
3911
3912  IntRange SourceRange = GetExprRange(S.Context, E);
3913  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3914
3915  if (SourceRange.Width > TargetRange.Width) {
3916    // If the source is a constant, use a default-on diagnostic.
3917    // TODO: this should happen for bitfield stores, too.
3918    llvm::APSInt Value(32);
3919    if (E->isIntegerConstantExpr(Value, S.Context)) {
3920      if (isFromSystemMacro(S, CC))
3921        return;
3922
3923      std::string PrettySourceValue = Value.toString(10);
3924      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3925
3926      S.DiagRuntimeBehavior(E->getExprLoc(), E,
3927        S.PDiag(diag::warn_impcast_integer_precision_constant)
3928            << PrettySourceValue << PrettyTargetValue
3929            << E->getType() << T << E->getSourceRange()
3930            << clang::SourceRange(CC));
3931      return;
3932    }
3933
3934    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3935    if (isFromSystemMacro(S, CC))
3936      return;
3937
3938    if (SourceRange.Width == 64 && TargetRange.Width == 32)
3939      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3940    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3941  }
3942
3943  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3944      (!TargetRange.NonNegative && SourceRange.NonNegative &&
3945       SourceRange.Width == TargetRange.Width)) {
3946
3947    if (isFromSystemMacro(S, CC))
3948      return;
3949
3950    unsigned DiagID = diag::warn_impcast_integer_sign;
3951
3952    // Traditionally, gcc has warned about this under -Wsign-compare.
3953    // We also want to warn about it in -Wconversion.
3954    // So if -Wconversion is off, use a completely identical diagnostic
3955    // in the sign-compare group.
3956    // The conditional-checking code will
3957    if (ICContext) {
3958      DiagID = diag::warn_impcast_integer_sign_conditional;
3959      *ICContext = true;
3960    }
3961
3962    return DiagnoseImpCast(S, E, T, CC, DiagID);
3963  }
3964
3965  // Diagnose conversions between different enumeration types.
3966  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3967  // type, to give us better diagnostics.
3968  QualType SourceType = E->getType();
3969  if (!S.getLangOptions().CPlusPlus) {
3970    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3971      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3972        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3973        SourceType = S.Context.getTypeDeclType(Enum);
3974        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3975      }
3976  }
3977
3978  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3979    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3980      if ((SourceEnum->getDecl()->getIdentifier() ||
3981           SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3982          (TargetEnum->getDecl()->getIdentifier() ||
3983           TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3984          SourceEnum != TargetEnum) {
3985        if (isFromSystemMacro(S, CC))
3986          return;
3987
3988        return DiagnoseImpCast(S, E, SourceType, T, CC,
3989                               diag::warn_impcast_different_enum_types);
3990      }
3991
3992  return;
3993}
3994
3995void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3996
3997void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3998                             SourceLocation CC, bool &ICContext) {
3999  E = E->IgnoreParenImpCasts();
4000
4001  if (isa<ConditionalOperator>(E))
4002    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
4003
4004  AnalyzeImplicitConversions(S, E, CC);
4005  if (E->getType() != T)
4006    return CheckImplicitConversion(S, E, T, CC, &ICContext);
4007  return;
4008}
4009
4010void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
4011  SourceLocation CC = E->getQuestionLoc();
4012
4013  AnalyzeImplicitConversions(S, E->getCond(), CC);
4014
4015  bool Suspicious = false;
4016  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
4017  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
4018
4019  // If -Wconversion would have warned about either of the candidates
4020  // for a signedness conversion to the context type...
4021  if (!Suspicious) return;
4022
4023  // ...but it's currently ignored...
4024  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
4025                                 CC))
4026    return;
4027
4028  // ...then check whether it would have warned about either of the
4029  // candidates for a signedness conversion to the condition type.
4030  if (E->getType() == T) return;
4031
4032  Suspicious = false;
4033  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
4034                          E->getType(), CC, &Suspicious);
4035  if (!Suspicious)
4036    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
4037                            E->getType(), CC, &Suspicious);
4038}
4039
4040/// AnalyzeImplicitConversions - Find and report any interesting
4041/// implicit conversions in the given expression.  There are a couple
4042/// of competing diagnostics here, -Wconversion and -Wsign-compare.
4043void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
4044  QualType T = OrigE->getType();
4045  Expr *E = OrigE->IgnoreParenImpCasts();
4046
4047  if (E->isTypeDependent() || E->isValueDependent())
4048    return;
4049
4050  // For conditional operators, we analyze the arguments as if they
4051  // were being fed directly into the output.
4052  if (isa<ConditionalOperator>(E)) {
4053    ConditionalOperator *CO = cast<ConditionalOperator>(E);
4054    CheckConditionalOperator(S, CO, T);
4055    return;
4056  }
4057
4058  // Go ahead and check any implicit conversions we might have skipped.
4059  // The non-canonical typecheck is just an optimization;
4060  // CheckImplicitConversion will filter out dead implicit conversions.
4061  if (E->getType() != T)
4062    CheckImplicitConversion(S, E, T, CC);
4063
4064  // Now continue drilling into this expression.
4065
4066  // Skip past explicit casts.
4067  if (isa<ExplicitCastExpr>(E)) {
4068    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
4069    return AnalyzeImplicitConversions(S, E, CC);
4070  }
4071
4072  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4073    // Do a somewhat different check with comparison operators.
4074    if (BO->isComparisonOp())
4075      return AnalyzeComparison(S, BO);
4076
4077    // And with assignments and compound assignments.
4078    if (BO->isAssignmentOp())
4079      return AnalyzeAssignment(S, BO);
4080  }
4081
4082  // These break the otherwise-useful invariant below.  Fortunately,
4083  // we don't really need to recurse into them, because any internal
4084  // expressions should have been analyzed already when they were
4085  // built into statements.
4086  if (isa<StmtExpr>(E)) return;
4087
4088  // Don't descend into unevaluated contexts.
4089  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
4090
4091  // Now just recurse over the expression's children.
4092  CC = E->getExprLoc();
4093  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
4094  bool IsLogicalOperator = BO && BO->isLogicalOp();
4095  for (Stmt::child_range I = E->children(); I; ++I) {
4096    Expr *ChildExpr = cast<Expr>(*I);
4097    if (IsLogicalOperator &&
4098        isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
4099      // Ignore checking string literals that are in logical operators.
4100      continue;
4101    AnalyzeImplicitConversions(S, ChildExpr, CC);
4102  }
4103}
4104
4105} // end anonymous namespace
4106
4107/// Diagnoses "dangerous" implicit conversions within the given
4108/// expression (which is a full expression).  Implements -Wconversion
4109/// and -Wsign-compare.
4110///
4111/// \param CC the "context" location of the implicit conversion, i.e.
4112///   the most location of the syntactic entity requiring the implicit
4113///   conversion
4114void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
4115  // Don't diagnose in unevaluated contexts.
4116  if (ExprEvalContexts.back().Context == Sema::Unevaluated)
4117    return;
4118
4119  // Don't diagnose for value- or type-dependent expressions.
4120  if (E->isTypeDependent() || E->isValueDependent())
4121    return;
4122
4123  // Check for array bounds violations in cases where the check isn't triggered
4124  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
4125  // ArraySubscriptExpr is on the RHS of a variable initialization.
4126  CheckArrayAccess(E);
4127
4128  // This is not the right CC for (e.g.) a variable initialization.
4129  AnalyzeImplicitConversions(*this, E, CC);
4130}
4131
4132void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
4133                                       FieldDecl *BitField,
4134                                       Expr *Init) {
4135  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
4136}
4137
4138/// CheckParmsForFunctionDef - Check that the parameters of the given
4139/// function are appropriate for the definition of a function. This
4140/// takes care of any checks that cannot be performed on the
4141/// declaration itself, e.g., that the types of each of the function
4142/// parameters are complete.
4143bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
4144                                    bool CheckParameterNames) {
4145  bool HasInvalidParm = false;
4146  for (; P != PEnd; ++P) {
4147    ParmVarDecl *Param = *P;
4148
4149    // C99 6.7.5.3p4: the parameters in a parameter type list in a
4150    // function declarator that is part of a function definition of
4151    // that function shall not have incomplete type.
4152    //
4153    // This is also C++ [dcl.fct]p6.
4154    if (!Param->isInvalidDecl() &&
4155        RequireCompleteType(Param->getLocation(), Param->getType(),
4156                               diag::err_typecheck_decl_incomplete_type)) {
4157      Param->setInvalidDecl();
4158      HasInvalidParm = true;
4159    }
4160
4161    // C99 6.9.1p5: If the declarator includes a parameter type list, the
4162    // declaration of each parameter shall include an identifier.
4163    if (CheckParameterNames &&
4164        Param->getIdentifier() == 0 &&
4165        !Param->isImplicit() &&
4166        !getLangOptions().CPlusPlus)
4167      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
4168
4169    // C99 6.7.5.3p12:
4170    //   If the function declarator is not part of a definition of that
4171    //   function, parameters may have incomplete type and may use the [*]
4172    //   notation in their sequences of declarator specifiers to specify
4173    //   variable length array types.
4174    QualType PType = Param->getOriginalType();
4175    if (const ArrayType *AT = Context.getAsArrayType(PType)) {
4176      if (AT->getSizeModifier() == ArrayType::Star) {
4177        // FIXME: This diagnosic should point the the '[*]' if source-location
4178        // information is added for it.
4179        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
4180      }
4181    }
4182  }
4183
4184  return HasInvalidParm;
4185}
4186
4187/// CheckCastAlign - Implements -Wcast-align, which warns when a
4188/// pointer cast increases the alignment requirements.
4189void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
4190  // This is actually a lot of work to potentially be doing on every
4191  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
4192  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
4193                                          TRange.getBegin())
4194        == DiagnosticsEngine::Ignored)
4195    return;
4196
4197  // Ignore dependent types.
4198  if (T->isDependentType() || Op->getType()->isDependentType())
4199    return;
4200
4201  // Require that the destination be a pointer type.
4202  const PointerType *DestPtr = T->getAs<PointerType>();
4203  if (!DestPtr) return;
4204
4205  // If the destination has alignment 1, we're done.
4206  QualType DestPointee = DestPtr->getPointeeType();
4207  if (DestPointee->isIncompleteType()) return;
4208  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
4209  if (DestAlign.isOne()) return;
4210
4211  // Require that the source be a pointer type.
4212  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
4213  if (!SrcPtr) return;
4214  QualType SrcPointee = SrcPtr->getPointeeType();
4215
4216  // Whitelist casts from cv void*.  We already implicitly
4217  // whitelisted casts to cv void*, since they have alignment 1.
4218  // Also whitelist casts involving incomplete types, which implicitly
4219  // includes 'void'.
4220  if (SrcPointee->isIncompleteType()) return;
4221
4222  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
4223  if (SrcAlign >= DestAlign) return;
4224
4225  Diag(TRange.getBegin(), diag::warn_cast_align)
4226    << Op->getType() << T
4227    << static_cast<unsigned>(SrcAlign.getQuantity())
4228    << static_cast<unsigned>(DestAlign.getQuantity())
4229    << TRange << Op->getSourceRange();
4230}
4231
4232static const Type* getElementType(const Expr *BaseExpr) {
4233  const Type* EltType = BaseExpr->getType().getTypePtr();
4234  if (EltType->isAnyPointerType())
4235    return EltType->getPointeeType().getTypePtr();
4236  else if (EltType->isArrayType())
4237    return EltType->getBaseElementTypeUnsafe();
4238  return EltType;
4239}
4240
4241/// \brief Check whether this array fits the idiom of a size-one tail padded
4242/// array member of a struct.
4243///
4244/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4245/// commonly used to emulate flexible arrays in C89 code.
4246static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4247                                    const NamedDecl *ND) {
4248  if (Size != 1 || !ND) return false;
4249
4250  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4251  if (!FD) return false;
4252
4253  // Don't consider sizes resulting from macro expansions or template argument
4254  // substitution to form C89 tail-padded arrays.
4255  ConstantArrayTypeLoc TL =
4256    cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4257  const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4258  if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4259    return false;
4260
4261  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4262  if (!RD) return false;
4263  if (RD->isUnion()) return false;
4264  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
4265    if (!CRD->isStandardLayout()) return false;
4266  }
4267
4268  // See if this is the last field decl in the record.
4269  const Decl *D = FD;
4270  while ((D = D->getNextDeclInContext()))
4271    if (isa<FieldDecl>(D))
4272      return false;
4273  return true;
4274}
4275
4276void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4277                            bool isSubscript, bool AllowOnePastEnd) {
4278  const Type* EffectiveType = getElementType(BaseExpr);
4279  BaseExpr = BaseExpr->IgnoreParenCasts();
4280  IndexExpr = IndexExpr->IgnoreParenCasts();
4281
4282  const ConstantArrayType *ArrayTy =
4283    Context.getAsConstantArrayType(BaseExpr->getType());
4284  if (!ArrayTy)
4285    return;
4286
4287  if (IndexExpr->isValueDependent())
4288    return;
4289  llvm::APSInt index;
4290  if (!IndexExpr->isIntegerConstantExpr(index, Context))
4291    return;
4292
4293  const NamedDecl *ND = NULL;
4294  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4295    ND = dyn_cast<NamedDecl>(DRE->getDecl());
4296  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4297    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4298
4299  if (index.isUnsigned() || !index.isNegative()) {
4300    llvm::APInt size = ArrayTy->getSize();
4301    if (!size.isStrictlyPositive())
4302      return;
4303
4304    const Type* BaseType = getElementType(BaseExpr);
4305    if (BaseType != EffectiveType) {
4306      // Make sure we're comparing apples to apples when comparing index to size
4307      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4308      uint64_t array_typesize = Context.getTypeSize(BaseType);
4309      // Handle ptrarith_typesize being zero, such as when casting to void*
4310      if (!ptrarith_typesize) ptrarith_typesize = 1;
4311      if (ptrarith_typesize != array_typesize) {
4312        // There's a cast to a different size type involved
4313        uint64_t ratio = array_typesize / ptrarith_typesize;
4314        // TODO: Be smarter about handling cases where array_typesize is not a
4315        // multiple of ptrarith_typesize
4316        if (ptrarith_typesize * ratio == array_typesize)
4317          size *= llvm::APInt(size.getBitWidth(), ratio);
4318      }
4319    }
4320
4321    if (size.getBitWidth() > index.getBitWidth())
4322      index = index.sext(size.getBitWidth());
4323    else if (size.getBitWidth() < index.getBitWidth())
4324      size = size.sext(index.getBitWidth());
4325
4326    // For array subscripting the index must be less than size, but for pointer
4327    // arithmetic also allow the index (offset) to be equal to size since
4328    // computing the next address after the end of the array is legal and
4329    // commonly done e.g. in C++ iterators and range-based for loops.
4330    if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
4331      return;
4332
4333    // Also don't warn for arrays of size 1 which are members of some
4334    // structure. These are often used to approximate flexible arrays in C89
4335    // code.
4336    if (IsTailPaddedMemberArray(*this, size, ND))
4337      return;
4338
4339    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4340    if (isSubscript)
4341      DiagID = diag::warn_array_index_exceeds_bounds;
4342
4343    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4344                        PDiag(DiagID) << index.toString(10, true)
4345                          << size.toString(10, true)
4346                          << (unsigned)size.getLimitedValue(~0U)
4347                          << IndexExpr->getSourceRange());
4348  } else {
4349    unsigned DiagID = diag::warn_array_index_precedes_bounds;
4350    if (!isSubscript) {
4351      DiagID = diag::warn_ptr_arith_precedes_bounds;
4352      if (index.isNegative()) index = -index;
4353    }
4354
4355    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4356                        PDiag(DiagID) << index.toString(10, true)
4357                          << IndexExpr->getSourceRange());
4358  }
4359
4360  if (!ND) {
4361    // Try harder to find a NamedDecl to point at in the note.
4362    while (const ArraySubscriptExpr *ASE =
4363           dyn_cast<ArraySubscriptExpr>(BaseExpr))
4364      BaseExpr = ASE->getBase()->IgnoreParenCasts();
4365    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4366      ND = dyn_cast<NamedDecl>(DRE->getDecl());
4367    if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
4368      ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
4369  }
4370
4371  if (ND)
4372    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4373                        PDiag(diag::note_array_index_out_of_bounds)
4374                          << ND->getDeclName());
4375}
4376
4377void Sema::CheckArrayAccess(const Expr *expr) {
4378  int AllowOnePastEnd = 0;
4379  while (expr) {
4380    expr = expr->IgnoreParenImpCasts();
4381    switch (expr->getStmtClass()) {
4382      case Stmt::ArraySubscriptExprClass: {
4383        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4384        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4385                         AllowOnePastEnd > 0);
4386        return;
4387      }
4388      case Stmt::UnaryOperatorClass: {
4389        // Only unwrap the * and & unary operators
4390        const UnaryOperator *UO = cast<UnaryOperator>(expr);
4391        expr = UO->getSubExpr();
4392        switch (UO->getOpcode()) {
4393          case UO_AddrOf:
4394            AllowOnePastEnd++;
4395            break;
4396          case UO_Deref:
4397            AllowOnePastEnd--;
4398            break;
4399          default:
4400            return;
4401        }
4402        break;
4403      }
4404      case Stmt::ConditionalOperatorClass: {
4405        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4406        if (const Expr *lhs = cond->getLHS())
4407          CheckArrayAccess(lhs);
4408        if (const Expr *rhs = cond->getRHS())
4409          CheckArrayAccess(rhs);
4410        return;
4411      }
4412      default:
4413        return;
4414    }
4415  }
4416}
4417
4418//===--- CHECK: Objective-C retain cycles ----------------------------------//
4419
4420namespace {
4421  struct RetainCycleOwner {
4422    RetainCycleOwner() : Variable(0), Indirect(false) {}
4423    VarDecl *Variable;
4424    SourceRange Range;
4425    SourceLocation Loc;
4426    bool Indirect;
4427
4428    void setLocsFrom(Expr *e) {
4429      Loc = e->getExprLoc();
4430      Range = e->getSourceRange();
4431    }
4432  };
4433}
4434
4435/// Consider whether capturing the given variable can possibly lead to
4436/// a retain cycle.
4437static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4438  // In ARC, it's captured strongly iff the variable has __strong
4439  // lifetime.  In MRR, it's captured strongly if the variable is
4440  // __block and has an appropriate type.
4441  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4442    return false;
4443
4444  owner.Variable = var;
4445  owner.setLocsFrom(ref);
4446  return true;
4447}
4448
4449static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4450  while (true) {
4451    e = e->IgnoreParens();
4452    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4453      switch (cast->getCastKind()) {
4454      case CK_BitCast:
4455      case CK_LValueBitCast:
4456      case CK_LValueToRValue:
4457      case CK_ARCReclaimReturnedObject:
4458        e = cast->getSubExpr();
4459        continue;
4460
4461      default:
4462        return false;
4463      }
4464    }
4465
4466    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4467      ObjCIvarDecl *ivar = ref->getDecl();
4468      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4469        return false;
4470
4471      // Try to find a retain cycle in the base.
4472      if (!findRetainCycleOwner(ref->getBase(), owner))
4473        return false;
4474
4475      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4476      owner.Indirect = true;
4477      return true;
4478    }
4479
4480    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4481      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4482      if (!var) return false;
4483      return considerVariable(var, ref, owner);
4484    }
4485
4486    if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4487      owner.Variable = ref->getDecl();
4488      owner.setLocsFrom(ref);
4489      return true;
4490    }
4491
4492    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4493      if (member->isArrow()) return false;
4494
4495      // Don't count this as an indirect ownership.
4496      e = member->getBase();
4497      continue;
4498    }
4499
4500    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4501      // Only pay attention to pseudo-objects on property references.
4502      ObjCPropertyRefExpr *pre
4503        = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4504                                              ->IgnoreParens());
4505      if (!pre) return false;
4506      if (pre->isImplicitProperty()) return false;
4507      ObjCPropertyDecl *property = pre->getExplicitProperty();
4508      if (!property->isRetaining() &&
4509          !(property->getPropertyIvarDecl() &&
4510            property->getPropertyIvarDecl()->getType()
4511              .getObjCLifetime() == Qualifiers::OCL_Strong))
4512          return false;
4513
4514      owner.Indirect = true;
4515      e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4516                              ->getSourceExpr());
4517      continue;
4518    }
4519
4520    // Array ivars?
4521
4522    return false;
4523  }
4524}
4525
4526namespace {
4527  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4528    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4529      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4530        Variable(variable), Capturer(0) {}
4531
4532    VarDecl *Variable;
4533    Expr *Capturer;
4534
4535    void VisitDeclRefExpr(DeclRefExpr *ref) {
4536      if (ref->getDecl() == Variable && !Capturer)
4537        Capturer = ref;
4538    }
4539
4540    void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4541      if (ref->getDecl() == Variable && !Capturer)
4542        Capturer = ref;
4543    }
4544
4545    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4546      if (Capturer) return;
4547      Visit(ref->getBase());
4548      if (Capturer && ref->isFreeIvar())
4549        Capturer = ref;
4550    }
4551
4552    void VisitBlockExpr(BlockExpr *block) {
4553      // Look inside nested blocks
4554      if (block->getBlockDecl()->capturesVariable(Variable))
4555        Visit(block->getBlockDecl()->getBody());
4556    }
4557  };
4558}
4559
4560/// Check whether the given argument is a block which captures a
4561/// variable.
4562static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4563  assert(owner.Variable && owner.Loc.isValid());
4564
4565  e = e->IgnoreParenCasts();
4566  BlockExpr *block = dyn_cast<BlockExpr>(e);
4567  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4568    return 0;
4569
4570  FindCaptureVisitor visitor(S.Context, owner.Variable);
4571  visitor.Visit(block->getBlockDecl()->getBody());
4572  return visitor.Capturer;
4573}
4574
4575static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4576                                RetainCycleOwner &owner) {
4577  assert(capturer);
4578  assert(owner.Variable && owner.Loc.isValid());
4579
4580  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4581    << owner.Variable << capturer->getSourceRange();
4582  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4583    << owner.Indirect << owner.Range;
4584}
4585
4586/// Check for a keyword selector that starts with the word 'add' or
4587/// 'set'.
4588static bool isSetterLikeSelector(Selector sel) {
4589  if (sel.isUnarySelector()) return false;
4590
4591  StringRef str = sel.getNameForSlot(0);
4592  while (!str.empty() && str.front() == '_') str = str.substr(1);
4593  if (str.startswith("set"))
4594    str = str.substr(3);
4595  else if (str.startswith("add")) {
4596    // Specially whitelist 'addOperationWithBlock:'.
4597    if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
4598      return false;
4599    str = str.substr(3);
4600  }
4601  else
4602    return false;
4603
4604  if (str.empty()) return true;
4605  return !islower(str.front());
4606}
4607
4608/// Check a message send to see if it's likely to cause a retain cycle.
4609void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4610  // Only check instance methods whose selector looks like a setter.
4611  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4612    return;
4613
4614  // Try to find a variable that the receiver is strongly owned by.
4615  RetainCycleOwner owner;
4616  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4617    if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4618      return;
4619  } else {
4620    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4621    owner.Variable = getCurMethodDecl()->getSelfDecl();
4622    owner.Loc = msg->getSuperLoc();
4623    owner.Range = msg->getSuperLoc();
4624  }
4625
4626  // Check whether the receiver is captured by any of the arguments.
4627  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4628    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4629      return diagnoseRetainCycle(*this, capturer, owner);
4630}
4631
4632/// Check a property assign to see if it's likely to cause a retain cycle.
4633void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4634  RetainCycleOwner owner;
4635  if (!findRetainCycleOwner(receiver, owner))
4636    return;
4637
4638  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4639    diagnoseRetainCycle(*this, capturer, owner);
4640}
4641
4642bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4643                              QualType LHS, Expr *RHS) {
4644  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4645  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4646    return false;
4647  // strip off any implicit cast added to get to the one arc-specific
4648  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4649    if (cast->getCastKind() == CK_ARCConsumeObject) {
4650      Diag(Loc, diag::warn_arc_retained_assign)
4651        << (LT == Qualifiers::OCL_ExplicitNone)
4652        << RHS->getSourceRange();
4653      return true;
4654    }
4655    RHS = cast->getSubExpr();
4656  }
4657  return false;
4658}
4659
4660void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4661                              Expr *LHS, Expr *RHS) {
4662  QualType LHSType = LHS->getType();
4663  if (checkUnsafeAssigns(Loc, LHSType, RHS))
4664    return;
4665  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4666  // FIXME. Check for other life times.
4667  if (LT != Qualifiers::OCL_None)
4668    return;
4669
4670  if (ObjCPropertyRefExpr *PRE
4671        = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
4672    if (PRE->isImplicitProperty())
4673      return;
4674    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4675    if (!PD)
4676      return;
4677
4678    unsigned Attributes = PD->getPropertyAttributes();
4679    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4680      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4681        if (cast->getCastKind() == CK_ARCConsumeObject) {
4682          Diag(Loc, diag::warn_arc_retained_property_assign)
4683          << RHS->getSourceRange();
4684          return;
4685        }
4686        RHS = cast->getSubExpr();
4687      }
4688  }
4689}
4690