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