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