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