SemaChecking.cpp revision 624bb5e59dbcc24efeee7dff12c9b48d2b5077e9
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/SemaInternal.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/CharUnits.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/Analysis/Analyses/FormatString.h"
27#include "clang/Basic/CharInfo.h"
28#include "clang/Basic/TargetBuiltins.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "llvm/ADT/SmallBitVector.h"
36#include "llvm/ADT/SmallString.h"
37#include "llvm/ADT/STLExtras.h"
38#include "llvm/Support/ConvertUTF.h"
39#include "llvm/Support/raw_ostream.h"
40#include <limits>
41using namespace clang;
42using namespace sema;
43
44SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
45                                                    unsigned ByteNo) const {
46  return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
47                               PP.getLangOpts(), PP.getTargetInfo());
48}
49
50/// Checks that a call expression's argument count is the desired number.
51/// This is useful when doing custom type-checking.  Returns true on error.
52static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
53  unsigned argCount = call->getNumArgs();
54  if (argCount == desiredArgCount) return false;
55
56  if (argCount < desiredArgCount)
57    return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
58        << 0 /*function call*/ << desiredArgCount << argCount
59        << call->getSourceRange();
60
61  // Highlight all the excess arguments.
62  SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
63                    call->getArg(argCount - 1)->getLocEnd());
64
65  return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66    << 0 /*function call*/ << desiredArgCount << argCount
67    << call->getArg(1)->getSourceRange();
68}
69
70/// Check that the first argument to __builtin_annotation is an integer
71/// and the second argument is a non-wide string literal.
72static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
73  if (checkArgCount(S, TheCall, 2))
74    return true;
75
76  // First argument should be an integer.
77  Expr *ValArg = TheCall->getArg(0);
78  QualType Ty = ValArg->getType();
79  if (!Ty->isIntegerType()) {
80    S.Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81      << ValArg->getSourceRange();
82    return true;
83  }
84
85  // Second argument should be a constant string.
86  Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
87  StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
88  if (!Literal || !Literal->isAscii()) {
89    S.Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90      << StrArg->getSourceRange();
91    return true;
92  }
93
94  TheCall->setType(Ty);
95  return false;
96}
97
98/// Check that the argument to __builtin_addressof is a glvalue, and set the
99/// result type to the corresponding pointer type.
100static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
101  if (checkArgCount(S, TheCall, 1))
102    return true;
103
104  ExprResult Arg(S.Owned(TheCall->getArg(0)));
105  QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getLocStart());
106  if (ResultType.isNull())
107    return true;
108
109  TheCall->setArg(0, Arg.take());
110  TheCall->setType(ResultType);
111  return false;
112}
113
114ExprResult
115Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
116  ExprResult TheCallResult(Owned(TheCall));
117
118  // Find out if any arguments are required to be integer constant expressions.
119  unsigned ICEArguments = 0;
120  ASTContext::GetBuiltinTypeError Error;
121  Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
122  if (Error != ASTContext::GE_None)
123    ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
124
125  // If any arguments are required to be ICE's, check and diagnose.
126  for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
127    // Skip arguments not required to be ICE's.
128    if ((ICEArguments & (1 << ArgNo)) == 0) continue;
129
130    llvm::APSInt Result;
131    if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
132      return true;
133    ICEArguments &= ~(1 << ArgNo);
134  }
135
136  switch (BuiltinID) {
137  case Builtin::BI__builtin___CFStringMakeConstantString:
138    assert(TheCall->getNumArgs() == 1 &&
139           "Wrong # arguments to builtin CFStringMakeConstantString");
140    if (CheckObjCString(TheCall->getArg(0)))
141      return ExprError();
142    break;
143  case Builtin::BI__builtin_stdarg_start:
144  case Builtin::BI__builtin_va_start:
145    if (SemaBuiltinVAStart(TheCall))
146      return ExprError();
147    break;
148  case Builtin::BI__builtin_isgreater:
149  case Builtin::BI__builtin_isgreaterequal:
150  case Builtin::BI__builtin_isless:
151  case Builtin::BI__builtin_islessequal:
152  case Builtin::BI__builtin_islessgreater:
153  case Builtin::BI__builtin_isunordered:
154    if (SemaBuiltinUnorderedCompare(TheCall))
155      return ExprError();
156    break;
157  case Builtin::BI__builtin_fpclassify:
158    if (SemaBuiltinFPClassification(TheCall, 6))
159      return ExprError();
160    break;
161  case Builtin::BI__builtin_isfinite:
162  case Builtin::BI__builtin_isinf:
163  case Builtin::BI__builtin_isinf_sign:
164  case Builtin::BI__builtin_isnan:
165  case Builtin::BI__builtin_isnormal:
166    if (SemaBuiltinFPClassification(TheCall, 1))
167      return ExprError();
168    break;
169  case Builtin::BI__builtin_shufflevector:
170    return SemaBuiltinShuffleVector(TheCall);
171    // TheCall will be freed by the smart pointer here, but that's fine, since
172    // SemaBuiltinShuffleVector guts it, but then doesn't release it.
173  case Builtin::BI__builtin_prefetch:
174    if (SemaBuiltinPrefetch(TheCall))
175      return ExprError();
176    break;
177  case Builtin::BI__builtin_object_size:
178    if (SemaBuiltinObjectSize(TheCall))
179      return ExprError();
180    break;
181  case Builtin::BI__builtin_longjmp:
182    if (SemaBuiltinLongjmp(TheCall))
183      return ExprError();
184    break;
185
186  case Builtin::BI__builtin_classify_type:
187    if (checkArgCount(*this, TheCall, 1)) return true;
188    TheCall->setType(Context.IntTy);
189    break;
190  case Builtin::BI__builtin_constant_p:
191    if (checkArgCount(*this, TheCall, 1)) return true;
192    TheCall->setType(Context.IntTy);
193    break;
194  case Builtin::BI__sync_fetch_and_add:
195  case Builtin::BI__sync_fetch_and_add_1:
196  case Builtin::BI__sync_fetch_and_add_2:
197  case Builtin::BI__sync_fetch_and_add_4:
198  case Builtin::BI__sync_fetch_and_add_8:
199  case Builtin::BI__sync_fetch_and_add_16:
200  case Builtin::BI__sync_fetch_and_sub:
201  case Builtin::BI__sync_fetch_and_sub_1:
202  case Builtin::BI__sync_fetch_and_sub_2:
203  case Builtin::BI__sync_fetch_and_sub_4:
204  case Builtin::BI__sync_fetch_and_sub_8:
205  case Builtin::BI__sync_fetch_and_sub_16:
206  case Builtin::BI__sync_fetch_and_or:
207  case Builtin::BI__sync_fetch_and_or_1:
208  case Builtin::BI__sync_fetch_and_or_2:
209  case Builtin::BI__sync_fetch_and_or_4:
210  case Builtin::BI__sync_fetch_and_or_8:
211  case Builtin::BI__sync_fetch_and_or_16:
212  case Builtin::BI__sync_fetch_and_and:
213  case Builtin::BI__sync_fetch_and_and_1:
214  case Builtin::BI__sync_fetch_and_and_2:
215  case Builtin::BI__sync_fetch_and_and_4:
216  case Builtin::BI__sync_fetch_and_and_8:
217  case Builtin::BI__sync_fetch_and_and_16:
218  case Builtin::BI__sync_fetch_and_xor:
219  case Builtin::BI__sync_fetch_and_xor_1:
220  case Builtin::BI__sync_fetch_and_xor_2:
221  case Builtin::BI__sync_fetch_and_xor_4:
222  case Builtin::BI__sync_fetch_and_xor_8:
223  case Builtin::BI__sync_fetch_and_xor_16:
224  case Builtin::BI__sync_add_and_fetch:
225  case Builtin::BI__sync_add_and_fetch_1:
226  case Builtin::BI__sync_add_and_fetch_2:
227  case Builtin::BI__sync_add_and_fetch_4:
228  case Builtin::BI__sync_add_and_fetch_8:
229  case Builtin::BI__sync_add_and_fetch_16:
230  case Builtin::BI__sync_sub_and_fetch:
231  case Builtin::BI__sync_sub_and_fetch_1:
232  case Builtin::BI__sync_sub_and_fetch_2:
233  case Builtin::BI__sync_sub_and_fetch_4:
234  case Builtin::BI__sync_sub_and_fetch_8:
235  case Builtin::BI__sync_sub_and_fetch_16:
236  case Builtin::BI__sync_and_and_fetch:
237  case Builtin::BI__sync_and_and_fetch_1:
238  case Builtin::BI__sync_and_and_fetch_2:
239  case Builtin::BI__sync_and_and_fetch_4:
240  case Builtin::BI__sync_and_and_fetch_8:
241  case Builtin::BI__sync_and_and_fetch_16:
242  case Builtin::BI__sync_or_and_fetch:
243  case Builtin::BI__sync_or_and_fetch_1:
244  case Builtin::BI__sync_or_and_fetch_2:
245  case Builtin::BI__sync_or_and_fetch_4:
246  case Builtin::BI__sync_or_and_fetch_8:
247  case Builtin::BI__sync_or_and_fetch_16:
248  case Builtin::BI__sync_xor_and_fetch:
249  case Builtin::BI__sync_xor_and_fetch_1:
250  case Builtin::BI__sync_xor_and_fetch_2:
251  case Builtin::BI__sync_xor_and_fetch_4:
252  case Builtin::BI__sync_xor_and_fetch_8:
253  case Builtin::BI__sync_xor_and_fetch_16:
254  case Builtin::BI__sync_val_compare_and_swap:
255  case Builtin::BI__sync_val_compare_and_swap_1:
256  case Builtin::BI__sync_val_compare_and_swap_2:
257  case Builtin::BI__sync_val_compare_and_swap_4:
258  case Builtin::BI__sync_val_compare_and_swap_8:
259  case Builtin::BI__sync_val_compare_and_swap_16:
260  case Builtin::BI__sync_bool_compare_and_swap:
261  case Builtin::BI__sync_bool_compare_and_swap_1:
262  case Builtin::BI__sync_bool_compare_and_swap_2:
263  case Builtin::BI__sync_bool_compare_and_swap_4:
264  case Builtin::BI__sync_bool_compare_and_swap_8:
265  case Builtin::BI__sync_bool_compare_and_swap_16:
266  case Builtin::BI__sync_lock_test_and_set:
267  case Builtin::BI__sync_lock_test_and_set_1:
268  case Builtin::BI__sync_lock_test_and_set_2:
269  case Builtin::BI__sync_lock_test_and_set_4:
270  case Builtin::BI__sync_lock_test_and_set_8:
271  case Builtin::BI__sync_lock_test_and_set_16:
272  case Builtin::BI__sync_lock_release:
273  case Builtin::BI__sync_lock_release_1:
274  case Builtin::BI__sync_lock_release_2:
275  case Builtin::BI__sync_lock_release_4:
276  case Builtin::BI__sync_lock_release_8:
277  case Builtin::BI__sync_lock_release_16:
278  case Builtin::BI__sync_swap:
279  case Builtin::BI__sync_swap_1:
280  case Builtin::BI__sync_swap_2:
281  case Builtin::BI__sync_swap_4:
282  case Builtin::BI__sync_swap_8:
283  case Builtin::BI__sync_swap_16:
284    return SemaBuiltinAtomicOverloaded(TheCallResult);
285#define BUILTIN(ID, TYPE, ATTRS)
286#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
287  case Builtin::BI##ID: \
288    return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
289#include "clang/Basic/Builtins.def"
290  case Builtin::BI__builtin_annotation:
291    if (SemaBuiltinAnnotation(*this, TheCall))
292      return ExprError();
293    break;
294  case Builtin::BI__builtin_addressof:
295    if (SemaBuiltinAddressof(*this, TheCall))
296      return ExprError();
297    break;
298  }
299
300  // Since the target specific builtins for each arch overlap, only check those
301  // of the arch we are compiling for.
302  if (BuiltinID >= Builtin::FirstTSBuiltin) {
303    switch (Context.getTargetInfo().getTriple().getArch()) {
304      case llvm::Triple::arm:
305      case llvm::Triple::thumb:
306        if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
307          return ExprError();
308        break;
309      case llvm::Triple::aarch64:
310        if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
311          return ExprError();
312        break;
313      case llvm::Triple::mips:
314      case llvm::Triple::mipsel:
315      case llvm::Triple::mips64:
316      case llvm::Triple::mips64el:
317        if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
318          return ExprError();
319        break;
320      default:
321        break;
322    }
323  }
324
325  return TheCallResult;
326}
327
328// Get the valid immediate range for the specified NEON type code.
329static unsigned RFT(unsigned t, bool shift = false) {
330  NeonTypeFlags Type(t);
331  int IsQuad = Type.isQuad();
332  switch (Type.getEltType()) {
333  case NeonTypeFlags::Int8:
334  case NeonTypeFlags::Poly8:
335    return shift ? 7 : (8 << IsQuad) - 1;
336  case NeonTypeFlags::Int16:
337  case NeonTypeFlags::Poly16:
338    return shift ? 15 : (4 << IsQuad) - 1;
339  case NeonTypeFlags::Int32:
340    return shift ? 31 : (2 << IsQuad) - 1;
341  case NeonTypeFlags::Int64:
342  case NeonTypeFlags::Poly64:
343    return shift ? 63 : (1 << IsQuad) - 1;
344  case NeonTypeFlags::Float16:
345    assert(!shift && "cannot shift float types!");
346    return (4 << IsQuad) - 1;
347  case NeonTypeFlags::Float32:
348    assert(!shift && "cannot shift float types!");
349    return (2 << IsQuad) - 1;
350  case NeonTypeFlags::Float64:
351    assert(!shift && "cannot shift float types!");
352    return (1 << IsQuad) - 1;
353  }
354  llvm_unreachable("Invalid NeonTypeFlag!");
355}
356
357/// getNeonEltType - Return the QualType corresponding to the elements of
358/// the vector type specified by the NeonTypeFlags.  This is used to check
359/// the pointer arguments for Neon load/store intrinsics.
360static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
361                               bool IsAArch64) {
362  switch (Flags.getEltType()) {
363  case NeonTypeFlags::Int8:
364    return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
365  case NeonTypeFlags::Int16:
366    return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
367  case NeonTypeFlags::Int32:
368    return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
369  case NeonTypeFlags::Int64:
370    return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
371  case NeonTypeFlags::Poly8:
372    return IsAArch64 ? Context.UnsignedCharTy : Context.SignedCharTy;
373  case NeonTypeFlags::Poly16:
374    return IsAArch64 ? Context.UnsignedShortTy : Context.ShortTy;
375  case NeonTypeFlags::Poly64:
376    return Context.UnsignedLongLongTy;
377  case NeonTypeFlags::Float16:
378    return Context.HalfTy;
379  case NeonTypeFlags::Float32:
380    return Context.FloatTy;
381  case NeonTypeFlags::Float64:
382    return Context.DoubleTy;
383  }
384  llvm_unreachable("Invalid NeonTypeFlag!");
385}
386
387bool Sema::CheckAArch64BuiltinFunctionCall(unsigned BuiltinID,
388                                           CallExpr *TheCall) {
389
390  llvm::APSInt Result;
391
392  uint64_t mask = 0;
393  unsigned TV = 0;
394  int PtrArgNum = -1;
395  bool HasConstPtr = false;
396  switch (BuiltinID) {
397#define GET_NEON_AARCH64_OVERLOAD_CHECK
398#include "clang/Basic/arm_neon.inc"
399#undef GET_NEON_AARCH64_OVERLOAD_CHECK
400  }
401
402  // For NEON intrinsics which are overloaded on vector element type, validate
403  // the immediate which specifies which variant to emit.
404  unsigned ImmArg = TheCall->getNumArgs() - 1;
405  if (mask) {
406    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
407      return true;
408
409    TV = Result.getLimitedValue(64);
410    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
411      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
412             << TheCall->getArg(ImmArg)->getSourceRange();
413  }
414
415  if (PtrArgNum >= 0) {
416    // Check that pointer arguments have the specified type.
417    Expr *Arg = TheCall->getArg(PtrArgNum);
418    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
419      Arg = ICE->getSubExpr();
420    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
421    QualType RHSTy = RHS.get()->getType();
422    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, true);
423    if (HasConstPtr)
424      EltTy = EltTy.withConst();
425    QualType LHSTy = Context.getPointerType(EltTy);
426    AssignConvertType ConvTy;
427    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
428    if (RHS.isInvalid())
429      return true;
430    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
431                                 RHS.get(), AA_Assigning))
432      return true;
433  }
434
435  // For NEON intrinsics which take an immediate value as part of the
436  // instruction, range check them here.
437  unsigned i = 0, l = 0, u = 0;
438  switch (BuiltinID) {
439  default:
440    return false;
441#define GET_NEON_AARCH64_IMMEDIATE_CHECK
442#include "clang/Basic/arm_neon.inc"
443#undef GET_NEON_AARCH64_IMMEDIATE_CHECK
444  }
445  ;
446
447  // We can't check the value of a dependent argument.
448  if (TheCall->getArg(i)->isTypeDependent() ||
449      TheCall->getArg(i)->isValueDependent())
450    return false;
451
452  // Check that the immediate argument is actually a constant.
453  if (SemaBuiltinConstantArg(TheCall, i, Result))
454    return true;
455
456  // Range check against the upper/lower values for this isntruction.
457  unsigned Val = Result.getZExtValue();
458  if (Val < l || Val > (u + l))
459    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
460           << l << u + l << TheCall->getArg(i)->getSourceRange();
461
462  return false;
463}
464
465bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall) {
466  assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
467          BuiltinID == ARM::BI__builtin_arm_strex) &&
468         "unexpected ARM builtin");
469  bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex;
470
471  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
472
473  // Ensure that we have the proper number of arguments.
474  if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
475    return true;
476
477  // Inspect the pointer argument of the atomic builtin.  This should always be
478  // a pointer type, whose element is an integral scalar or pointer type.
479  // Because it is a pointer type, we don't have to worry about any implicit
480  // casts here.
481  Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
482  ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
483  if (PointerArgRes.isInvalid())
484    return true;
485  PointerArg = PointerArgRes.take();
486
487  const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
488  if (!pointerType) {
489    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
490      << PointerArg->getType() << PointerArg->getSourceRange();
491    return true;
492  }
493
494  // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
495  // task is to insert the appropriate casts into the AST. First work out just
496  // what the appropriate type is.
497  QualType ValType = pointerType->getPointeeType();
498  QualType AddrType = ValType.getUnqualifiedType().withVolatile();
499  if (IsLdrex)
500    AddrType.addConst();
501
502  // Issue a warning if the cast is dodgy.
503  CastKind CastNeeded = CK_NoOp;
504  if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
505    CastNeeded = CK_BitCast;
506    Diag(DRE->getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
507      << PointerArg->getType()
508      << Context.getPointerType(AddrType)
509      << AA_Passing << PointerArg->getSourceRange();
510  }
511
512  // Finally, do the cast and replace the argument with the corrected version.
513  AddrType = Context.getPointerType(AddrType);
514  PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
515  if (PointerArgRes.isInvalid())
516    return true;
517  PointerArg = PointerArgRes.take();
518
519  TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
520
521  // In general, we allow ints, floats and pointers to be loaded and stored.
522  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
523      !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
524    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
525      << PointerArg->getType() << PointerArg->getSourceRange();
526    return true;
527  }
528
529  // But ARM doesn't have instructions to deal with 128-bit versions.
530  if (Context.getTypeSize(ValType) > 64) {
531    Diag(DRE->getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
532      << PointerArg->getType() << PointerArg->getSourceRange();
533    return true;
534  }
535
536  switch (ValType.getObjCLifetime()) {
537  case Qualifiers::OCL_None:
538  case Qualifiers::OCL_ExplicitNone:
539    // okay
540    break;
541
542  case Qualifiers::OCL_Weak:
543  case Qualifiers::OCL_Strong:
544  case Qualifiers::OCL_Autoreleasing:
545    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
546      << ValType << PointerArg->getSourceRange();
547    return true;
548  }
549
550
551  if (IsLdrex) {
552    TheCall->setType(ValType);
553    return false;
554  }
555
556  // Initialize the argument to be stored.
557  ExprResult ValArg = TheCall->getArg(0);
558  InitializedEntity Entity = InitializedEntity::InitializeParameter(
559      Context, ValType, /*consume*/ false);
560  ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
561  if (ValArg.isInvalid())
562    return true;
563  TheCall->setArg(0, ValArg.get());
564
565  // __builtin_arm_strex always returns an int. It's marked as such in the .def,
566  // but the custom checker bypasses all default analysis.
567  TheCall->setType(Context.IntTy);
568  return false;
569}
570
571bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
572  llvm::APSInt Result;
573
574  if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
575      BuiltinID == ARM::BI__builtin_arm_strex) {
576    return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall);
577  }
578
579  uint64_t mask = 0;
580  unsigned TV = 0;
581  int PtrArgNum = -1;
582  bool HasConstPtr = false;
583  switch (BuiltinID) {
584#define GET_NEON_OVERLOAD_CHECK
585#include "clang/Basic/arm_neon.inc"
586#undef GET_NEON_OVERLOAD_CHECK
587  }
588
589  // For NEON intrinsics which are overloaded on vector element type, validate
590  // the immediate which specifies which variant to emit.
591  unsigned ImmArg = TheCall->getNumArgs()-1;
592  if (mask) {
593    if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
594      return true;
595
596    TV = Result.getLimitedValue(64);
597    if ((TV > 63) || (mask & (1ULL << TV)) == 0)
598      return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
599        << TheCall->getArg(ImmArg)->getSourceRange();
600  }
601
602  if (PtrArgNum >= 0) {
603    // Check that pointer arguments have the specified type.
604    Expr *Arg = TheCall->getArg(PtrArgNum);
605    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
606      Arg = ICE->getSubExpr();
607    ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
608    QualType RHSTy = RHS.get()->getType();
609    QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context, false);
610    if (HasConstPtr)
611      EltTy = EltTy.withConst();
612    QualType LHSTy = Context.getPointerType(EltTy);
613    AssignConvertType ConvTy;
614    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
615    if (RHS.isInvalid())
616      return true;
617    if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
618                                 RHS.get(), AA_Assigning))
619      return true;
620  }
621
622  // For NEON intrinsics which take an immediate value as part of the
623  // instruction, range check them here.
624  unsigned i = 0, l = 0, u = 0;
625  switch (BuiltinID) {
626  default: return false;
627  case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
628  case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
629  case ARM::BI__builtin_arm_vcvtr_f:
630  case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
631  case ARM::BI__builtin_arm_dmb:
632  case ARM::BI__builtin_arm_dsb: l = 0; u = 15; break;
633#define GET_NEON_IMMEDIATE_CHECK
634#include "clang/Basic/arm_neon.inc"
635#undef GET_NEON_IMMEDIATE_CHECK
636  };
637
638  // We can't check the value of a dependent argument.
639  if (TheCall->getArg(i)->isTypeDependent() ||
640      TheCall->getArg(i)->isValueDependent())
641    return false;
642
643  // Check that the immediate argument is actually a constant.
644  if (SemaBuiltinConstantArg(TheCall, i, Result))
645    return true;
646
647  // Range check against the upper/lower values for this isntruction.
648  unsigned Val = Result.getZExtValue();
649  if (Val < l || Val > (u + l))
650    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
651      << l << u+l << TheCall->getArg(i)->getSourceRange();
652
653  // FIXME: VFP Intrinsics should error if VFP not present.
654  return false;
655}
656
657bool Sema::CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
658  unsigned i = 0, l = 0, u = 0;
659  switch (BuiltinID) {
660  default: return false;
661  case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
662  case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
663  case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
664  case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
665  case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
666  case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
667  case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
668  };
669
670  // We can't check the value of a dependent argument.
671  if (TheCall->getArg(i)->isTypeDependent() ||
672      TheCall->getArg(i)->isValueDependent())
673    return false;
674
675  // Check that the immediate argument is actually a constant.
676  llvm::APSInt Result;
677  if (SemaBuiltinConstantArg(TheCall, i, Result))
678    return true;
679
680  // Range check against the upper/lower values for this instruction.
681  unsigned Val = Result.getZExtValue();
682  if (Val < l || Val > u)
683    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
684      << l << u << TheCall->getArg(i)->getSourceRange();
685
686  return false;
687}
688
689/// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
690/// parameter with the FormatAttr's correct format_idx and firstDataArg.
691/// Returns true when the format fits the function and the FormatStringInfo has
692/// been populated.
693bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
694                               FormatStringInfo *FSI) {
695  FSI->HasVAListArg = Format->getFirstArg() == 0;
696  FSI->FormatIdx = Format->getFormatIdx() - 1;
697  FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
698
699  // The way the format attribute works in GCC, the implicit this argument
700  // of member functions is counted. However, it doesn't appear in our own
701  // lists, so decrement format_idx in that case.
702  if (IsCXXMember) {
703    if(FSI->FormatIdx == 0)
704      return false;
705    --FSI->FormatIdx;
706    if (FSI->FirstDataArg != 0)
707      --FSI->FirstDataArg;
708  }
709  return true;
710}
711
712/// Handles the checks for format strings, non-POD arguments to vararg
713/// functions, and NULL arguments passed to non-NULL parameters.
714void Sema::checkCall(NamedDecl *FDecl,
715                     ArrayRef<const Expr *> Args,
716                     unsigned NumProtoArgs,
717                     bool IsMemberFunction,
718                     SourceLocation Loc,
719                     SourceRange Range,
720                     VariadicCallType CallType) {
721  // FIXME: We should check as much as we can in the template definition.
722  if (CurContext->isDependentContext())
723    return;
724
725  // Printf and scanf checking.
726  llvm::SmallBitVector CheckedVarArgs;
727  if (FDecl) {
728    for (specific_attr_iterator<FormatAttr>
729             I = FDecl->specific_attr_begin<FormatAttr>(),
730             E = FDecl->specific_attr_end<FormatAttr>();
731         I != E; ++I) {
732      // Only create vector if there are format attributes.
733      CheckedVarArgs.resize(Args.size());
734
735      CheckFormatArguments(*I, Args, IsMemberFunction, CallType, Loc, Range,
736                           CheckedVarArgs);
737    }
738  }
739
740  // Refuse POD arguments that weren't caught by the format string
741  // checks above.
742  if (CallType != VariadicDoesNotApply) {
743    for (unsigned ArgIdx = NumProtoArgs; ArgIdx < Args.size(); ++ArgIdx) {
744      // Args[ArgIdx] can be null in malformed code.
745      if (const Expr *Arg = Args[ArgIdx]) {
746        if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
747          checkVariadicArgument(Arg, CallType);
748      }
749    }
750  }
751
752  if (FDecl) {
753    for (specific_attr_iterator<NonNullAttr>
754           I = FDecl->specific_attr_begin<NonNullAttr>(),
755           E = FDecl->specific_attr_end<NonNullAttr>(); I != E; ++I)
756      CheckNonNullArguments(*I, Args.data(), Loc);
757
758    // Type safety checking.
759    for (specific_attr_iterator<ArgumentWithTypeTagAttr>
760           i = FDecl->specific_attr_begin<ArgumentWithTypeTagAttr>(),
761           e = FDecl->specific_attr_end<ArgumentWithTypeTagAttr>();
762         i != e; ++i) {
763      CheckArgumentWithTypeTag(*i, Args.data());
764    }
765  }
766}
767
768/// CheckConstructorCall - Check a constructor call for correctness and safety
769/// properties not enforced by the C type system.
770void Sema::CheckConstructorCall(FunctionDecl *FDecl,
771                                ArrayRef<const Expr *> Args,
772                                const FunctionProtoType *Proto,
773                                SourceLocation Loc) {
774  VariadicCallType CallType =
775    Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
776  checkCall(FDecl, Args, Proto->getNumArgs(),
777            /*IsMemberFunction=*/true, Loc, SourceRange(), CallType);
778}
779
780/// CheckFunctionCall - Check a direct function call for various correctness
781/// and safety properties not strictly enforced by the C type system.
782bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
783                             const FunctionProtoType *Proto) {
784  bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
785                              isa<CXXMethodDecl>(FDecl);
786  bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
787                          IsMemberOperatorCall;
788  VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
789                                                  TheCall->getCallee());
790  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
791  Expr** Args = TheCall->getArgs();
792  unsigned NumArgs = TheCall->getNumArgs();
793  if (IsMemberOperatorCall) {
794    // If this is a call to a member operator, hide the first argument
795    // from checkCall.
796    // FIXME: Our choice of AST representation here is less than ideal.
797    ++Args;
798    --NumArgs;
799  }
800  checkCall(FDecl, llvm::makeArrayRef<const Expr *>(Args, NumArgs),
801            NumProtoArgs,
802            IsMemberFunction, TheCall->getRParenLoc(),
803            TheCall->getCallee()->getSourceRange(), CallType);
804
805  IdentifierInfo *FnInfo = FDecl->getIdentifier();
806  // None of the checks below are needed for functions that don't have
807  // simple names (e.g., C++ conversion functions).
808  if (!FnInfo)
809    return false;
810
811  unsigned CMId = FDecl->getMemoryFunctionKind();
812  if (CMId == 0)
813    return false;
814
815  // Handle memory setting and copying functions.
816  if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
817    CheckStrlcpycatArguments(TheCall, FnInfo);
818  else if (CMId == Builtin::BIstrncat)
819    CheckStrncatArguments(TheCall, FnInfo);
820  else
821    CheckMemaccessArguments(TheCall, CMId, FnInfo);
822
823  return false;
824}
825
826bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
827                               ArrayRef<const Expr *> Args) {
828  VariadicCallType CallType =
829      Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
830
831  checkCall(Method, Args, Method->param_size(),
832            /*IsMemberFunction=*/false,
833            lbrac, Method->getSourceRange(), CallType);
834
835  return false;
836}
837
838bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
839                            const FunctionProtoType *Proto) {
840  const VarDecl *V = dyn_cast<VarDecl>(NDecl);
841  if (!V)
842    return false;
843
844  QualType Ty = V->getType();
845  if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType())
846    return false;
847
848  VariadicCallType CallType;
849  if (!Proto || !Proto->isVariadic()) {
850    CallType = VariadicDoesNotApply;
851  } else if (Ty->isBlockPointerType()) {
852    CallType = VariadicBlock;
853  } else { // Ty->isFunctionPointerType()
854    CallType = VariadicFunction;
855  }
856  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
857
858  checkCall(NDecl,
859            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
860                                             TheCall->getNumArgs()),
861            NumProtoArgs, /*IsMemberFunction=*/false,
862            TheCall->getRParenLoc(),
863            TheCall->getCallee()->getSourceRange(), CallType);
864
865  return false;
866}
867
868/// Checks function calls when a FunctionDecl or a NamedDecl is not available,
869/// such as function pointers returned from functions.
870bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
871  VariadicCallType CallType = getVariadicCallType(/*FDecl=*/0, Proto,
872                                                  TheCall->getCallee());
873  unsigned NumProtoArgs = Proto ? Proto->getNumArgs() : 0;
874
875  checkCall(/*FDecl=*/0,
876            llvm::makeArrayRef<const Expr *>(TheCall->getArgs(),
877                                             TheCall->getNumArgs()),
878            NumProtoArgs, /*IsMemberFunction=*/false,
879            TheCall->getRParenLoc(),
880            TheCall->getCallee()->getSourceRange(), CallType);
881
882  return false;
883}
884
885ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
886                                         AtomicExpr::AtomicOp Op) {
887  CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
888  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
889
890  // All these operations take one of the following forms:
891  enum {
892    // C    __c11_atomic_init(A *, C)
893    Init,
894    // C    __c11_atomic_load(A *, int)
895    Load,
896    // void __atomic_load(A *, CP, int)
897    Copy,
898    // C    __c11_atomic_add(A *, M, int)
899    Arithmetic,
900    // C    __atomic_exchange_n(A *, CP, int)
901    Xchg,
902    // void __atomic_exchange(A *, C *, CP, int)
903    GNUXchg,
904    // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
905    C11CmpXchg,
906    // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
907    GNUCmpXchg
908  } Form = Init;
909  const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
910  const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
911  // where:
912  //   C is an appropriate type,
913  //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
914  //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
915  //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
916  //   the int parameters are for orderings.
917
918  assert(AtomicExpr::AO__c11_atomic_init == 0 &&
919         AtomicExpr::AO__c11_atomic_fetch_xor + 1 == AtomicExpr::AO__atomic_load
920         && "need to update code for modified C11 atomics");
921  bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
922               Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
923  bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
924             Op == AtomicExpr::AO__atomic_store_n ||
925             Op == AtomicExpr::AO__atomic_exchange_n ||
926             Op == AtomicExpr::AO__atomic_compare_exchange_n;
927  bool IsAddSub = false;
928
929  switch (Op) {
930  case AtomicExpr::AO__c11_atomic_init:
931    Form = Init;
932    break;
933
934  case AtomicExpr::AO__c11_atomic_load:
935  case AtomicExpr::AO__atomic_load_n:
936    Form = Load;
937    break;
938
939  case AtomicExpr::AO__c11_atomic_store:
940  case AtomicExpr::AO__atomic_load:
941  case AtomicExpr::AO__atomic_store:
942  case AtomicExpr::AO__atomic_store_n:
943    Form = Copy;
944    break;
945
946  case AtomicExpr::AO__c11_atomic_fetch_add:
947  case AtomicExpr::AO__c11_atomic_fetch_sub:
948  case AtomicExpr::AO__atomic_fetch_add:
949  case AtomicExpr::AO__atomic_fetch_sub:
950  case AtomicExpr::AO__atomic_add_fetch:
951  case AtomicExpr::AO__atomic_sub_fetch:
952    IsAddSub = true;
953    // Fall through.
954  case AtomicExpr::AO__c11_atomic_fetch_and:
955  case AtomicExpr::AO__c11_atomic_fetch_or:
956  case AtomicExpr::AO__c11_atomic_fetch_xor:
957  case AtomicExpr::AO__atomic_fetch_and:
958  case AtomicExpr::AO__atomic_fetch_or:
959  case AtomicExpr::AO__atomic_fetch_xor:
960  case AtomicExpr::AO__atomic_fetch_nand:
961  case AtomicExpr::AO__atomic_and_fetch:
962  case AtomicExpr::AO__atomic_or_fetch:
963  case AtomicExpr::AO__atomic_xor_fetch:
964  case AtomicExpr::AO__atomic_nand_fetch:
965    Form = Arithmetic;
966    break;
967
968  case AtomicExpr::AO__c11_atomic_exchange:
969  case AtomicExpr::AO__atomic_exchange_n:
970    Form = Xchg;
971    break;
972
973  case AtomicExpr::AO__atomic_exchange:
974    Form = GNUXchg;
975    break;
976
977  case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
978  case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
979    Form = C11CmpXchg;
980    break;
981
982  case AtomicExpr::AO__atomic_compare_exchange:
983  case AtomicExpr::AO__atomic_compare_exchange_n:
984    Form = GNUCmpXchg;
985    break;
986  }
987
988  // Check we have the right number of arguments.
989  if (TheCall->getNumArgs() < NumArgs[Form]) {
990    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
991      << 0 << NumArgs[Form] << TheCall->getNumArgs()
992      << TheCall->getCallee()->getSourceRange();
993    return ExprError();
994  } else if (TheCall->getNumArgs() > NumArgs[Form]) {
995    Diag(TheCall->getArg(NumArgs[Form])->getLocStart(),
996         diag::err_typecheck_call_too_many_args)
997      << 0 << NumArgs[Form] << TheCall->getNumArgs()
998      << TheCall->getCallee()->getSourceRange();
999    return ExprError();
1000  }
1001
1002  // Inspect the first argument of the atomic operation.
1003  Expr *Ptr = TheCall->getArg(0);
1004  Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1005  const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
1006  if (!pointerType) {
1007    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1008      << Ptr->getType() << Ptr->getSourceRange();
1009    return ExprError();
1010  }
1011
1012  // For a __c11 builtin, this should be a pointer to an _Atomic type.
1013  QualType AtomTy = pointerType->getPointeeType(); // 'A'
1014  QualType ValType = AtomTy; // 'C'
1015  if (IsC11) {
1016    if (!AtomTy->isAtomicType()) {
1017      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1018        << Ptr->getType() << Ptr->getSourceRange();
1019      return ExprError();
1020    }
1021    if (AtomTy.isConstQualified()) {
1022      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1023        << Ptr->getType() << Ptr->getSourceRange();
1024      return ExprError();
1025    }
1026    ValType = AtomTy->getAs<AtomicType>()->getValueType();
1027  }
1028
1029  // For an arithmetic operation, the implied arithmetic must be well-formed.
1030  if (Form == Arithmetic) {
1031    // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
1032    if (IsAddSub && !ValType->isIntegerType() && !ValType->isPointerType()) {
1033      Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1034        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1035      return ExprError();
1036    }
1037    if (!IsAddSub && !ValType->isIntegerType()) {
1038      Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1039        << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1040      return ExprError();
1041    }
1042  } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
1043    // For __atomic_*_n operations, the value type must be a scalar integral or
1044    // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
1045    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1046      << IsC11 << Ptr->getType() << Ptr->getSourceRange();
1047    return ExprError();
1048  }
1049
1050  if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
1051      !AtomTy->isScalarType()) {
1052    // For GNU atomics, require a trivially-copyable type. This is not part of
1053    // the GNU atomics specification, but we enforce it for sanity.
1054    Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1055      << Ptr->getType() << Ptr->getSourceRange();
1056    return ExprError();
1057  }
1058
1059  // FIXME: For any builtin other than a load, the ValType must not be
1060  // const-qualified.
1061
1062  switch (ValType.getObjCLifetime()) {
1063  case Qualifiers::OCL_None:
1064  case Qualifiers::OCL_ExplicitNone:
1065    // okay
1066    break;
1067
1068  case Qualifiers::OCL_Weak:
1069  case Qualifiers::OCL_Strong:
1070  case Qualifiers::OCL_Autoreleasing:
1071    // FIXME: Can this happen? By this point, ValType should be known
1072    // to be trivially copyable.
1073    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1074      << ValType << Ptr->getSourceRange();
1075    return ExprError();
1076  }
1077
1078  QualType ResultType = ValType;
1079  if (Form == Copy || Form == GNUXchg || Form == Init)
1080    ResultType = Context.VoidTy;
1081  else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1082    ResultType = Context.BoolTy;
1083
1084  // The type of a parameter passed 'by value'. In the GNU atomics, such
1085  // arguments are actually passed as pointers.
1086  QualType ByValType = ValType; // 'CP'
1087  if (!IsC11 && !IsN)
1088    ByValType = Ptr->getType();
1089
1090  // The first argument --- the pointer --- has a fixed type; we
1091  // deduce the types of the rest of the arguments accordingly.  Walk
1092  // the remaining arguments, converting them to the deduced value type.
1093  for (unsigned i = 1; i != NumArgs[Form]; ++i) {
1094    QualType Ty;
1095    if (i < NumVals[Form] + 1) {
1096      switch (i) {
1097      case 1:
1098        // The second argument is the non-atomic operand. For arithmetic, this
1099        // is always passed by value, and for a compare_exchange it is always
1100        // passed by address. For the rest, GNU uses by-address and C11 uses
1101        // by-value.
1102        assert(Form != Load);
1103        if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
1104          Ty = ValType;
1105        else if (Form == Copy || Form == Xchg)
1106          Ty = ByValType;
1107        else if (Form == Arithmetic)
1108          Ty = Context.getPointerDiffType();
1109        else
1110          Ty = Context.getPointerType(ValType.getUnqualifiedType());
1111        break;
1112      case 2:
1113        // The third argument to compare_exchange / GNU exchange is a
1114        // (pointer to a) desired value.
1115        Ty = ByValType;
1116        break;
1117      case 3:
1118        // The fourth argument to GNU compare_exchange is a 'weak' flag.
1119        Ty = Context.BoolTy;
1120        break;
1121      }
1122    } else {
1123      // The order(s) are always converted to int.
1124      Ty = Context.IntTy;
1125    }
1126
1127    InitializedEntity Entity =
1128        InitializedEntity::InitializeParameter(Context, Ty, false);
1129    ExprResult Arg = TheCall->getArg(i);
1130    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1131    if (Arg.isInvalid())
1132      return true;
1133    TheCall->setArg(i, Arg.get());
1134  }
1135
1136  // Permute the arguments into a 'consistent' order.
1137  SmallVector<Expr*, 5> SubExprs;
1138  SubExprs.push_back(Ptr);
1139  switch (Form) {
1140  case Init:
1141    // Note, AtomicExpr::getVal1() has a special case for this atomic.
1142    SubExprs.push_back(TheCall->getArg(1)); // Val1
1143    break;
1144  case Load:
1145    SubExprs.push_back(TheCall->getArg(1)); // Order
1146    break;
1147  case Copy:
1148  case Arithmetic:
1149  case Xchg:
1150    SubExprs.push_back(TheCall->getArg(2)); // Order
1151    SubExprs.push_back(TheCall->getArg(1)); // Val1
1152    break;
1153  case GNUXchg:
1154    // Note, AtomicExpr::getVal2() has a special case for this atomic.
1155    SubExprs.push_back(TheCall->getArg(3)); // Order
1156    SubExprs.push_back(TheCall->getArg(1)); // Val1
1157    SubExprs.push_back(TheCall->getArg(2)); // Val2
1158    break;
1159  case C11CmpXchg:
1160    SubExprs.push_back(TheCall->getArg(3)); // Order
1161    SubExprs.push_back(TheCall->getArg(1)); // Val1
1162    SubExprs.push_back(TheCall->getArg(4)); // OrderFail
1163    SubExprs.push_back(TheCall->getArg(2)); // Val2
1164    break;
1165  case GNUCmpXchg:
1166    SubExprs.push_back(TheCall->getArg(4)); // Order
1167    SubExprs.push_back(TheCall->getArg(1)); // Val1
1168    SubExprs.push_back(TheCall->getArg(5)); // OrderFail
1169    SubExprs.push_back(TheCall->getArg(2)); // Val2
1170    SubExprs.push_back(TheCall->getArg(3)); // Weak
1171    break;
1172  }
1173
1174  AtomicExpr *AE = new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
1175                                            SubExprs, ResultType, Op,
1176                                            TheCall->getRParenLoc());
1177
1178  if ((Op == AtomicExpr::AO__c11_atomic_load ||
1179       (Op == AtomicExpr::AO__c11_atomic_store)) &&
1180      Context.AtomicUsesUnsupportedLibcall(AE))
1181    Diag(AE->getLocStart(), diag::err_atomic_load_store_uses_lib) <<
1182    ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1183
1184  return Owned(AE);
1185}
1186
1187
1188/// checkBuiltinArgument - Given a call to a builtin function, perform
1189/// normal type-checking on the given argument, updating the call in
1190/// place.  This is useful when a builtin function requires custom
1191/// type-checking for some of its arguments but not necessarily all of
1192/// them.
1193///
1194/// Returns true on error.
1195static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
1196  FunctionDecl *Fn = E->getDirectCallee();
1197  assert(Fn && "builtin call without direct callee!");
1198
1199  ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
1200  InitializedEntity Entity =
1201    InitializedEntity::InitializeParameter(S.Context, Param);
1202
1203  ExprResult Arg = E->getArg(0);
1204  Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
1205  if (Arg.isInvalid())
1206    return true;
1207
1208  E->setArg(ArgIndex, Arg.take());
1209  return false;
1210}
1211
1212/// SemaBuiltinAtomicOverloaded - We have a call to a function like
1213/// __sync_fetch_and_add, which is an overloaded function based on the pointer
1214/// type of its first argument.  The main ActOnCallExpr routines have already
1215/// promoted the types of arguments because all of these calls are prototyped as
1216/// void(...).
1217///
1218/// This function goes through and does final semantic checking for these
1219/// builtins,
1220ExprResult
1221Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
1222  CallExpr *TheCall = (CallExpr *)TheCallResult.get();
1223  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1224  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1225
1226  // Ensure that we have at least one argument to do type inference from.
1227  if (TheCall->getNumArgs() < 1) {
1228    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1229      << 0 << 1 << TheCall->getNumArgs()
1230      << TheCall->getCallee()->getSourceRange();
1231    return ExprError();
1232  }
1233
1234  // Inspect the first argument of the atomic builtin.  This should always be
1235  // a pointer type, whose element is an integral scalar or pointer type.
1236  // Because it is a pointer type, we don't have to worry about any implicit
1237  // casts here.
1238  // FIXME: We don't allow floating point scalars as input.
1239  Expr *FirstArg = TheCall->getArg(0);
1240  ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1241  if (FirstArgResult.isInvalid())
1242    return ExprError();
1243  FirstArg = FirstArgResult.take();
1244  TheCall->setArg(0, FirstArg);
1245
1246  const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
1247  if (!pointerType) {
1248    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1249      << FirstArg->getType() << FirstArg->getSourceRange();
1250    return ExprError();
1251  }
1252
1253  QualType ValType = pointerType->getPointeeType();
1254  if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
1255      !ValType->isBlockPointerType()) {
1256    Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1257      << FirstArg->getType() << FirstArg->getSourceRange();
1258    return ExprError();
1259  }
1260
1261  switch (ValType.getObjCLifetime()) {
1262  case Qualifiers::OCL_None:
1263  case Qualifiers::OCL_ExplicitNone:
1264    // okay
1265    break;
1266
1267  case Qualifiers::OCL_Weak:
1268  case Qualifiers::OCL_Strong:
1269  case Qualifiers::OCL_Autoreleasing:
1270    Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1271      << ValType << FirstArg->getSourceRange();
1272    return ExprError();
1273  }
1274
1275  // Strip any qualifiers off ValType.
1276  ValType = ValType.getUnqualifiedType();
1277
1278  // The majority of builtins return a value, but a few have special return
1279  // types, so allow them to override appropriately below.
1280  QualType ResultType = ValType;
1281
1282  // We need to figure out which concrete builtin this maps onto.  For example,
1283  // __sync_fetch_and_add with a 2 byte object turns into
1284  // __sync_fetch_and_add_2.
1285#define BUILTIN_ROW(x) \
1286  { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1287    Builtin::BI##x##_8, Builtin::BI##x##_16 }
1288
1289  static const unsigned BuiltinIndices[][5] = {
1290    BUILTIN_ROW(__sync_fetch_and_add),
1291    BUILTIN_ROW(__sync_fetch_and_sub),
1292    BUILTIN_ROW(__sync_fetch_and_or),
1293    BUILTIN_ROW(__sync_fetch_and_and),
1294    BUILTIN_ROW(__sync_fetch_and_xor),
1295
1296    BUILTIN_ROW(__sync_add_and_fetch),
1297    BUILTIN_ROW(__sync_sub_and_fetch),
1298    BUILTIN_ROW(__sync_and_and_fetch),
1299    BUILTIN_ROW(__sync_or_and_fetch),
1300    BUILTIN_ROW(__sync_xor_and_fetch),
1301
1302    BUILTIN_ROW(__sync_val_compare_and_swap),
1303    BUILTIN_ROW(__sync_bool_compare_and_swap),
1304    BUILTIN_ROW(__sync_lock_test_and_set),
1305    BUILTIN_ROW(__sync_lock_release),
1306    BUILTIN_ROW(__sync_swap)
1307  };
1308#undef BUILTIN_ROW
1309
1310  // Determine the index of the size.
1311  unsigned SizeIndex;
1312  switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
1313  case 1: SizeIndex = 0; break;
1314  case 2: SizeIndex = 1; break;
1315  case 4: SizeIndex = 2; break;
1316  case 8: SizeIndex = 3; break;
1317  case 16: SizeIndex = 4; break;
1318  default:
1319    Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
1320      << FirstArg->getType() << FirstArg->getSourceRange();
1321    return ExprError();
1322  }
1323
1324  // Each of these builtins has one pointer argument, followed by some number of
1325  // values (0, 1 or 2) followed by a potentially empty varags list of stuff
1326  // that we ignore.  Find out which row of BuiltinIndices to read from as well
1327  // as the number of fixed args.
1328  unsigned BuiltinID = FDecl->getBuiltinID();
1329  unsigned BuiltinIndex, NumFixed = 1;
1330  switch (BuiltinID) {
1331  default: llvm_unreachable("Unknown overloaded atomic builtin!");
1332  case Builtin::BI__sync_fetch_and_add:
1333  case Builtin::BI__sync_fetch_and_add_1:
1334  case Builtin::BI__sync_fetch_and_add_2:
1335  case Builtin::BI__sync_fetch_and_add_4:
1336  case Builtin::BI__sync_fetch_and_add_8:
1337  case Builtin::BI__sync_fetch_and_add_16:
1338    BuiltinIndex = 0;
1339    break;
1340
1341  case Builtin::BI__sync_fetch_and_sub:
1342  case Builtin::BI__sync_fetch_and_sub_1:
1343  case Builtin::BI__sync_fetch_and_sub_2:
1344  case Builtin::BI__sync_fetch_and_sub_4:
1345  case Builtin::BI__sync_fetch_and_sub_8:
1346  case Builtin::BI__sync_fetch_and_sub_16:
1347    BuiltinIndex = 1;
1348    break;
1349
1350  case Builtin::BI__sync_fetch_and_or:
1351  case Builtin::BI__sync_fetch_and_or_1:
1352  case Builtin::BI__sync_fetch_and_or_2:
1353  case Builtin::BI__sync_fetch_and_or_4:
1354  case Builtin::BI__sync_fetch_and_or_8:
1355  case Builtin::BI__sync_fetch_and_or_16:
1356    BuiltinIndex = 2;
1357    break;
1358
1359  case Builtin::BI__sync_fetch_and_and:
1360  case Builtin::BI__sync_fetch_and_and_1:
1361  case Builtin::BI__sync_fetch_and_and_2:
1362  case Builtin::BI__sync_fetch_and_and_4:
1363  case Builtin::BI__sync_fetch_and_and_8:
1364  case Builtin::BI__sync_fetch_and_and_16:
1365    BuiltinIndex = 3;
1366    break;
1367
1368  case Builtin::BI__sync_fetch_and_xor:
1369  case Builtin::BI__sync_fetch_and_xor_1:
1370  case Builtin::BI__sync_fetch_and_xor_2:
1371  case Builtin::BI__sync_fetch_and_xor_4:
1372  case Builtin::BI__sync_fetch_and_xor_8:
1373  case Builtin::BI__sync_fetch_and_xor_16:
1374    BuiltinIndex = 4;
1375    break;
1376
1377  case Builtin::BI__sync_add_and_fetch:
1378  case Builtin::BI__sync_add_and_fetch_1:
1379  case Builtin::BI__sync_add_and_fetch_2:
1380  case Builtin::BI__sync_add_and_fetch_4:
1381  case Builtin::BI__sync_add_and_fetch_8:
1382  case Builtin::BI__sync_add_and_fetch_16:
1383    BuiltinIndex = 5;
1384    break;
1385
1386  case Builtin::BI__sync_sub_and_fetch:
1387  case Builtin::BI__sync_sub_and_fetch_1:
1388  case Builtin::BI__sync_sub_and_fetch_2:
1389  case Builtin::BI__sync_sub_and_fetch_4:
1390  case Builtin::BI__sync_sub_and_fetch_8:
1391  case Builtin::BI__sync_sub_and_fetch_16:
1392    BuiltinIndex = 6;
1393    break;
1394
1395  case Builtin::BI__sync_and_and_fetch:
1396  case Builtin::BI__sync_and_and_fetch_1:
1397  case Builtin::BI__sync_and_and_fetch_2:
1398  case Builtin::BI__sync_and_and_fetch_4:
1399  case Builtin::BI__sync_and_and_fetch_8:
1400  case Builtin::BI__sync_and_and_fetch_16:
1401    BuiltinIndex = 7;
1402    break;
1403
1404  case Builtin::BI__sync_or_and_fetch:
1405  case Builtin::BI__sync_or_and_fetch_1:
1406  case Builtin::BI__sync_or_and_fetch_2:
1407  case Builtin::BI__sync_or_and_fetch_4:
1408  case Builtin::BI__sync_or_and_fetch_8:
1409  case Builtin::BI__sync_or_and_fetch_16:
1410    BuiltinIndex = 8;
1411    break;
1412
1413  case Builtin::BI__sync_xor_and_fetch:
1414  case Builtin::BI__sync_xor_and_fetch_1:
1415  case Builtin::BI__sync_xor_and_fetch_2:
1416  case Builtin::BI__sync_xor_and_fetch_4:
1417  case Builtin::BI__sync_xor_and_fetch_8:
1418  case Builtin::BI__sync_xor_and_fetch_16:
1419    BuiltinIndex = 9;
1420    break;
1421
1422  case Builtin::BI__sync_val_compare_and_swap:
1423  case Builtin::BI__sync_val_compare_and_swap_1:
1424  case Builtin::BI__sync_val_compare_and_swap_2:
1425  case Builtin::BI__sync_val_compare_and_swap_4:
1426  case Builtin::BI__sync_val_compare_and_swap_8:
1427  case Builtin::BI__sync_val_compare_and_swap_16:
1428    BuiltinIndex = 10;
1429    NumFixed = 2;
1430    break;
1431
1432  case Builtin::BI__sync_bool_compare_and_swap:
1433  case Builtin::BI__sync_bool_compare_and_swap_1:
1434  case Builtin::BI__sync_bool_compare_and_swap_2:
1435  case Builtin::BI__sync_bool_compare_and_swap_4:
1436  case Builtin::BI__sync_bool_compare_and_swap_8:
1437  case Builtin::BI__sync_bool_compare_and_swap_16:
1438    BuiltinIndex = 11;
1439    NumFixed = 2;
1440    ResultType = Context.BoolTy;
1441    break;
1442
1443  case Builtin::BI__sync_lock_test_and_set:
1444  case Builtin::BI__sync_lock_test_and_set_1:
1445  case Builtin::BI__sync_lock_test_and_set_2:
1446  case Builtin::BI__sync_lock_test_and_set_4:
1447  case Builtin::BI__sync_lock_test_and_set_8:
1448  case Builtin::BI__sync_lock_test_and_set_16:
1449    BuiltinIndex = 12;
1450    break;
1451
1452  case Builtin::BI__sync_lock_release:
1453  case Builtin::BI__sync_lock_release_1:
1454  case Builtin::BI__sync_lock_release_2:
1455  case Builtin::BI__sync_lock_release_4:
1456  case Builtin::BI__sync_lock_release_8:
1457  case Builtin::BI__sync_lock_release_16:
1458    BuiltinIndex = 13;
1459    NumFixed = 0;
1460    ResultType = Context.VoidTy;
1461    break;
1462
1463  case Builtin::BI__sync_swap:
1464  case Builtin::BI__sync_swap_1:
1465  case Builtin::BI__sync_swap_2:
1466  case Builtin::BI__sync_swap_4:
1467  case Builtin::BI__sync_swap_8:
1468  case Builtin::BI__sync_swap_16:
1469    BuiltinIndex = 14;
1470    break;
1471  }
1472
1473  // Now that we know how many fixed arguments we expect, first check that we
1474  // have at least that many.
1475  if (TheCall->getNumArgs() < 1+NumFixed) {
1476    Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1477      << 0 << 1+NumFixed << TheCall->getNumArgs()
1478      << TheCall->getCallee()->getSourceRange();
1479    return ExprError();
1480  }
1481
1482  // Get the decl for the concrete builtin from this, we can tell what the
1483  // concrete integer type we should convert to is.
1484  unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
1485  const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
1486  FunctionDecl *NewBuiltinDecl;
1487  if (NewBuiltinID == BuiltinID)
1488    NewBuiltinDecl = FDecl;
1489  else {
1490    // Perform builtin lookup to avoid redeclaring it.
1491    DeclarationName DN(&Context.Idents.get(NewBuiltinName));
1492    LookupResult Res(*this, DN, DRE->getLocStart(), LookupOrdinaryName);
1493    LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
1494    assert(Res.getFoundDecl());
1495    NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
1496    if (NewBuiltinDecl == 0)
1497      return ExprError();
1498  }
1499
1500  // The first argument --- the pointer --- has a fixed type; we
1501  // deduce the types of the rest of the arguments accordingly.  Walk
1502  // the remaining arguments, converting them to the deduced value type.
1503  for (unsigned i = 0; i != NumFixed; ++i) {
1504    ExprResult Arg = TheCall->getArg(i+1);
1505
1506    // GCC does an implicit conversion to the pointer or integer ValType.  This
1507    // can fail in some cases (1i -> int**), check for this error case now.
1508    // Initialize the argument.
1509    InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1510                                                   ValType, /*consume*/ false);
1511    Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
1512    if (Arg.isInvalid())
1513      return ExprError();
1514
1515    // Okay, we have something that *can* be converted to the right type.  Check
1516    // to see if there is a potentially weird extension going on here.  This can
1517    // happen when you do an atomic operation on something like an char* and
1518    // pass in 42.  The 42 gets converted to char.  This is even more strange
1519    // for things like 45.123 -> char, etc.
1520    // FIXME: Do this check.
1521    TheCall->setArg(i+1, Arg.take());
1522  }
1523
1524  ASTContext& Context = this->getASTContext();
1525
1526  // Create a new DeclRefExpr to refer to the new decl.
1527  DeclRefExpr* NewDRE = DeclRefExpr::Create(
1528      Context,
1529      DRE->getQualifierLoc(),
1530      SourceLocation(),
1531      NewBuiltinDecl,
1532      /*enclosing*/ false,
1533      DRE->getLocation(),
1534      Context.BuiltinFnTy,
1535      DRE->getValueKind());
1536
1537  // Set the callee in the CallExpr.
1538  // FIXME: This loses syntactic information.
1539  QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
1540  ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
1541                                              CK_BuiltinFnToFnPtr);
1542  TheCall->setCallee(PromotedCall.take());
1543
1544  // Change the result type of the call to match the original value type. This
1545  // is arbitrary, but the codegen for these builtins ins design to handle it
1546  // gracefully.
1547  TheCall->setType(ResultType);
1548
1549  return TheCallResult;
1550}
1551
1552/// CheckObjCString - Checks that the argument to the builtin
1553/// CFString constructor is correct
1554/// Note: It might also make sense to do the UTF-16 conversion here (would
1555/// simplify the backend).
1556bool Sema::CheckObjCString(Expr *Arg) {
1557  Arg = Arg->IgnoreParenCasts();
1558  StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
1559
1560  if (!Literal || !Literal->isAscii()) {
1561    Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
1562      << Arg->getSourceRange();
1563    return true;
1564  }
1565
1566  if (Literal->containsNonAsciiOrNull()) {
1567    StringRef String = Literal->getString();
1568    unsigned NumBytes = String.size();
1569    SmallVector<UTF16, 128> ToBuf(NumBytes);
1570    const UTF8 *FromPtr = (const UTF8 *)String.data();
1571    UTF16 *ToPtr = &ToBuf[0];
1572
1573    ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1574                                                 &ToPtr, ToPtr + NumBytes,
1575                                                 strictConversion);
1576    // Check for conversion failure.
1577    if (Result != conversionOK)
1578      Diag(Arg->getLocStart(),
1579           diag::warn_cfstring_truncated) << Arg->getSourceRange();
1580  }
1581  return false;
1582}
1583
1584/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
1585/// Emit an error and return true on failure, return false on success.
1586bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
1587  Expr *Fn = TheCall->getCallee();
1588  if (TheCall->getNumArgs() > 2) {
1589    Diag(TheCall->getArg(2)->getLocStart(),
1590         diag::err_typecheck_call_too_many_args)
1591      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1592      << Fn->getSourceRange()
1593      << SourceRange(TheCall->getArg(2)->getLocStart(),
1594                     (*(TheCall->arg_end()-1))->getLocEnd());
1595    return true;
1596  }
1597
1598  if (TheCall->getNumArgs() < 2) {
1599    return Diag(TheCall->getLocEnd(),
1600      diag::err_typecheck_call_too_few_args_at_least)
1601      << 0 /*function call*/ << 2 << TheCall->getNumArgs();
1602  }
1603
1604  // Type-check the first argument normally.
1605  if (checkBuiltinArgument(*this, TheCall, 0))
1606    return true;
1607
1608  // Determine whether the current function is variadic or not.
1609  BlockScopeInfo *CurBlock = getCurBlock();
1610  bool isVariadic;
1611  if (CurBlock)
1612    isVariadic = CurBlock->TheDecl->isVariadic();
1613  else if (FunctionDecl *FD = getCurFunctionDecl())
1614    isVariadic = FD->isVariadic();
1615  else
1616    isVariadic = getCurMethodDecl()->isVariadic();
1617
1618  if (!isVariadic) {
1619    Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
1620    return true;
1621  }
1622
1623  // Verify that the second argument to the builtin is the last argument of the
1624  // current function or method.
1625  bool SecondArgIsLastNamedArgument = false;
1626  const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
1627
1628  // These are valid if SecondArgIsLastNamedArgument is false after the next
1629  // block.
1630  QualType Type;
1631  SourceLocation ParamLoc;
1632
1633  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
1634    if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
1635      // FIXME: This isn't correct for methods (results in bogus warning).
1636      // Get the last formal in the current function.
1637      const ParmVarDecl *LastArg;
1638      if (CurBlock)
1639        LastArg = *(CurBlock->TheDecl->param_end()-1);
1640      else if (FunctionDecl *FD = getCurFunctionDecl())
1641        LastArg = *(FD->param_end()-1);
1642      else
1643        LastArg = *(getCurMethodDecl()->param_end()-1);
1644      SecondArgIsLastNamedArgument = PV == LastArg;
1645
1646      Type = PV->getType();
1647      ParamLoc = PV->getLocation();
1648    }
1649  }
1650
1651  if (!SecondArgIsLastNamedArgument)
1652    Diag(TheCall->getArg(1)->getLocStart(),
1653         diag::warn_second_parameter_of_va_start_not_last_named_argument);
1654  else if (Type->isReferenceType()) {
1655    Diag(Arg->getLocStart(),
1656         diag::warn_va_start_of_reference_type_is_undefined);
1657    Diag(ParamLoc, diag::note_parameter_type) << Type;
1658  }
1659
1660  TheCall->setType(Context.VoidTy);
1661  return false;
1662}
1663
1664/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1665/// friends.  This is declared to take (...), so we have to check everything.
1666bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1667  if (TheCall->getNumArgs() < 2)
1668    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1669      << 0 << 2 << TheCall->getNumArgs()/*function call*/;
1670  if (TheCall->getNumArgs() > 2)
1671    return Diag(TheCall->getArg(2)->getLocStart(),
1672                diag::err_typecheck_call_too_many_args)
1673      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1674      << SourceRange(TheCall->getArg(2)->getLocStart(),
1675                     (*(TheCall->arg_end()-1))->getLocEnd());
1676
1677  ExprResult OrigArg0 = TheCall->getArg(0);
1678  ExprResult OrigArg1 = TheCall->getArg(1);
1679
1680  // Do standard promotions between the two arguments, returning their common
1681  // type.
1682  QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
1683  if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1684    return true;
1685
1686  // Make sure any conversions are pushed back into the call; this is
1687  // type safe since unordered compare builtins are declared as "_Bool
1688  // foo(...)".
1689  TheCall->setArg(0, OrigArg0.get());
1690  TheCall->setArg(1, OrigArg1.get());
1691
1692  if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
1693    return false;
1694
1695  // If the common type isn't a real floating type, then the arguments were
1696  // invalid for this operation.
1697  if (Res.isNull() || !Res->isRealFloatingType())
1698    return Diag(OrigArg0.get()->getLocStart(),
1699                diag::err_typecheck_call_invalid_ordered_compare)
1700      << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1701      << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
1702
1703  return false;
1704}
1705
1706/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1707/// __builtin_isnan and friends.  This is declared to take (...), so we have
1708/// to check everything. We expect the last argument to be a floating point
1709/// value.
1710bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1711  if (TheCall->getNumArgs() < NumArgs)
1712    return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
1713      << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
1714  if (TheCall->getNumArgs() > NumArgs)
1715    return Diag(TheCall->getArg(NumArgs)->getLocStart(),
1716                diag::err_typecheck_call_too_many_args)
1717      << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1718      << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1719                     (*(TheCall->arg_end()-1))->getLocEnd());
1720
1721  Expr *OrigArg = TheCall->getArg(NumArgs-1);
1722
1723  if (OrigArg->isTypeDependent())
1724    return false;
1725
1726  // This operation requires a non-_Complex floating-point number.
1727  if (!OrigArg->getType()->isRealFloatingType())
1728    return Diag(OrigArg->getLocStart(),
1729                diag::err_typecheck_call_invalid_unary_fp)
1730      << OrigArg->getType() << OrigArg->getSourceRange();
1731
1732  // If this is an implicit conversion from float -> double, remove it.
1733  if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1734    Expr *CastArg = Cast->getSubExpr();
1735    if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1736      assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1737             "promotion from float to double is the only expected cast here");
1738      Cast->setSubExpr(0);
1739      TheCall->setArg(NumArgs-1, CastArg);
1740    }
1741  }
1742
1743  return false;
1744}
1745
1746/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1747// This is declared to take (...), so we have to check everything.
1748ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1749  if (TheCall->getNumArgs() < 2)
1750    return ExprError(Diag(TheCall->getLocEnd(),
1751                          diag::err_typecheck_call_too_few_args_at_least)
1752                     << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1753                     << TheCall->getSourceRange());
1754
1755  // Determine which of the following types of shufflevector we're checking:
1756  // 1) unary, vector mask: (lhs, mask)
1757  // 2) binary, vector mask: (lhs, rhs, mask)
1758  // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1759  QualType resType = TheCall->getArg(0)->getType();
1760  unsigned numElements = 0;
1761
1762  if (!TheCall->getArg(0)->isTypeDependent() &&
1763      !TheCall->getArg(1)->isTypeDependent()) {
1764    QualType LHSType = TheCall->getArg(0)->getType();
1765    QualType RHSType = TheCall->getArg(1)->getType();
1766
1767    if (!LHSType->isVectorType() || !RHSType->isVectorType())
1768      return ExprError(Diag(TheCall->getLocStart(),
1769                            diag::err_shufflevector_non_vector)
1770                       << SourceRange(TheCall->getArg(0)->getLocStart(),
1771                                      TheCall->getArg(1)->getLocEnd()));
1772
1773    numElements = LHSType->getAs<VectorType>()->getNumElements();
1774    unsigned numResElements = TheCall->getNumArgs() - 2;
1775
1776    // Check to see if we have a call with 2 vector arguments, the unary shuffle
1777    // with mask.  If so, verify that RHS is an integer vector type with the
1778    // same number of elts as lhs.
1779    if (TheCall->getNumArgs() == 2) {
1780      if (!RHSType->hasIntegerRepresentation() ||
1781          RHSType->getAs<VectorType>()->getNumElements() != numElements)
1782        return ExprError(Diag(TheCall->getLocStart(),
1783                              diag::err_shufflevector_incompatible_vector)
1784                         << SourceRange(TheCall->getArg(1)->getLocStart(),
1785                                        TheCall->getArg(1)->getLocEnd()));
1786    } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1787      return ExprError(Diag(TheCall->getLocStart(),
1788                            diag::err_shufflevector_incompatible_vector)
1789                       << SourceRange(TheCall->getArg(0)->getLocStart(),
1790                                      TheCall->getArg(1)->getLocEnd()));
1791    } else if (numElements != numResElements) {
1792      QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1793      resType = Context.getVectorType(eltType, numResElements,
1794                                      VectorType::GenericVector);
1795    }
1796  }
1797
1798  for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1799    if (TheCall->getArg(i)->isTypeDependent() ||
1800        TheCall->getArg(i)->isValueDependent())
1801      continue;
1802
1803    llvm::APSInt Result(32);
1804    if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1805      return ExprError(Diag(TheCall->getLocStart(),
1806                            diag::err_shufflevector_nonconstant_argument)
1807                       << TheCall->getArg(i)->getSourceRange());
1808
1809    // Allow -1 which will be translated to undef in the IR.
1810    if (Result.isSigned() && Result.isAllOnesValue())
1811      continue;
1812
1813    if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1814      return ExprError(Diag(TheCall->getLocStart(),
1815                            diag::err_shufflevector_argument_too_large)
1816                       << TheCall->getArg(i)->getSourceRange());
1817  }
1818
1819  SmallVector<Expr*, 32> exprs;
1820
1821  for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1822    exprs.push_back(TheCall->getArg(i));
1823    TheCall->setArg(i, 0);
1824  }
1825
1826  return Owned(new (Context) ShuffleVectorExpr(Context, exprs, resType,
1827                                            TheCall->getCallee()->getLocStart(),
1828                                            TheCall->getRParenLoc()));
1829}
1830
1831/// SemaConvertVectorExpr - Handle __builtin_convertvector
1832ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
1833                                       SourceLocation BuiltinLoc,
1834                                       SourceLocation RParenLoc) {
1835  ExprValueKind VK = VK_RValue;
1836  ExprObjectKind OK = OK_Ordinary;
1837  QualType DstTy = TInfo->getType();
1838  QualType SrcTy = E->getType();
1839
1840  if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
1841    return ExprError(Diag(BuiltinLoc,
1842                          diag::err_convertvector_non_vector)
1843                     << E->getSourceRange());
1844  if (!DstTy->isVectorType() && !DstTy->isDependentType())
1845    return ExprError(Diag(BuiltinLoc,
1846                          diag::err_convertvector_non_vector_type));
1847
1848  if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
1849    unsigned SrcElts = SrcTy->getAs<VectorType>()->getNumElements();
1850    unsigned DstElts = DstTy->getAs<VectorType>()->getNumElements();
1851    if (SrcElts != DstElts)
1852      return ExprError(Diag(BuiltinLoc,
1853                            diag::err_convertvector_incompatible_vector)
1854                       << E->getSourceRange());
1855  }
1856
1857  return Owned(new (Context) ConvertVectorExpr(E, TInfo, DstTy, VK, OK,
1858               BuiltinLoc, RParenLoc));
1859
1860}
1861
1862/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1863// This is declared to take (const void*, ...) and can take two
1864// optional constant int args.
1865bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1866  unsigned NumArgs = TheCall->getNumArgs();
1867
1868  if (NumArgs > 3)
1869    return Diag(TheCall->getLocEnd(),
1870             diag::err_typecheck_call_too_many_args_at_most)
1871             << 0 /*function call*/ << 3 << NumArgs
1872             << TheCall->getSourceRange();
1873
1874  // Argument 0 is checked for us and the remaining arguments must be
1875  // constant integers.
1876  for (unsigned i = 1; i != NumArgs; ++i) {
1877    Expr *Arg = TheCall->getArg(i);
1878
1879    // We can't check the value of a dependent argument.
1880    if (Arg->isTypeDependent() || Arg->isValueDependent())
1881      continue;
1882
1883    llvm::APSInt Result;
1884    if (SemaBuiltinConstantArg(TheCall, i, Result))
1885      return true;
1886
1887    // FIXME: gcc issues a warning and rewrites these to 0. These
1888    // seems especially odd for the third argument since the default
1889    // is 3.
1890    if (i == 1) {
1891      if (Result.getLimitedValue() > 1)
1892        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1893             << "0" << "1" << Arg->getSourceRange();
1894    } else {
1895      if (Result.getLimitedValue() > 3)
1896        return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1897            << "0" << "3" << Arg->getSourceRange();
1898    }
1899  }
1900
1901  return false;
1902}
1903
1904/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1905/// TheCall is a constant expression.
1906bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1907                                  llvm::APSInt &Result) {
1908  Expr *Arg = TheCall->getArg(ArgNum);
1909  DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1910  FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1911
1912  if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1913
1914  if (!Arg->isIntegerConstantExpr(Result, Context))
1915    return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1916                << FDecl->getDeclName() <<  Arg->getSourceRange();
1917
1918  return false;
1919}
1920
1921/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1922/// int type). This simply type checks that type is one of the defined
1923/// constants (0-3).
1924// For compatibility check 0-3, llvm only handles 0 and 2.
1925bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1926  llvm::APSInt Result;
1927
1928  // We can't check the value of a dependent argument.
1929  if (TheCall->getArg(1)->isTypeDependent() ||
1930      TheCall->getArg(1)->isValueDependent())
1931    return false;
1932
1933  // Check constant-ness first.
1934  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1935    return true;
1936
1937  Expr *Arg = TheCall->getArg(1);
1938  if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1939    return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1940             << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1941  }
1942
1943  return false;
1944}
1945
1946/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1947/// This checks that val is a constant 1.
1948bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1949  Expr *Arg = TheCall->getArg(1);
1950  llvm::APSInt Result;
1951
1952  // TODO: This is less than ideal. Overload this to take a value.
1953  if (SemaBuiltinConstantArg(TheCall, 1, Result))
1954    return true;
1955
1956  if (Result != 1)
1957    return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1958             << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1959
1960  return false;
1961}
1962
1963namespace {
1964enum StringLiteralCheckType {
1965  SLCT_NotALiteral,
1966  SLCT_UncheckedLiteral,
1967  SLCT_CheckedLiteral
1968};
1969}
1970
1971// Determine if an expression is a string literal or constant string.
1972// If this function returns false on the arguments to a function expecting a
1973// format string, we will usually need to emit a warning.
1974// True string literals are then checked by CheckFormatString.
1975static StringLiteralCheckType
1976checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
1977                      bool HasVAListArg, unsigned format_idx,
1978                      unsigned firstDataArg, Sema::FormatStringType Type,
1979                      Sema::VariadicCallType CallType, bool InFunctionCall,
1980                      llvm::SmallBitVector &CheckedVarArgs) {
1981 tryAgain:
1982  if (E->isTypeDependent() || E->isValueDependent())
1983    return SLCT_NotALiteral;
1984
1985  E = E->IgnoreParenCasts();
1986
1987  if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
1988    // Technically -Wformat-nonliteral does not warn about this case.
1989    // The behavior of printf and friends in this case is implementation
1990    // dependent.  Ideally if the format string cannot be null then
1991    // it should have a 'nonnull' attribute in the function prototype.
1992    return SLCT_UncheckedLiteral;
1993
1994  switch (E->getStmtClass()) {
1995  case Stmt::BinaryConditionalOperatorClass:
1996  case Stmt::ConditionalOperatorClass: {
1997    // The expression is a literal if both sub-expressions were, and it was
1998    // completely checked only if both sub-expressions were checked.
1999    const AbstractConditionalOperator *C =
2000        cast<AbstractConditionalOperator>(E);
2001    StringLiteralCheckType Left =
2002        checkFormatStringExpr(S, C->getTrueExpr(), Args,
2003                              HasVAListArg, format_idx, firstDataArg,
2004                              Type, CallType, InFunctionCall, CheckedVarArgs);
2005    if (Left == SLCT_NotALiteral)
2006      return SLCT_NotALiteral;
2007    StringLiteralCheckType Right =
2008        checkFormatStringExpr(S, C->getFalseExpr(), Args,
2009                              HasVAListArg, format_idx, firstDataArg,
2010                              Type, CallType, InFunctionCall, CheckedVarArgs);
2011    return Left < Right ? Left : Right;
2012  }
2013
2014  case Stmt::ImplicitCastExprClass: {
2015    E = cast<ImplicitCastExpr>(E)->getSubExpr();
2016    goto tryAgain;
2017  }
2018
2019  case Stmt::OpaqueValueExprClass:
2020    if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2021      E = src;
2022      goto tryAgain;
2023    }
2024    return SLCT_NotALiteral;
2025
2026  case Stmt::PredefinedExprClass:
2027    // While __func__, etc., are technically not string literals, they
2028    // cannot contain format specifiers and thus are not a security
2029    // liability.
2030    return SLCT_UncheckedLiteral;
2031
2032  case Stmt::DeclRefExprClass: {
2033    const DeclRefExpr *DR = cast<DeclRefExpr>(E);
2034
2035    // As an exception, do not flag errors for variables binding to
2036    // const string literals.
2037    if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
2038      bool isConstant = false;
2039      QualType T = DR->getType();
2040
2041      if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
2042        isConstant = AT->getElementType().isConstant(S.Context);
2043      } else if (const PointerType *PT = T->getAs<PointerType>()) {
2044        isConstant = T.isConstant(S.Context) &&
2045                     PT->getPointeeType().isConstant(S.Context);
2046      } else if (T->isObjCObjectPointerType()) {
2047        // In ObjC, there is usually no "const ObjectPointer" type,
2048        // so don't check if the pointee type is constant.
2049        isConstant = T.isConstant(S.Context);
2050      }
2051
2052      if (isConstant) {
2053        if (const Expr *Init = VD->getAnyInitializer()) {
2054          // Look through initializers like const char c[] = { "foo" }
2055          if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2056            if (InitList->isStringLiteralInit())
2057              Init = InitList->getInit(0)->IgnoreParenImpCasts();
2058          }
2059          return checkFormatStringExpr(S, Init, Args,
2060                                       HasVAListArg, format_idx,
2061                                       firstDataArg, Type, CallType,
2062                                       /*InFunctionCall*/false, CheckedVarArgs);
2063        }
2064      }
2065
2066      // For vprintf* functions (i.e., HasVAListArg==true), we add a
2067      // special check to see if the format string is a function parameter
2068      // of the function calling the printf function.  If the function
2069      // has an attribute indicating it is a printf-like function, then we
2070      // should suppress warnings concerning non-literals being used in a call
2071      // to a vprintf function.  For example:
2072      //
2073      // void
2074      // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
2075      //      va_list ap;
2076      //      va_start(ap, fmt);
2077      //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
2078      //      ...
2079      // }
2080      if (HasVAListArg) {
2081        if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2082          if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2083            int PVIndex = PV->getFunctionScopeIndex() + 1;
2084            for (specific_attr_iterator<FormatAttr>
2085                 i = ND->specific_attr_begin<FormatAttr>(),
2086                 e = ND->specific_attr_end<FormatAttr>(); i != e ; ++i) {
2087              FormatAttr *PVFormat = *i;
2088              // adjust for implicit parameter
2089              if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2090                if (MD->isInstance())
2091                  ++PVIndex;
2092              // We also check if the formats are compatible.
2093              // We can't pass a 'scanf' string to a 'printf' function.
2094              if (PVIndex == PVFormat->getFormatIdx() &&
2095                  Type == S.GetFormatStringType(PVFormat))
2096                return SLCT_UncheckedLiteral;
2097            }
2098          }
2099        }
2100      }
2101    }
2102
2103    return SLCT_NotALiteral;
2104  }
2105
2106  case Stmt::CallExprClass:
2107  case Stmt::CXXMemberCallExprClass: {
2108    const CallExpr *CE = cast<CallExpr>(E);
2109    if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
2110      if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2111        unsigned ArgIndex = FA->getFormatIdx();
2112        if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
2113          if (MD->isInstance())
2114            --ArgIndex;
2115        const Expr *Arg = CE->getArg(ArgIndex - 1);
2116
2117        return checkFormatStringExpr(S, Arg, Args,
2118                                     HasVAListArg, format_idx, firstDataArg,
2119                                     Type, CallType, InFunctionCall,
2120                                     CheckedVarArgs);
2121      } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2122        unsigned BuiltinID = FD->getBuiltinID();
2123        if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2124            BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
2125          const Expr *Arg = CE->getArg(0);
2126          return checkFormatStringExpr(S, Arg, Args,
2127                                       HasVAListArg, format_idx,
2128                                       firstDataArg, Type, CallType,
2129                                       InFunctionCall, CheckedVarArgs);
2130        }
2131      }
2132    }
2133
2134    return SLCT_NotALiteral;
2135  }
2136
2137  case Stmt::ObjCMessageExprClass: {
2138    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(E);
2139    if (const ObjCMethodDecl *MDecl = ME->getMethodDecl()) {
2140      if (const NamedDecl *ND = dyn_cast<NamedDecl>(MDecl)) {
2141        if (const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2142          unsigned ArgIndex = FA->getFormatIdx();
2143          if (ArgIndex <= ME->getNumArgs()) {
2144            const Expr *Arg = ME->getArg(ArgIndex-1);
2145            return checkFormatStringExpr(S, Arg, Args,
2146                                         HasVAListArg, format_idx,
2147                                         firstDataArg, Type, CallType,
2148                                         InFunctionCall, CheckedVarArgs);
2149          }
2150        }
2151      }
2152    }
2153
2154    return SLCT_NotALiteral;
2155  }
2156
2157  case Stmt::ObjCStringLiteralClass:
2158  case Stmt::StringLiteralClass: {
2159    const StringLiteral *StrE = NULL;
2160
2161    if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
2162      StrE = ObjCFExpr->getString();
2163    else
2164      StrE = cast<StringLiteral>(E);
2165
2166    if (StrE) {
2167      S.CheckFormatString(StrE, E, Args, HasVAListArg, format_idx, firstDataArg,
2168                          Type, InFunctionCall, CallType, CheckedVarArgs);
2169      return SLCT_CheckedLiteral;
2170    }
2171
2172    return SLCT_NotALiteral;
2173  }
2174
2175  default:
2176    return SLCT_NotALiteral;
2177  }
2178}
2179
2180void
2181Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
2182                            const Expr * const *ExprArgs,
2183                            SourceLocation CallSiteLoc) {
2184  for (NonNullAttr::args_iterator i = NonNull->args_begin(),
2185                                  e = NonNull->args_end();
2186       i != e; ++i) {
2187    const Expr *ArgExpr = ExprArgs[*i];
2188
2189    // As a special case, transparent unions initialized with zero are
2190    // considered null for the purposes of the nonnull attribute.
2191    if (const RecordType *UT = ArgExpr->getType()->getAsUnionType()) {
2192      if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2193        if (const CompoundLiteralExpr *CLE =
2194            dyn_cast<CompoundLiteralExpr>(ArgExpr))
2195          if (const InitListExpr *ILE =
2196              dyn_cast<InitListExpr>(CLE->getInitializer()))
2197            ArgExpr = ILE->getInit(0);
2198    }
2199
2200    bool Result;
2201    if (ArgExpr->EvaluateAsBooleanCondition(Result, Context) && !Result)
2202      Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
2203  }
2204}
2205
2206Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
2207  return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
2208  .Case("scanf", FST_Scanf)
2209  .Cases("printf", "printf0", FST_Printf)
2210  .Cases("NSString", "CFString", FST_NSString)
2211  .Case("strftime", FST_Strftime)
2212  .Case("strfmon", FST_Strfmon)
2213  .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
2214  .Default(FST_Unknown);
2215}
2216
2217/// CheckFormatArguments - Check calls to printf and scanf (and similar
2218/// functions) for correct use of format strings.
2219/// Returns true if a format string has been fully checked.
2220bool Sema::CheckFormatArguments(const FormatAttr *Format,
2221                                ArrayRef<const Expr *> Args,
2222                                bool IsCXXMember,
2223                                VariadicCallType CallType,
2224                                SourceLocation Loc, SourceRange Range,
2225                                llvm::SmallBitVector &CheckedVarArgs) {
2226  FormatStringInfo FSI;
2227  if (getFormatStringInfo(Format, IsCXXMember, &FSI))
2228    return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
2229                                FSI.FirstDataArg, GetFormatStringType(Format),
2230                                CallType, Loc, Range, CheckedVarArgs);
2231  return false;
2232}
2233
2234bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
2235                                bool HasVAListArg, unsigned format_idx,
2236                                unsigned firstDataArg, FormatStringType Type,
2237                                VariadicCallType CallType,
2238                                SourceLocation Loc, SourceRange Range,
2239                                llvm::SmallBitVector &CheckedVarArgs) {
2240  // CHECK: printf/scanf-like function is called with no format string.
2241  if (format_idx >= Args.size()) {
2242    Diag(Loc, diag::warn_missing_format_string) << Range;
2243    return false;
2244  }
2245
2246  const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
2247
2248  // CHECK: format string is not a string literal.
2249  //
2250  // Dynamically generated format strings are difficult to
2251  // automatically vet at compile time.  Requiring that format strings
2252  // are string literals: (1) permits the checking of format strings by
2253  // the compiler and thereby (2) can practically remove the source of
2254  // many format string exploits.
2255
2256  // Format string can be either ObjC string (e.g. @"%d") or
2257  // C string (e.g. "%d")
2258  // ObjC string uses the same format specifiers as C string, so we can use
2259  // the same format string checking logic for both ObjC and C strings.
2260  StringLiteralCheckType CT =
2261      checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
2262                            format_idx, firstDataArg, Type, CallType,
2263                            /*IsFunctionCall*/true, CheckedVarArgs);
2264  if (CT != SLCT_NotALiteral)
2265    // Literal format string found, check done!
2266    return CT == SLCT_CheckedLiteral;
2267
2268  // Strftime is particular as it always uses a single 'time' argument,
2269  // so it is safe to pass a non-literal string.
2270  if (Type == FST_Strftime)
2271    return false;
2272
2273  // Do not emit diag when the string param is a macro expansion and the
2274  // format is either NSString or CFString. This is a hack to prevent
2275  // diag when using the NSLocalizedString and CFCopyLocalizedString macros
2276  // which are usually used in place of NS and CF string literals.
2277  if (Type == FST_NSString &&
2278      SourceMgr.isInSystemMacro(Args[format_idx]->getLocStart()))
2279    return false;
2280
2281  // If there are no arguments specified, warn with -Wformat-security, otherwise
2282  // warn only with -Wformat-nonliteral.
2283  if (Args.size() == firstDataArg)
2284    Diag(Args[format_idx]->getLocStart(),
2285         diag::warn_format_nonliteral_noargs)
2286      << OrigFormatExpr->getSourceRange();
2287  else
2288    Diag(Args[format_idx]->getLocStart(),
2289         diag::warn_format_nonliteral)
2290           << OrigFormatExpr->getSourceRange();
2291  return false;
2292}
2293
2294namespace {
2295class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
2296protected:
2297  Sema &S;
2298  const StringLiteral *FExpr;
2299  const Expr *OrigFormatExpr;
2300  const unsigned FirstDataArg;
2301  const unsigned NumDataArgs;
2302  const char *Beg; // Start of format string.
2303  const bool HasVAListArg;
2304  ArrayRef<const Expr *> Args;
2305  unsigned FormatIdx;
2306  llvm::SmallBitVector CoveredArgs;
2307  bool usesPositionalArgs;
2308  bool atFirstArg;
2309  bool inFunctionCall;
2310  Sema::VariadicCallType CallType;
2311  llvm::SmallBitVector &CheckedVarArgs;
2312public:
2313  CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
2314                     const Expr *origFormatExpr, unsigned firstDataArg,
2315                     unsigned numDataArgs, const char *beg, bool hasVAListArg,
2316                     ArrayRef<const Expr *> Args,
2317                     unsigned formatIdx, bool inFunctionCall,
2318                     Sema::VariadicCallType callType,
2319                     llvm::SmallBitVector &CheckedVarArgs)
2320    : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
2321      FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
2322      Beg(beg), HasVAListArg(hasVAListArg),
2323      Args(Args), FormatIdx(formatIdx),
2324      usesPositionalArgs(false), atFirstArg(true),
2325      inFunctionCall(inFunctionCall), CallType(callType),
2326      CheckedVarArgs(CheckedVarArgs) {
2327    CoveredArgs.resize(numDataArgs);
2328    CoveredArgs.reset();
2329  }
2330
2331  void DoneProcessing();
2332
2333  void HandleIncompleteSpecifier(const char *startSpecifier,
2334                                 unsigned specifierLen);
2335
2336  void HandleInvalidLengthModifier(
2337      const analyze_format_string::FormatSpecifier &FS,
2338      const analyze_format_string::ConversionSpecifier &CS,
2339      const char *startSpecifier, unsigned specifierLen, unsigned DiagID);
2340
2341  void HandleNonStandardLengthModifier(
2342      const analyze_format_string::FormatSpecifier &FS,
2343      const char *startSpecifier, unsigned specifierLen);
2344
2345  void HandleNonStandardConversionSpecifier(
2346      const analyze_format_string::ConversionSpecifier &CS,
2347      const char *startSpecifier, unsigned specifierLen);
2348
2349  virtual void HandlePosition(const char *startPos, unsigned posLen);
2350
2351  virtual void HandleInvalidPosition(const char *startSpecifier,
2352                                     unsigned specifierLen,
2353                                     analyze_format_string::PositionContext p);
2354
2355  virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
2356
2357  void HandleNullChar(const char *nullCharacter);
2358
2359  template <typename Range>
2360  static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
2361                                   const Expr *ArgumentExpr,
2362                                   PartialDiagnostic PDiag,
2363                                   SourceLocation StringLoc,
2364                                   bool IsStringLocation, Range StringRange,
2365                                   ArrayRef<FixItHint> Fixit = None);
2366
2367protected:
2368  bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
2369                                        const char *startSpec,
2370                                        unsigned specifierLen,
2371                                        const char *csStart, unsigned csLen);
2372
2373  void HandlePositionalNonpositionalArgs(SourceLocation Loc,
2374                                         const char *startSpec,
2375                                         unsigned specifierLen);
2376
2377  SourceRange getFormatStringRange();
2378  CharSourceRange getSpecifierRange(const char *startSpecifier,
2379                                    unsigned specifierLen);
2380  SourceLocation getLocationOfByte(const char *x);
2381
2382  const Expr *getDataArg(unsigned i) const;
2383
2384  bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
2385                    const analyze_format_string::ConversionSpecifier &CS,
2386                    const char *startSpecifier, unsigned specifierLen,
2387                    unsigned argIndex);
2388
2389  template <typename Range>
2390  void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
2391                            bool IsStringLocation, Range StringRange,
2392                            ArrayRef<FixItHint> Fixit = None);
2393
2394  void CheckPositionalAndNonpositionalArgs(
2395      const analyze_format_string::FormatSpecifier *FS);
2396};
2397}
2398
2399SourceRange CheckFormatHandler::getFormatStringRange() {
2400  return OrigFormatExpr->getSourceRange();
2401}
2402
2403CharSourceRange CheckFormatHandler::
2404getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
2405  SourceLocation Start = getLocationOfByte(startSpecifier);
2406  SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
2407
2408  // Advance the end SourceLocation by one due to half-open ranges.
2409  End = End.getLocWithOffset(1);
2410
2411  return CharSourceRange::getCharRange(Start, End);
2412}
2413
2414SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
2415  return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
2416}
2417
2418void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
2419                                                   unsigned specifierLen){
2420  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
2421                       getLocationOfByte(startSpecifier),
2422                       /*IsStringLocation*/true,
2423                       getSpecifierRange(startSpecifier, specifierLen));
2424}
2425
2426void CheckFormatHandler::HandleInvalidLengthModifier(
2427    const analyze_format_string::FormatSpecifier &FS,
2428    const analyze_format_string::ConversionSpecifier &CS,
2429    const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
2430  using namespace analyze_format_string;
2431
2432  const LengthModifier &LM = FS.getLengthModifier();
2433  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2434
2435  // See if we know how to fix this length modifier.
2436  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2437  if (FixedLM) {
2438    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2439                         getLocationOfByte(LM.getStart()),
2440                         /*IsStringLocation*/true,
2441                         getSpecifierRange(startSpecifier, specifierLen));
2442
2443    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2444      << FixedLM->toString()
2445      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2446
2447  } else {
2448    FixItHint Hint;
2449    if (DiagID == diag::warn_format_nonsensical_length)
2450      Hint = FixItHint::CreateRemoval(LMRange);
2451
2452    EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
2453                         getLocationOfByte(LM.getStart()),
2454                         /*IsStringLocation*/true,
2455                         getSpecifierRange(startSpecifier, specifierLen),
2456                         Hint);
2457  }
2458}
2459
2460void CheckFormatHandler::HandleNonStandardLengthModifier(
2461    const analyze_format_string::FormatSpecifier &FS,
2462    const char *startSpecifier, unsigned specifierLen) {
2463  using namespace analyze_format_string;
2464
2465  const LengthModifier &LM = FS.getLengthModifier();
2466  CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
2467
2468  // See if we know how to fix this length modifier.
2469  Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
2470  if (FixedLM) {
2471    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2472                           << LM.toString() << 0,
2473                         getLocationOfByte(LM.getStart()),
2474                         /*IsStringLocation*/true,
2475                         getSpecifierRange(startSpecifier, specifierLen));
2476
2477    S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
2478      << FixedLM->toString()
2479      << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
2480
2481  } else {
2482    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2483                           << LM.toString() << 0,
2484                         getLocationOfByte(LM.getStart()),
2485                         /*IsStringLocation*/true,
2486                         getSpecifierRange(startSpecifier, specifierLen));
2487  }
2488}
2489
2490void CheckFormatHandler::HandleNonStandardConversionSpecifier(
2491    const analyze_format_string::ConversionSpecifier &CS,
2492    const char *startSpecifier, unsigned specifierLen) {
2493  using namespace analyze_format_string;
2494
2495  // See if we know how to fix this conversion specifier.
2496  Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
2497  if (FixedCS) {
2498    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2499                          << CS.toString() << /*conversion specifier*/1,
2500                         getLocationOfByte(CS.getStart()),
2501                         /*IsStringLocation*/true,
2502                         getSpecifierRange(startSpecifier, specifierLen));
2503
2504    CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
2505    S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
2506      << FixedCS->toString()
2507      << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
2508  } else {
2509    EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
2510                          << CS.toString() << /*conversion specifier*/1,
2511                         getLocationOfByte(CS.getStart()),
2512                         /*IsStringLocation*/true,
2513                         getSpecifierRange(startSpecifier, specifierLen));
2514  }
2515}
2516
2517void CheckFormatHandler::HandlePosition(const char *startPos,
2518                                        unsigned posLen) {
2519  EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
2520                               getLocationOfByte(startPos),
2521                               /*IsStringLocation*/true,
2522                               getSpecifierRange(startPos, posLen));
2523}
2524
2525void
2526CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
2527                                     analyze_format_string::PositionContext p) {
2528  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
2529                         << (unsigned) p,
2530                       getLocationOfByte(startPos), /*IsStringLocation*/true,
2531                       getSpecifierRange(startPos, posLen));
2532}
2533
2534void CheckFormatHandler::HandleZeroPosition(const char *startPos,
2535                                            unsigned posLen) {
2536  EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
2537                               getLocationOfByte(startPos),
2538                               /*IsStringLocation*/true,
2539                               getSpecifierRange(startPos, posLen));
2540}
2541
2542void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
2543  if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
2544    // The presence of a null character is likely an error.
2545    EmitFormatDiagnostic(
2546      S.PDiag(diag::warn_printf_format_string_contains_null_char),
2547      getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
2548      getFormatStringRange());
2549  }
2550}
2551
2552// Note that this may return NULL if there was an error parsing or building
2553// one of the argument expressions.
2554const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
2555  return Args[FirstDataArg + i];
2556}
2557
2558void CheckFormatHandler::DoneProcessing() {
2559    // Does the number of data arguments exceed the number of
2560    // format conversions in the format string?
2561  if (!HasVAListArg) {
2562      // Find any arguments that weren't covered.
2563    CoveredArgs.flip();
2564    signed notCoveredArg = CoveredArgs.find_first();
2565    if (notCoveredArg >= 0) {
2566      assert((unsigned)notCoveredArg < NumDataArgs);
2567      if (const Expr *E = getDataArg((unsigned) notCoveredArg)) {
2568        SourceLocation Loc = E->getLocStart();
2569        if (!S.getSourceManager().isInSystemMacro(Loc)) {
2570          EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
2571                               Loc, /*IsStringLocation*/false,
2572                               getFormatStringRange());
2573        }
2574      }
2575    }
2576  }
2577}
2578
2579bool
2580CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
2581                                                     SourceLocation Loc,
2582                                                     const char *startSpec,
2583                                                     unsigned specifierLen,
2584                                                     const char *csStart,
2585                                                     unsigned csLen) {
2586
2587  bool keepGoing = true;
2588  if (argIndex < NumDataArgs) {
2589    // Consider the argument coverered, even though the specifier doesn't
2590    // make sense.
2591    CoveredArgs.set(argIndex);
2592  }
2593  else {
2594    // If argIndex exceeds the number of data arguments we
2595    // don't issue a warning because that is just a cascade of warnings (and
2596    // they may have intended '%%' anyway). We don't want to continue processing
2597    // the format string after this point, however, as we will like just get
2598    // gibberish when trying to match arguments.
2599    keepGoing = false;
2600  }
2601
2602  EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
2603                         << StringRef(csStart, csLen),
2604                       Loc, /*IsStringLocation*/true,
2605                       getSpecifierRange(startSpec, specifierLen));
2606
2607  return keepGoing;
2608}
2609
2610void
2611CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
2612                                                      const char *startSpec,
2613                                                      unsigned specifierLen) {
2614  EmitFormatDiagnostic(
2615    S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
2616    Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
2617}
2618
2619bool
2620CheckFormatHandler::CheckNumArgs(
2621  const analyze_format_string::FormatSpecifier &FS,
2622  const analyze_format_string::ConversionSpecifier &CS,
2623  const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
2624
2625  if (argIndex >= NumDataArgs) {
2626    PartialDiagnostic PDiag = FS.usesPositionalArg()
2627      ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
2628           << (argIndex+1) << NumDataArgs)
2629      : S.PDiag(diag::warn_printf_insufficient_data_args);
2630    EmitFormatDiagnostic(
2631      PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
2632      getSpecifierRange(startSpecifier, specifierLen));
2633    return false;
2634  }
2635  return true;
2636}
2637
2638template<typename Range>
2639void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
2640                                              SourceLocation Loc,
2641                                              bool IsStringLocation,
2642                                              Range StringRange,
2643                                              ArrayRef<FixItHint> FixIt) {
2644  EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
2645                       Loc, IsStringLocation, StringRange, FixIt);
2646}
2647
2648/// \brief If the format string is not within the funcion call, emit a note
2649/// so that the function call and string are in diagnostic messages.
2650///
2651/// \param InFunctionCall if true, the format string is within the function
2652/// call and only one diagnostic message will be produced.  Otherwise, an
2653/// extra note will be emitted pointing to location of the format string.
2654///
2655/// \param ArgumentExpr the expression that is passed as the format string
2656/// argument in the function call.  Used for getting locations when two
2657/// diagnostics are emitted.
2658///
2659/// \param PDiag the callee should already have provided any strings for the
2660/// diagnostic message.  This function only adds locations and fixits
2661/// to diagnostics.
2662///
2663/// \param Loc primary location for diagnostic.  If two diagnostics are
2664/// required, one will be at Loc and a new SourceLocation will be created for
2665/// the other one.
2666///
2667/// \param IsStringLocation if true, Loc points to the format string should be
2668/// used for the note.  Otherwise, Loc points to the argument list and will
2669/// be used with PDiag.
2670///
2671/// \param StringRange some or all of the string to highlight.  This is
2672/// templated so it can accept either a CharSourceRange or a SourceRange.
2673///
2674/// \param FixIt optional fix it hint for the format string.
2675template<typename Range>
2676void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
2677                                              const Expr *ArgumentExpr,
2678                                              PartialDiagnostic PDiag,
2679                                              SourceLocation Loc,
2680                                              bool IsStringLocation,
2681                                              Range StringRange,
2682                                              ArrayRef<FixItHint> FixIt) {
2683  if (InFunctionCall) {
2684    const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
2685    D << StringRange;
2686    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2687         I != E; ++I) {
2688      D << *I;
2689    }
2690  } else {
2691    S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
2692      << ArgumentExpr->getSourceRange();
2693
2694    const Sema::SemaDiagnosticBuilder &Note =
2695      S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
2696             diag::note_format_string_defined);
2697
2698    Note << StringRange;
2699    for (ArrayRef<FixItHint>::iterator I = FixIt.begin(), E = FixIt.end();
2700         I != E; ++I) {
2701      Note << *I;
2702    }
2703  }
2704}
2705
2706//===--- CHECK: Printf format string checking ------------------------------===//
2707
2708namespace {
2709class CheckPrintfHandler : public CheckFormatHandler {
2710  bool ObjCContext;
2711public:
2712  CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
2713                     const Expr *origFormatExpr, unsigned firstDataArg,
2714                     unsigned numDataArgs, bool isObjC,
2715                     const char *beg, bool hasVAListArg,
2716                     ArrayRef<const Expr *> Args,
2717                     unsigned formatIdx, bool inFunctionCall,
2718                     Sema::VariadicCallType CallType,
2719                     llvm::SmallBitVector &CheckedVarArgs)
2720    : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2721                         numDataArgs, beg, hasVAListArg, Args,
2722                         formatIdx, inFunctionCall, CallType, CheckedVarArgs),
2723      ObjCContext(isObjC)
2724  {}
2725
2726
2727  bool HandleInvalidPrintfConversionSpecifier(
2728                                      const analyze_printf::PrintfSpecifier &FS,
2729                                      const char *startSpecifier,
2730                                      unsigned specifierLen);
2731
2732  bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
2733                             const char *startSpecifier,
2734                             unsigned specifierLen);
2735  bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
2736                       const char *StartSpecifier,
2737                       unsigned SpecifierLen,
2738                       const Expr *E);
2739
2740  bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
2741                    const char *startSpecifier, unsigned specifierLen);
2742  void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
2743                           const analyze_printf::OptionalAmount &Amt,
2744                           unsigned type,
2745                           const char *startSpecifier, unsigned specifierLen);
2746  void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2747                  const analyze_printf::OptionalFlag &flag,
2748                  const char *startSpecifier, unsigned specifierLen);
2749  void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
2750                         const analyze_printf::OptionalFlag &ignoredFlag,
2751                         const analyze_printf::OptionalFlag &flag,
2752                         const char *startSpecifier, unsigned specifierLen);
2753  bool checkForCStrMembers(const analyze_printf::ArgType &AT,
2754                           const Expr *E, const CharSourceRange &CSR);
2755
2756};
2757}
2758
2759bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
2760                                      const analyze_printf::PrintfSpecifier &FS,
2761                                      const char *startSpecifier,
2762                                      unsigned specifierLen) {
2763  const analyze_printf::PrintfConversionSpecifier &CS =
2764    FS.getConversionSpecifier();
2765
2766  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2767                                          getLocationOfByte(CS.getStart()),
2768                                          startSpecifier, specifierLen,
2769                                          CS.getStart(), CS.getLength());
2770}
2771
2772bool CheckPrintfHandler::HandleAmount(
2773                               const analyze_format_string::OptionalAmount &Amt,
2774                               unsigned k, const char *startSpecifier,
2775                               unsigned specifierLen) {
2776
2777  if (Amt.hasDataArgument()) {
2778    if (!HasVAListArg) {
2779      unsigned argIndex = Amt.getArgIndex();
2780      if (argIndex >= NumDataArgs) {
2781        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
2782                               << k,
2783                             getLocationOfByte(Amt.getStart()),
2784                             /*IsStringLocation*/true,
2785                             getSpecifierRange(startSpecifier, specifierLen));
2786        // Don't do any more checking.  We will just emit
2787        // spurious errors.
2788        return false;
2789      }
2790
2791      // Type check the data argument.  It should be an 'int'.
2792      // Although not in conformance with C99, we also allow the argument to be
2793      // an 'unsigned int' as that is a reasonably safe case.  GCC also
2794      // doesn't emit a warning for that case.
2795      CoveredArgs.set(argIndex);
2796      const Expr *Arg = getDataArg(argIndex);
2797      if (!Arg)
2798        return false;
2799
2800      QualType T = Arg->getType();
2801
2802      const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
2803      assert(AT.isValid());
2804
2805      if (!AT.matchesType(S.Context, T)) {
2806        EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
2807                               << k << AT.getRepresentativeTypeName(S.Context)
2808                               << T << Arg->getSourceRange(),
2809                             getLocationOfByte(Amt.getStart()),
2810                             /*IsStringLocation*/true,
2811                             getSpecifierRange(startSpecifier, specifierLen));
2812        // Don't do any more checking.  We will just emit
2813        // spurious errors.
2814        return false;
2815      }
2816    }
2817  }
2818  return true;
2819}
2820
2821void CheckPrintfHandler::HandleInvalidAmount(
2822                                      const analyze_printf::PrintfSpecifier &FS,
2823                                      const analyze_printf::OptionalAmount &Amt,
2824                                      unsigned type,
2825                                      const char *startSpecifier,
2826                                      unsigned specifierLen) {
2827  const analyze_printf::PrintfConversionSpecifier &CS =
2828    FS.getConversionSpecifier();
2829
2830  FixItHint fixit =
2831    Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
2832      ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
2833                                 Amt.getConstantLength()))
2834      : FixItHint();
2835
2836  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
2837                         << type << CS.toString(),
2838                       getLocationOfByte(Amt.getStart()),
2839                       /*IsStringLocation*/true,
2840                       getSpecifierRange(startSpecifier, specifierLen),
2841                       fixit);
2842}
2843
2844void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
2845                                    const analyze_printf::OptionalFlag &flag,
2846                                    const char *startSpecifier,
2847                                    unsigned specifierLen) {
2848  // Warn about pointless flag with a fixit removal.
2849  const analyze_printf::PrintfConversionSpecifier &CS =
2850    FS.getConversionSpecifier();
2851  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
2852                         << flag.toString() << CS.toString(),
2853                       getLocationOfByte(flag.getPosition()),
2854                       /*IsStringLocation*/true,
2855                       getSpecifierRange(startSpecifier, specifierLen),
2856                       FixItHint::CreateRemoval(
2857                         getSpecifierRange(flag.getPosition(), 1)));
2858}
2859
2860void CheckPrintfHandler::HandleIgnoredFlag(
2861                                const analyze_printf::PrintfSpecifier &FS,
2862                                const analyze_printf::OptionalFlag &ignoredFlag,
2863                                const analyze_printf::OptionalFlag &flag,
2864                                const char *startSpecifier,
2865                                unsigned specifierLen) {
2866  // Warn about ignored flag with a fixit removal.
2867  EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
2868                         << ignoredFlag.toString() << flag.toString(),
2869                       getLocationOfByte(ignoredFlag.getPosition()),
2870                       /*IsStringLocation*/true,
2871                       getSpecifierRange(startSpecifier, specifierLen),
2872                       FixItHint::CreateRemoval(
2873                         getSpecifierRange(ignoredFlag.getPosition(), 1)));
2874}
2875
2876// Determines if the specified is a C++ class or struct containing
2877// a member with the specified name and kind (e.g. a CXXMethodDecl named
2878// "c_str()").
2879template<typename MemberKind>
2880static llvm::SmallPtrSet<MemberKind*, 1>
2881CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
2882  const RecordType *RT = Ty->getAs<RecordType>();
2883  llvm::SmallPtrSet<MemberKind*, 1> Results;
2884
2885  if (!RT)
2886    return Results;
2887  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
2888  if (!RD)
2889    return Results;
2890
2891  LookupResult R(S, &S.PP.getIdentifierTable().get(Name), SourceLocation(),
2892                 Sema::LookupMemberName);
2893
2894  // We just need to include all members of the right kind turned up by the
2895  // filter, at this point.
2896  if (S.LookupQualifiedName(R, RT->getDecl()))
2897    for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2898      NamedDecl *decl = (*I)->getUnderlyingDecl();
2899      if (MemberKind *FK = dyn_cast<MemberKind>(decl))
2900        Results.insert(FK);
2901    }
2902  return Results;
2903}
2904
2905// Check if a (w)string was passed when a (w)char* was needed, and offer a
2906// better diagnostic if so. AT is assumed to be valid.
2907// Returns true when a c_str() conversion method is found.
2908bool CheckPrintfHandler::checkForCStrMembers(
2909    const analyze_printf::ArgType &AT, const Expr *E,
2910    const CharSourceRange &CSR) {
2911  typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
2912
2913  MethodSet Results =
2914      CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
2915
2916  for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
2917       MI != ME; ++MI) {
2918    const CXXMethodDecl *Method = *MI;
2919    if (Method->getNumParams() == 0 &&
2920          AT.matchesType(S.Context, Method->getResultType())) {
2921      // FIXME: Suggest parens if the expression needs them.
2922      SourceLocation EndLoc =
2923          S.getPreprocessor().getLocForEndOfToken(E->getLocEnd());
2924      S.Diag(E->getLocStart(), diag::note_printf_c_str)
2925          << "c_str()"
2926          << FixItHint::CreateInsertion(EndLoc, ".c_str()");
2927      return true;
2928    }
2929  }
2930
2931  return false;
2932}
2933
2934bool
2935CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
2936                                            &FS,
2937                                          const char *startSpecifier,
2938                                          unsigned specifierLen) {
2939
2940  using namespace analyze_format_string;
2941  using namespace analyze_printf;
2942  const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
2943
2944  if (FS.consumesDataArgument()) {
2945    if (atFirstArg) {
2946        atFirstArg = false;
2947        usesPositionalArgs = FS.usesPositionalArg();
2948    }
2949    else if (usesPositionalArgs != FS.usesPositionalArg()) {
2950      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2951                                        startSpecifier, specifierLen);
2952      return false;
2953    }
2954  }
2955
2956  // First check if the field width, precision, and conversion specifier
2957  // have matching data arguments.
2958  if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
2959                    startSpecifier, specifierLen)) {
2960    return false;
2961  }
2962
2963  if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
2964                    startSpecifier, specifierLen)) {
2965    return false;
2966  }
2967
2968  if (!CS.consumesDataArgument()) {
2969    // FIXME: Technically specifying a precision or field width here
2970    // makes no sense.  Worth issuing a warning at some point.
2971    return true;
2972  }
2973
2974  // Consume the argument.
2975  unsigned argIndex = FS.getArgIndex();
2976  if (argIndex < NumDataArgs) {
2977    // The check to see if the argIndex is valid will come later.
2978    // We set the bit here because we may exit early from this
2979    // function if we encounter some other error.
2980    CoveredArgs.set(argIndex);
2981  }
2982
2983  // Check for using an Objective-C specific conversion specifier
2984  // in a non-ObjC literal.
2985  if (!ObjCContext && CS.isObjCArg()) {
2986    return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
2987                                                  specifierLen);
2988  }
2989
2990  // Check for invalid use of field width
2991  if (!FS.hasValidFieldWidth()) {
2992    HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
2993        startSpecifier, specifierLen);
2994  }
2995
2996  // Check for invalid use of precision
2997  if (!FS.hasValidPrecision()) {
2998    HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
2999        startSpecifier, specifierLen);
3000  }
3001
3002  // Check each flag does not conflict with any other component.
3003  if (!FS.hasValidThousandsGroupingPrefix())
3004    HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
3005  if (!FS.hasValidLeadingZeros())
3006    HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
3007  if (!FS.hasValidPlusPrefix())
3008    HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
3009  if (!FS.hasValidSpacePrefix())
3010    HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
3011  if (!FS.hasValidAlternativeForm())
3012    HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
3013  if (!FS.hasValidLeftJustified())
3014    HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
3015
3016  // Check that flags are not ignored by another flag
3017  if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
3018    HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
3019        startSpecifier, specifierLen);
3020  if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
3021    HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
3022            startSpecifier, specifierLen);
3023
3024  // Check the length modifier is valid with the given conversion specifier.
3025  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3026    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3027                                diag::warn_format_nonsensical_length);
3028  else if (!FS.hasStandardLengthModifier())
3029    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3030  else if (!FS.hasStandardLengthConversionCombination())
3031    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3032                                diag::warn_format_non_standard_conversion_spec);
3033
3034  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3035    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3036
3037  // The remaining checks depend on the data arguments.
3038  if (HasVAListArg)
3039    return true;
3040
3041  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3042    return false;
3043
3044  const Expr *Arg = getDataArg(argIndex);
3045  if (!Arg)
3046    return true;
3047
3048  return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3049}
3050
3051static bool requiresParensToAddCast(const Expr *E) {
3052  // FIXME: We should have a general way to reason about operator
3053  // precedence and whether parens are actually needed here.
3054  // Take care of a few common cases where they aren't.
3055  const Expr *Inside = E->IgnoreImpCasts();
3056  if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
3057    Inside = POE->getSyntacticForm()->IgnoreImpCasts();
3058
3059  switch (Inside->getStmtClass()) {
3060  case Stmt::ArraySubscriptExprClass:
3061  case Stmt::CallExprClass:
3062  case Stmt::CharacterLiteralClass:
3063  case Stmt::CXXBoolLiteralExprClass:
3064  case Stmt::DeclRefExprClass:
3065  case Stmt::FloatingLiteralClass:
3066  case Stmt::IntegerLiteralClass:
3067  case Stmt::MemberExprClass:
3068  case Stmt::ObjCArrayLiteralClass:
3069  case Stmt::ObjCBoolLiteralExprClass:
3070  case Stmt::ObjCBoxedExprClass:
3071  case Stmt::ObjCDictionaryLiteralClass:
3072  case Stmt::ObjCEncodeExprClass:
3073  case Stmt::ObjCIvarRefExprClass:
3074  case Stmt::ObjCMessageExprClass:
3075  case Stmt::ObjCPropertyRefExprClass:
3076  case Stmt::ObjCStringLiteralClass:
3077  case Stmt::ObjCSubscriptRefExprClass:
3078  case Stmt::ParenExprClass:
3079  case Stmt::StringLiteralClass:
3080  case Stmt::UnaryOperatorClass:
3081    return false;
3082  default:
3083    return true;
3084  }
3085}
3086
3087bool
3088CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
3089                                    const char *StartSpecifier,
3090                                    unsigned SpecifierLen,
3091                                    const Expr *E) {
3092  using namespace analyze_format_string;
3093  using namespace analyze_printf;
3094  // Now type check the data expression that matches the
3095  // format specifier.
3096  const analyze_printf::ArgType &AT = FS.getArgType(S.Context,
3097                                                    ObjCContext);
3098  if (!AT.isValid())
3099    return true;
3100
3101  QualType ExprTy = E->getType();
3102  while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
3103    ExprTy = TET->getUnderlyingExpr()->getType();
3104  }
3105
3106  if (AT.matchesType(S.Context, ExprTy))
3107    return true;
3108
3109  // Look through argument promotions for our error message's reported type.
3110  // This includes the integral and floating promotions, but excludes array
3111  // and function pointer decay; seeing that an argument intended to be a
3112  // string has type 'char [6]' is probably more confusing than 'char *'.
3113  if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3114    if (ICE->getCastKind() == CK_IntegralCast ||
3115        ICE->getCastKind() == CK_FloatingCast) {
3116      E = ICE->getSubExpr();
3117      ExprTy = E->getType();
3118
3119      // Check if we didn't match because of an implicit cast from a 'char'
3120      // or 'short' to an 'int'.  This is done because printf is a varargs
3121      // function.
3122      if (ICE->getType() == S.Context.IntTy ||
3123          ICE->getType() == S.Context.UnsignedIntTy) {
3124        // All further checking is done on the subexpression.
3125        if (AT.matchesType(S.Context, ExprTy))
3126          return true;
3127      }
3128    }
3129  } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
3130    // Special case for 'a', which has type 'int' in C.
3131    // Note, however, that we do /not/ want to treat multibyte constants like
3132    // 'MooV' as characters! This form is deprecated but still exists.
3133    if (ExprTy == S.Context.IntTy)
3134      if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
3135        ExprTy = S.Context.CharTy;
3136  }
3137
3138  // %C in an Objective-C context prints a unichar, not a wchar_t.
3139  // If the argument is an integer of some kind, believe the %C and suggest
3140  // a cast instead of changing the conversion specifier.
3141  QualType IntendedTy = ExprTy;
3142  if (ObjCContext &&
3143      FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
3144    if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
3145        !ExprTy->isCharType()) {
3146      // 'unichar' is defined as a typedef of unsigned short, but we should
3147      // prefer using the typedef if it is visible.
3148      IntendedTy = S.Context.UnsignedShortTy;
3149
3150      // While we are here, check if the value is an IntegerLiteral that happens
3151      // to be within the valid range.
3152      if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
3153        const llvm::APInt &V = IL->getValue();
3154        if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
3155          return true;
3156      }
3157
3158      LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getLocStart(),
3159                          Sema::LookupOrdinaryName);
3160      if (S.LookupName(Result, S.getCurScope())) {
3161        NamedDecl *ND = Result.getFoundDecl();
3162        if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
3163          if (TD->getUnderlyingType() == IntendedTy)
3164            IntendedTy = S.Context.getTypedefType(TD);
3165      }
3166    }
3167  }
3168
3169  // Special-case some of Darwin's platform-independence types by suggesting
3170  // casts to primitive types that are known to be large enough.
3171  bool ShouldNotPrintDirectly = false;
3172  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
3173    // Use a 'while' to peel off layers of typedefs.
3174    QualType TyTy = IntendedTy;
3175    while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
3176      StringRef Name = UserTy->getDecl()->getName();
3177      QualType CastTy = llvm::StringSwitch<QualType>(Name)
3178        .Case("NSInteger", S.Context.LongTy)
3179        .Case("NSUInteger", S.Context.UnsignedLongTy)
3180        .Case("SInt32", S.Context.IntTy)
3181        .Case("UInt32", S.Context.UnsignedIntTy)
3182        .Default(QualType());
3183
3184      if (!CastTy.isNull()) {
3185        ShouldNotPrintDirectly = true;
3186        IntendedTy = CastTy;
3187        break;
3188      }
3189      TyTy = UserTy->desugar();
3190    }
3191  }
3192
3193  // We may be able to offer a FixItHint if it is a supported type.
3194  PrintfSpecifier fixedFS = FS;
3195  bool success = fixedFS.fixType(IntendedTy, S.getLangOpts(),
3196                                 S.Context, ObjCContext);
3197
3198  if (success) {
3199    // Get the fix string from the fixed format specifier
3200    SmallString<16> buf;
3201    llvm::raw_svector_ostream os(buf);
3202    fixedFS.toString(os);
3203
3204    CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
3205
3206    if (IntendedTy == ExprTy) {
3207      // In this case, the specifier is wrong and should be changed to match
3208      // the argument.
3209      EmitFormatDiagnostic(
3210        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3211          << AT.getRepresentativeTypeName(S.Context) << IntendedTy
3212          << E->getSourceRange(),
3213        E->getLocStart(),
3214        /*IsStringLocation*/false,
3215        SpecRange,
3216        FixItHint::CreateReplacement(SpecRange, os.str()));
3217
3218    } else {
3219      // The canonical type for formatting this value is different from the
3220      // actual type of the expression. (This occurs, for example, with Darwin's
3221      // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
3222      // should be printed as 'long' for 64-bit compatibility.)
3223      // Rather than emitting a normal format/argument mismatch, we want to
3224      // add a cast to the recommended type (and correct the format string
3225      // if necessary).
3226      SmallString<16> CastBuf;
3227      llvm::raw_svector_ostream CastFix(CastBuf);
3228      CastFix << "(";
3229      IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
3230      CastFix << ")";
3231
3232      SmallVector<FixItHint,4> Hints;
3233      if (!AT.matchesType(S.Context, IntendedTy))
3234        Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
3235
3236      if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
3237        // If there's already a cast present, just replace it.
3238        SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
3239        Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
3240
3241      } else if (!requiresParensToAddCast(E)) {
3242        // If the expression has high enough precedence,
3243        // just write the C-style cast.
3244        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3245                                                   CastFix.str()));
3246      } else {
3247        // Otherwise, add parens around the expression as well as the cast.
3248        CastFix << "(";
3249        Hints.push_back(FixItHint::CreateInsertion(E->getLocStart(),
3250                                                   CastFix.str()));
3251
3252        SourceLocation After = S.PP.getLocForEndOfToken(E->getLocEnd());
3253        Hints.push_back(FixItHint::CreateInsertion(After, ")"));
3254      }
3255
3256      if (ShouldNotPrintDirectly) {
3257        // The expression has a type that should not be printed directly.
3258        // We extract the name from the typedef because we don't want to show
3259        // the underlying type in the diagnostic.
3260        StringRef Name = cast<TypedefType>(ExprTy)->getDecl()->getName();
3261
3262        EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
3263                               << Name << IntendedTy
3264                               << E->getSourceRange(),
3265                             E->getLocStart(), /*IsStringLocation=*/false,
3266                             SpecRange, Hints);
3267      } else {
3268        // In this case, the expression could be printed using a different
3269        // specifier, but we've decided that the specifier is probably correct
3270        // and we should cast instead. Just use the normal warning message.
3271        EmitFormatDiagnostic(
3272          S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3273            << AT.getRepresentativeTypeName(S.Context) << ExprTy
3274            << E->getSourceRange(),
3275          E->getLocStart(), /*IsStringLocation*/false,
3276          SpecRange, Hints);
3277      }
3278    }
3279  } else {
3280    const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
3281                                                   SpecifierLen);
3282    // Since the warning for passing non-POD types to variadic functions
3283    // was deferred until now, we emit a warning for non-POD
3284    // arguments here.
3285    switch (S.isValidVarArgType(ExprTy)) {
3286    case Sema::VAK_Valid:
3287    case Sema::VAK_ValidInCXX11:
3288      EmitFormatDiagnostic(
3289        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3290          << AT.getRepresentativeTypeName(S.Context) << ExprTy
3291          << CSR
3292          << E->getSourceRange(),
3293        E->getLocStart(), /*IsStringLocation*/false, CSR);
3294      break;
3295
3296    case Sema::VAK_Undefined:
3297      EmitFormatDiagnostic(
3298        S.PDiag(diag::warn_non_pod_vararg_with_format_string)
3299          << S.getLangOpts().CPlusPlus11
3300          << ExprTy
3301          << CallType
3302          << AT.getRepresentativeTypeName(S.Context)
3303          << CSR
3304          << E->getSourceRange(),
3305        E->getLocStart(), /*IsStringLocation*/false, CSR);
3306      checkForCStrMembers(AT, E, CSR);
3307      break;
3308
3309    case Sema::VAK_Invalid:
3310      if (ExprTy->isObjCObjectType())
3311        EmitFormatDiagnostic(
3312          S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
3313            << S.getLangOpts().CPlusPlus11
3314            << ExprTy
3315            << CallType
3316            << AT.getRepresentativeTypeName(S.Context)
3317            << CSR
3318            << E->getSourceRange(),
3319          E->getLocStart(), /*IsStringLocation*/false, CSR);
3320      else
3321        // FIXME: If this is an initializer list, suggest removing the braces
3322        // or inserting a cast to the target type.
3323        S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
3324          << isa<InitListExpr>(E) << ExprTy << CallType
3325          << AT.getRepresentativeTypeName(S.Context)
3326          << E->getSourceRange();
3327      break;
3328    }
3329
3330    assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
3331           "format string specifier index out of range");
3332    CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
3333  }
3334
3335  return true;
3336}
3337
3338//===--- CHECK: Scanf format string checking ------------------------------===//
3339
3340namespace {
3341class CheckScanfHandler : public CheckFormatHandler {
3342public:
3343  CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
3344                    const Expr *origFormatExpr, unsigned firstDataArg,
3345                    unsigned numDataArgs, const char *beg, bool hasVAListArg,
3346                    ArrayRef<const Expr *> Args,
3347                    unsigned formatIdx, bool inFunctionCall,
3348                    Sema::VariadicCallType CallType,
3349                    llvm::SmallBitVector &CheckedVarArgs)
3350    : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3351                         numDataArgs, beg, hasVAListArg,
3352                         Args, formatIdx, inFunctionCall, CallType,
3353                         CheckedVarArgs)
3354  {}
3355
3356  bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
3357                            const char *startSpecifier,
3358                            unsigned specifierLen);
3359
3360  bool HandleInvalidScanfConversionSpecifier(
3361          const analyze_scanf::ScanfSpecifier &FS,
3362          const char *startSpecifier,
3363          unsigned specifierLen);
3364
3365  void HandleIncompleteScanList(const char *start, const char *end);
3366};
3367}
3368
3369void CheckScanfHandler::HandleIncompleteScanList(const char *start,
3370                                                 const char *end) {
3371  EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
3372                       getLocationOfByte(end), /*IsStringLocation*/true,
3373                       getSpecifierRange(start, end - start));
3374}
3375
3376bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
3377                                        const analyze_scanf::ScanfSpecifier &FS,
3378                                        const char *startSpecifier,
3379                                        unsigned specifierLen) {
3380
3381  const analyze_scanf::ScanfConversionSpecifier &CS =
3382    FS.getConversionSpecifier();
3383
3384  return HandleInvalidConversionSpecifier(FS.getArgIndex(),
3385                                          getLocationOfByte(CS.getStart()),
3386                                          startSpecifier, specifierLen,
3387                                          CS.getStart(), CS.getLength());
3388}
3389
3390bool CheckScanfHandler::HandleScanfSpecifier(
3391                                       const analyze_scanf::ScanfSpecifier &FS,
3392                                       const char *startSpecifier,
3393                                       unsigned specifierLen) {
3394
3395  using namespace analyze_scanf;
3396  using namespace analyze_format_string;
3397
3398  const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
3399
3400  // Handle case where '%' and '*' don't consume an argument.  These shouldn't
3401  // be used to decide if we are using positional arguments consistently.
3402  if (FS.consumesDataArgument()) {
3403    if (atFirstArg) {
3404      atFirstArg = false;
3405      usesPositionalArgs = FS.usesPositionalArg();
3406    }
3407    else if (usesPositionalArgs != FS.usesPositionalArg()) {
3408      HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
3409                                        startSpecifier, specifierLen);
3410      return false;
3411    }
3412  }
3413
3414  // Check if the field with is non-zero.
3415  const OptionalAmount &Amt = FS.getFieldWidth();
3416  if (Amt.getHowSpecified() == OptionalAmount::Constant) {
3417    if (Amt.getConstantAmount() == 0) {
3418      const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
3419                                                   Amt.getConstantLength());
3420      EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
3421                           getLocationOfByte(Amt.getStart()),
3422                           /*IsStringLocation*/true, R,
3423                           FixItHint::CreateRemoval(R));
3424    }
3425  }
3426
3427  if (!FS.consumesDataArgument()) {
3428    // FIXME: Technically specifying a precision or field width here
3429    // makes no sense.  Worth issuing a warning at some point.
3430    return true;
3431  }
3432
3433  // Consume the argument.
3434  unsigned argIndex = FS.getArgIndex();
3435  if (argIndex < NumDataArgs) {
3436      // The check to see if the argIndex is valid will come later.
3437      // We set the bit here because we may exit early from this
3438      // function if we encounter some other error.
3439    CoveredArgs.set(argIndex);
3440  }
3441
3442  // Check the length modifier is valid with the given conversion specifier.
3443  if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo()))
3444    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3445                                diag::warn_format_nonsensical_length);
3446  else if (!FS.hasStandardLengthModifier())
3447    HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3448  else if (!FS.hasStandardLengthConversionCombination())
3449    HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3450                                diag::warn_format_non_standard_conversion_spec);
3451
3452  if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
3453    HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3454
3455  // The remaining checks depend on the data arguments.
3456  if (HasVAListArg)
3457    return true;
3458
3459  if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3460    return false;
3461
3462  // Check that the argument type matches the format specifier.
3463  const Expr *Ex = getDataArg(argIndex);
3464  if (!Ex)
3465    return true;
3466
3467  const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
3468  if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) {
3469    ScanfSpecifier fixedFS = FS;
3470    bool success = fixedFS.fixType(Ex->getType(), S.getLangOpts(),
3471                                   S.Context);
3472
3473    if (success) {
3474      // Get the fix string from the fixed format specifier.
3475      SmallString<128> buf;
3476      llvm::raw_svector_ostream os(buf);
3477      fixedFS.toString(os);
3478
3479      EmitFormatDiagnostic(
3480        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3481          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3482          << Ex->getSourceRange(),
3483        Ex->getLocStart(),
3484        /*IsStringLocation*/false,
3485        getSpecifierRange(startSpecifier, specifierLen),
3486        FixItHint::CreateReplacement(
3487          getSpecifierRange(startSpecifier, specifierLen),
3488          os.str()));
3489    } else {
3490      EmitFormatDiagnostic(
3491        S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
3492          << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
3493          << Ex->getSourceRange(),
3494        Ex->getLocStart(),
3495        /*IsStringLocation*/false,
3496        getSpecifierRange(startSpecifier, specifierLen));
3497    }
3498  }
3499
3500  return true;
3501}
3502
3503void Sema::CheckFormatString(const StringLiteral *FExpr,
3504                             const Expr *OrigFormatExpr,
3505                             ArrayRef<const Expr *> Args,
3506                             bool HasVAListArg, unsigned format_idx,
3507                             unsigned firstDataArg, FormatStringType Type,
3508                             bool inFunctionCall, VariadicCallType CallType,
3509                             llvm::SmallBitVector &CheckedVarArgs) {
3510
3511  // CHECK: is the format string a wide literal?
3512  if (!FExpr->isAscii() && !FExpr->isUTF8()) {
3513    CheckFormatHandler::EmitFormatDiagnostic(
3514      *this, inFunctionCall, Args[format_idx],
3515      PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
3516      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3517    return;
3518  }
3519
3520  // Str - The format string.  NOTE: this is NOT null-terminated!
3521  StringRef StrRef = FExpr->getString();
3522  const char *Str = StrRef.data();
3523  unsigned StrLen = StrRef.size();
3524  const unsigned numDataArgs = Args.size() - firstDataArg;
3525
3526  // CHECK: empty format string?
3527  if (StrLen == 0 && numDataArgs > 0) {
3528    CheckFormatHandler::EmitFormatDiagnostic(
3529      *this, inFunctionCall, Args[format_idx],
3530      PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
3531      /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
3532    return;
3533  }
3534
3535  if (Type == FST_Printf || Type == FST_NSString) {
3536    CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
3537                         numDataArgs, (Type == FST_NSString),
3538                         Str, HasVAListArg, Args, format_idx,
3539                         inFunctionCall, CallType, CheckedVarArgs);
3540
3541    if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
3542                                                  getLangOpts(),
3543                                                  Context.getTargetInfo()))
3544      H.DoneProcessing();
3545  } else if (Type == FST_Scanf) {
3546    CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
3547                        Str, HasVAListArg, Args, format_idx,
3548                        inFunctionCall, CallType, CheckedVarArgs);
3549
3550    if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
3551                                                 getLangOpts(),
3552                                                 Context.getTargetInfo()))
3553      H.DoneProcessing();
3554  } // TODO: handle other formats
3555}
3556
3557//===--- CHECK: Standard memory functions ---------------------------------===//
3558
3559/// \brief Determine whether the given type is a dynamic class type (e.g.,
3560/// whether it has a vtable).
3561static bool isDynamicClassType(QualType T) {
3562  if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3563    if (CXXRecordDecl *Definition = Record->getDefinition())
3564      if (Definition->isDynamicClass())
3565        return true;
3566
3567  return false;
3568}
3569
3570/// \brief If E is a sizeof expression, returns its argument expression,
3571/// otherwise returns NULL.
3572static const Expr *getSizeOfExprArg(const Expr* E) {
3573  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3574      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3575    if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
3576      return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
3577
3578  return 0;
3579}
3580
3581/// \brief If E is a sizeof expression, returns its argument type.
3582static QualType getSizeOfArgType(const Expr* E) {
3583  if (const UnaryExprOrTypeTraitExpr *SizeOf =
3584      dyn_cast<UnaryExprOrTypeTraitExpr>(E))
3585    if (SizeOf->getKind() == clang::UETT_SizeOf)
3586      return SizeOf->getTypeOfArgument();
3587
3588  return QualType();
3589}
3590
3591/// \brief Check for dangerous or invalid arguments to memset().
3592///
3593/// This issues warnings on known problematic, dangerous or unspecified
3594/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
3595/// function calls.
3596///
3597/// \param Call The call expression to diagnose.
3598void Sema::CheckMemaccessArguments(const CallExpr *Call,
3599                                   unsigned BId,
3600                                   IdentifierInfo *FnName) {
3601  assert(BId != 0);
3602
3603  // It is possible to have a non-standard definition of memset.  Validate
3604  // we have enough arguments, and if not, abort further checking.
3605  unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
3606  if (Call->getNumArgs() < ExpectedNumArgs)
3607    return;
3608
3609  unsigned LastArg = (BId == Builtin::BImemset ||
3610                      BId == Builtin::BIstrndup ? 1 : 2);
3611  unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
3612  const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
3613
3614  // We have special checking when the length is a sizeof expression.
3615  QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
3616  const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
3617  llvm::FoldingSetNodeID SizeOfArgID;
3618
3619  for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
3620    const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
3621    SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
3622
3623    QualType DestTy = Dest->getType();
3624    if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
3625      QualType PointeeTy = DestPtrTy->getPointeeType();
3626
3627      // Never warn about void type pointers. This can be used to suppress
3628      // false positives.
3629      if (PointeeTy->isVoidType())
3630        continue;
3631
3632      // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
3633      // actually comparing the expressions for equality. Because computing the
3634      // expression IDs can be expensive, we only do this if the diagnostic is
3635      // enabled.
3636      if (SizeOfArg &&
3637          Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
3638                                   SizeOfArg->getExprLoc())) {
3639        // We only compute IDs for expressions if the warning is enabled, and
3640        // cache the sizeof arg's ID.
3641        if (SizeOfArgID == llvm::FoldingSetNodeID())
3642          SizeOfArg->Profile(SizeOfArgID, Context, true);
3643        llvm::FoldingSetNodeID DestID;
3644        Dest->Profile(DestID, Context, true);
3645        if (DestID == SizeOfArgID) {
3646          // TODO: For strncpy() and friends, this could suggest sizeof(dst)
3647          //       over sizeof(src) as well.
3648          unsigned ActionIdx = 0; // Default is to suggest dereferencing.
3649          StringRef ReadableName = FnName->getName();
3650
3651          if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
3652            if (UnaryOp->getOpcode() == UO_AddrOf)
3653              ActionIdx = 1; // If its an address-of operator, just remove it.
3654          if (!PointeeTy->isIncompleteType() &&
3655              (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
3656            ActionIdx = 2; // If the pointee's size is sizeof(char),
3657                           // suggest an explicit length.
3658
3659          // If the function is defined as a builtin macro, do not show macro
3660          // expansion.
3661          SourceLocation SL = SizeOfArg->getExprLoc();
3662          SourceRange DSR = Dest->getSourceRange();
3663          SourceRange SSR = SizeOfArg->getSourceRange();
3664          SourceManager &SM  = PP.getSourceManager();
3665
3666          if (SM.isMacroArgExpansion(SL)) {
3667            ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
3668            SL = SM.getSpellingLoc(SL);
3669            DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
3670                             SM.getSpellingLoc(DSR.getEnd()));
3671            SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
3672                             SM.getSpellingLoc(SSR.getEnd()));
3673          }
3674
3675          DiagRuntimeBehavior(SL, SizeOfArg,
3676                              PDiag(diag::warn_sizeof_pointer_expr_memaccess)
3677                                << ReadableName
3678                                << PointeeTy
3679                                << DestTy
3680                                << DSR
3681                                << SSR);
3682          DiagRuntimeBehavior(SL, SizeOfArg,
3683                         PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
3684                                << ActionIdx
3685                                << SSR);
3686
3687          break;
3688        }
3689      }
3690
3691      // Also check for cases where the sizeof argument is the exact same
3692      // type as the memory argument, and where it points to a user-defined
3693      // record type.
3694      if (SizeOfArgTy != QualType()) {
3695        if (PointeeTy->isRecordType() &&
3696            Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
3697          DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
3698                              PDiag(diag::warn_sizeof_pointer_type_memaccess)
3699                                << FnName << SizeOfArgTy << ArgIdx
3700                                << PointeeTy << Dest->getSourceRange()
3701                                << LenExpr->getSourceRange());
3702          break;
3703        }
3704      }
3705
3706      // Always complain about dynamic classes.
3707      if (isDynamicClassType(PointeeTy)) {
3708
3709        unsigned OperationType = 0;
3710        // "overwritten" if we're warning about the destination for any call
3711        // but memcmp; otherwise a verb appropriate to the call.
3712        if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
3713          if (BId == Builtin::BImemcpy)
3714            OperationType = 1;
3715          else if(BId == Builtin::BImemmove)
3716            OperationType = 2;
3717          else if (BId == Builtin::BImemcmp)
3718            OperationType = 3;
3719        }
3720
3721        DiagRuntimeBehavior(
3722          Dest->getExprLoc(), Dest,
3723          PDiag(diag::warn_dyn_class_memaccess)
3724            << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
3725            << FnName << PointeeTy
3726            << OperationType
3727            << Call->getCallee()->getSourceRange());
3728      } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
3729               BId != Builtin::BImemset)
3730        DiagRuntimeBehavior(
3731          Dest->getExprLoc(), Dest,
3732          PDiag(diag::warn_arc_object_memaccess)
3733            << ArgIdx << FnName << PointeeTy
3734            << Call->getCallee()->getSourceRange());
3735      else
3736        continue;
3737
3738      DiagRuntimeBehavior(
3739        Dest->getExprLoc(), Dest,
3740        PDiag(diag::note_bad_memaccess_silence)
3741          << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
3742      break;
3743    }
3744  }
3745}
3746
3747// A little helper routine: ignore addition and subtraction of integer literals.
3748// This intentionally does not ignore all integer constant expressions because
3749// we don't want to remove sizeof().
3750static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
3751  Ex = Ex->IgnoreParenCasts();
3752
3753  for (;;) {
3754    const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
3755    if (!BO || !BO->isAdditiveOp())
3756      break;
3757
3758    const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
3759    const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
3760
3761    if (isa<IntegerLiteral>(RHS))
3762      Ex = LHS;
3763    else if (isa<IntegerLiteral>(LHS))
3764      Ex = RHS;
3765    else
3766      break;
3767  }
3768
3769  return Ex;
3770}
3771
3772static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
3773                                                      ASTContext &Context) {
3774  // Only handle constant-sized or VLAs, but not flexible members.
3775  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
3776    // Only issue the FIXIT for arrays of size > 1.
3777    if (CAT->getSize().getSExtValue() <= 1)
3778      return false;
3779  } else if (!Ty->isVariableArrayType()) {
3780    return false;
3781  }
3782  return true;
3783}
3784
3785// Warn if the user has made the 'size' argument to strlcpy or strlcat
3786// be the size of the source, instead of the destination.
3787void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
3788                                    IdentifierInfo *FnName) {
3789
3790  // Don't crash if the user has the wrong number of arguments
3791  if (Call->getNumArgs() != 3)
3792    return;
3793
3794  const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
3795  const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
3796  const Expr *CompareWithSrc = NULL;
3797
3798  // Look for 'strlcpy(dst, x, sizeof(x))'
3799  if (const Expr *Ex = getSizeOfExprArg(SizeArg))
3800    CompareWithSrc = Ex;
3801  else {
3802    // Look for 'strlcpy(dst, x, strlen(x))'
3803    if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
3804      if (SizeCall->isBuiltinCall() == Builtin::BIstrlen
3805          && SizeCall->getNumArgs() == 1)
3806        CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
3807    }
3808  }
3809
3810  if (!CompareWithSrc)
3811    return;
3812
3813  // Determine if the argument to sizeof/strlen is equal to the source
3814  // argument.  In principle there's all kinds of things you could do
3815  // here, for instance creating an == expression and evaluating it with
3816  // EvaluateAsBooleanCondition, but this uses a more direct technique:
3817  const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
3818  if (!SrcArgDRE)
3819    return;
3820
3821  const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
3822  if (!CompareWithSrcDRE ||
3823      SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
3824    return;
3825
3826  const Expr *OriginalSizeArg = Call->getArg(2);
3827  Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
3828    << OriginalSizeArg->getSourceRange() << FnName;
3829
3830  // Output a FIXIT hint if the destination is an array (rather than a
3831  // pointer to an array).  This could be enhanced to handle some
3832  // pointers if we know the actual size, like if DstArg is 'array+2'
3833  // we could say 'sizeof(array)-2'.
3834  const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
3835  if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
3836    return;
3837
3838  SmallString<128> sizeString;
3839  llvm::raw_svector_ostream OS(sizeString);
3840  OS << "sizeof(";
3841  DstArg->printPretty(OS, 0, getPrintingPolicy());
3842  OS << ")";
3843
3844  Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
3845    << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
3846                                    OS.str());
3847}
3848
3849/// Check if two expressions refer to the same declaration.
3850static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
3851  if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
3852    if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
3853      return D1->getDecl() == D2->getDecl();
3854  return false;
3855}
3856
3857static const Expr *getStrlenExprArg(const Expr *E) {
3858  if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
3859    const FunctionDecl *FD = CE->getDirectCallee();
3860    if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
3861      return 0;
3862    return CE->getArg(0)->IgnoreParenCasts();
3863  }
3864  return 0;
3865}
3866
3867// Warn on anti-patterns as the 'size' argument to strncat.
3868// The correct size argument should look like following:
3869//   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
3870void Sema::CheckStrncatArguments(const CallExpr *CE,
3871                                 IdentifierInfo *FnName) {
3872  // Don't crash if the user has the wrong number of arguments.
3873  if (CE->getNumArgs() < 3)
3874    return;
3875  const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
3876  const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
3877  const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
3878
3879  // Identify common expressions, which are wrongly used as the size argument
3880  // to strncat and may lead to buffer overflows.
3881  unsigned PatternType = 0;
3882  if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
3883    // - sizeof(dst)
3884    if (referToTheSameDecl(SizeOfArg, DstArg))
3885      PatternType = 1;
3886    // - sizeof(src)
3887    else if (referToTheSameDecl(SizeOfArg, SrcArg))
3888      PatternType = 2;
3889  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
3890    if (BE->getOpcode() == BO_Sub) {
3891      const Expr *L = BE->getLHS()->IgnoreParenCasts();
3892      const Expr *R = BE->getRHS()->IgnoreParenCasts();
3893      // - sizeof(dst) - strlen(dst)
3894      if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
3895          referToTheSameDecl(DstArg, getStrlenExprArg(R)))
3896        PatternType = 1;
3897      // - sizeof(src) - (anything)
3898      else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
3899        PatternType = 2;
3900    }
3901  }
3902
3903  if (PatternType == 0)
3904    return;
3905
3906  // Generate the diagnostic.
3907  SourceLocation SL = LenArg->getLocStart();
3908  SourceRange SR = LenArg->getSourceRange();
3909  SourceManager &SM  = PP.getSourceManager();
3910
3911  // If the function is defined as a builtin macro, do not show macro expansion.
3912  if (SM.isMacroArgExpansion(SL)) {
3913    SL = SM.getSpellingLoc(SL);
3914    SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
3915                     SM.getSpellingLoc(SR.getEnd()));
3916  }
3917
3918  // Check if the destination is an array (rather than a pointer to an array).
3919  QualType DstTy = DstArg->getType();
3920  bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
3921                                                                    Context);
3922  if (!isKnownSizeArray) {
3923    if (PatternType == 1)
3924      Diag(SL, diag::warn_strncat_wrong_size) << SR;
3925    else
3926      Diag(SL, diag::warn_strncat_src_size) << SR;
3927    return;
3928  }
3929
3930  if (PatternType == 1)
3931    Diag(SL, diag::warn_strncat_large_size) << SR;
3932  else
3933    Diag(SL, diag::warn_strncat_src_size) << SR;
3934
3935  SmallString<128> sizeString;
3936  llvm::raw_svector_ostream OS(sizeString);
3937  OS << "sizeof(";
3938  DstArg->printPretty(OS, 0, getPrintingPolicy());
3939  OS << ") - ";
3940  OS << "strlen(";
3941  DstArg->printPretty(OS, 0, getPrintingPolicy());
3942  OS << ") - 1";
3943
3944  Diag(SL, diag::note_strncat_wrong_size)
3945    << FixItHint::CreateReplacement(SR, OS.str());
3946}
3947
3948//===--- CHECK: Return Address of Stack Variable --------------------------===//
3949
3950static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
3951                     Decl *ParentDecl);
3952static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars,
3953                      Decl *ParentDecl);
3954
3955/// CheckReturnStackAddr - Check if a return statement returns the address
3956///   of a stack variable.
3957void
3958Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
3959                           SourceLocation ReturnLoc) {
3960
3961  Expr *stackE = 0;
3962  SmallVector<DeclRefExpr *, 8> refVars;
3963
3964  // Perform checking for returned stack addresses, local blocks,
3965  // label addresses or references to temporaries.
3966  if (lhsType->isPointerType() ||
3967      (!getLangOpts().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
3968    stackE = EvalAddr(RetValExp, refVars, /*ParentDecl=*/0);
3969  } else if (lhsType->isReferenceType()) {
3970    stackE = EvalVal(RetValExp, refVars, /*ParentDecl=*/0);
3971  }
3972
3973  if (stackE == 0)
3974    return; // Nothing suspicious was found.
3975
3976  SourceLocation diagLoc;
3977  SourceRange diagRange;
3978  if (refVars.empty()) {
3979    diagLoc = stackE->getLocStart();
3980    diagRange = stackE->getSourceRange();
3981  } else {
3982    // We followed through a reference variable. 'stackE' contains the
3983    // problematic expression but we will warn at the return statement pointing
3984    // at the reference variable. We will later display the "trail" of
3985    // reference variables using notes.
3986    diagLoc = refVars[0]->getLocStart();
3987    diagRange = refVars[0]->getSourceRange();
3988  }
3989
3990  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
3991    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
3992                                             : diag::warn_ret_stack_addr)
3993     << DR->getDecl()->getDeclName() << diagRange;
3994  } else if (isa<BlockExpr>(stackE)) { // local block.
3995    Diag(diagLoc, diag::err_ret_local_block) << diagRange;
3996  } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
3997    Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
3998  } else { // local temporary.
3999    Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
4000                                             : diag::warn_ret_local_temp_addr)
4001     << diagRange;
4002  }
4003
4004  // Display the "trail" of reference variables that we followed until we
4005  // found the problematic expression using notes.
4006  for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
4007    VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
4008    // If this var binds to another reference var, show the range of the next
4009    // var, otherwise the var binds to the problematic expression, in which case
4010    // show the range of the expression.
4011    SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
4012                                  : stackE->getSourceRange();
4013    Diag(VD->getLocation(), diag::note_ref_var_local_bind)
4014      << VD->getDeclName() << range;
4015  }
4016}
4017
4018/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
4019///  check if the expression in a return statement evaluates to an address
4020///  to a location on the stack, a local block, an address of a label, or a
4021///  reference to local temporary. The recursion is used to traverse the
4022///  AST of the return expression, with recursion backtracking when we
4023///  encounter a subexpression that (1) clearly does not lead to one of the
4024///  above problematic expressions (2) is something we cannot determine leads to
4025///  a problematic expression based on such local checking.
4026///
4027///  Both EvalAddr and EvalVal follow through reference variables to evaluate
4028///  the expression that they point to. Such variables are added to the
4029///  'refVars' vector so that we know what the reference variable "trail" was.
4030///
4031///  EvalAddr processes expressions that are pointers that are used as
4032///  references (and not L-values).  EvalVal handles all other values.
4033///  At the base case of the recursion is a check for the above problematic
4034///  expressions.
4035///
4036///  This implementation handles:
4037///
4038///   * pointer-to-pointer casts
4039///   * implicit conversions from array references to pointers
4040///   * taking the address of fields
4041///   * arbitrary interplay between "&" and "*" operators
4042///   * pointer arithmetic from an address of a stack variable
4043///   * taking the address of an array element where the array is on the stack
4044static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4045                      Decl *ParentDecl) {
4046  if (E->isTypeDependent())
4047    return NULL;
4048
4049  // We should only be called for evaluating pointer expressions.
4050  assert((E->getType()->isAnyPointerType() ||
4051          E->getType()->isBlockPointerType() ||
4052          E->getType()->isObjCQualifiedIdType()) &&
4053         "EvalAddr only works on pointers");
4054
4055  E = E->IgnoreParens();
4056
4057  // Our "symbolic interpreter" is just a dispatch off the currently
4058  // viewed AST node.  We then recursively traverse the AST by calling
4059  // EvalAddr and EvalVal appropriately.
4060  switch (E->getStmtClass()) {
4061  case Stmt::DeclRefExprClass: {
4062    DeclRefExpr *DR = cast<DeclRefExpr>(E);
4063
4064    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
4065      // If this is a reference variable, follow through to the expression that
4066      // it points to.
4067      if (V->hasLocalStorage() &&
4068          V->getType()->isReferenceType() && V->hasInit()) {
4069        // Add the reference variable to the "trail".
4070        refVars.push_back(DR);
4071        return EvalAddr(V->getInit(), refVars, ParentDecl);
4072      }
4073
4074    return NULL;
4075  }
4076
4077  case Stmt::UnaryOperatorClass: {
4078    // The only unary operator that make sense to handle here
4079    // is AddrOf.  All others don't make sense as pointers.
4080    UnaryOperator *U = cast<UnaryOperator>(E);
4081
4082    if (U->getOpcode() == UO_AddrOf)
4083      return EvalVal(U->getSubExpr(), refVars, ParentDecl);
4084    else
4085      return NULL;
4086  }
4087
4088  case Stmt::BinaryOperatorClass: {
4089    // Handle pointer arithmetic.  All other binary operators are not valid
4090    // in this context.
4091    BinaryOperator *B = cast<BinaryOperator>(E);
4092    BinaryOperatorKind op = B->getOpcode();
4093
4094    if (op != BO_Add && op != BO_Sub)
4095      return NULL;
4096
4097    Expr *Base = B->getLHS();
4098
4099    // Determine which argument is the real pointer base.  It could be
4100    // the RHS argument instead of the LHS.
4101    if (!Base->getType()->isPointerType()) Base = B->getRHS();
4102
4103    assert (Base->getType()->isPointerType());
4104    return EvalAddr(Base, refVars, ParentDecl);
4105  }
4106
4107  // For conditional operators we need to see if either the LHS or RHS are
4108  // valid DeclRefExpr*s.  If one of them is valid, we return it.
4109  case Stmt::ConditionalOperatorClass: {
4110    ConditionalOperator *C = cast<ConditionalOperator>(E);
4111
4112    // Handle the GNU extension for missing LHS.
4113    if (Expr *lhsExpr = C->getLHS()) {
4114    // In C++, we can have a throw-expression, which has 'void' type.
4115      if (!lhsExpr->getType()->isVoidType())
4116        if (Expr* LHS = EvalAddr(lhsExpr, refVars, ParentDecl))
4117          return LHS;
4118    }
4119
4120    // In C++, we can have a throw-expression, which has 'void' type.
4121    if (C->getRHS()->getType()->isVoidType())
4122      return NULL;
4123
4124    return EvalAddr(C->getRHS(), refVars, ParentDecl);
4125  }
4126
4127  case Stmt::BlockExprClass:
4128    if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
4129      return E; // local block.
4130    return NULL;
4131
4132  case Stmt::AddrLabelExprClass:
4133    return E; // address of label.
4134
4135  case Stmt::ExprWithCleanupsClass:
4136    return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
4137                    ParentDecl);
4138
4139  // For casts, we need to handle conversions from arrays to
4140  // pointer values, and pointer-to-pointer conversions.
4141  case Stmt::ImplicitCastExprClass:
4142  case Stmt::CStyleCastExprClass:
4143  case Stmt::CXXFunctionalCastExprClass:
4144  case Stmt::ObjCBridgedCastExprClass:
4145  case Stmt::CXXStaticCastExprClass:
4146  case Stmt::CXXDynamicCastExprClass:
4147  case Stmt::CXXConstCastExprClass:
4148  case Stmt::CXXReinterpretCastExprClass: {
4149    Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
4150    switch (cast<CastExpr>(E)->getCastKind()) {
4151    case CK_BitCast:
4152    case CK_LValueToRValue:
4153    case CK_NoOp:
4154    case CK_BaseToDerived:
4155    case CK_DerivedToBase:
4156    case CK_UncheckedDerivedToBase:
4157    case CK_Dynamic:
4158    case CK_CPointerToObjCPointerCast:
4159    case CK_BlockPointerToObjCPointerCast:
4160    case CK_AnyPointerToBlockPointerCast:
4161      return EvalAddr(SubExpr, refVars, ParentDecl);
4162
4163    case CK_ArrayToPointerDecay:
4164      return EvalVal(SubExpr, refVars, ParentDecl);
4165
4166    default:
4167      return 0;
4168    }
4169  }
4170
4171  case Stmt::MaterializeTemporaryExprClass:
4172    if (Expr *Result = EvalAddr(
4173                         cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4174                                refVars, ParentDecl))
4175      return Result;
4176
4177    return E;
4178
4179  // Everything else: we simply don't reason about them.
4180  default:
4181    return NULL;
4182  }
4183}
4184
4185
4186///  EvalVal - This function is complements EvalAddr in the mutual recursion.
4187///   See the comments for EvalAddr for more details.
4188static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
4189                     Decl *ParentDecl) {
4190do {
4191  // We should only be called for evaluating non-pointer expressions, or
4192  // expressions with a pointer type that are not used as references but instead
4193  // are l-values (e.g., DeclRefExpr with a pointer type).
4194
4195  // Our "symbolic interpreter" is just a dispatch off the currently
4196  // viewed AST node.  We then recursively traverse the AST by calling
4197  // EvalAddr and EvalVal appropriately.
4198
4199  E = E->IgnoreParens();
4200  switch (E->getStmtClass()) {
4201  case Stmt::ImplicitCastExprClass: {
4202    ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
4203    if (IE->getValueKind() == VK_LValue) {
4204      E = IE->getSubExpr();
4205      continue;
4206    }
4207    return NULL;
4208  }
4209
4210  case Stmt::ExprWithCleanupsClass:
4211    return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
4212
4213  case Stmt::DeclRefExprClass: {
4214    // When we hit a DeclRefExpr we are looking at code that refers to a
4215    // variable's name. If it's not a reference variable we check if it has
4216    // local storage within the function, and if so, return the expression.
4217    DeclRefExpr *DR = cast<DeclRefExpr>(E);
4218
4219    if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl())) {
4220      // Check if it refers to itself, e.g. "int& i = i;".
4221      if (V == ParentDecl)
4222        return DR;
4223
4224      if (V->hasLocalStorage()) {
4225        if (!V->getType()->isReferenceType())
4226          return DR;
4227
4228        // Reference variable, follow through to the expression that
4229        // it points to.
4230        if (V->hasInit()) {
4231          // Add the reference variable to the "trail".
4232          refVars.push_back(DR);
4233          return EvalVal(V->getInit(), refVars, V);
4234        }
4235      }
4236    }
4237
4238    return NULL;
4239  }
4240
4241  case Stmt::UnaryOperatorClass: {
4242    // The only unary operator that make sense to handle here
4243    // is Deref.  All others don't resolve to a "name."  This includes
4244    // handling all sorts of rvalues passed to a unary operator.
4245    UnaryOperator *U = cast<UnaryOperator>(E);
4246
4247    if (U->getOpcode() == UO_Deref)
4248      return EvalAddr(U->getSubExpr(), refVars, ParentDecl);
4249
4250    return NULL;
4251  }
4252
4253  case Stmt::ArraySubscriptExprClass: {
4254    // Array subscripts are potential references to data on the stack.  We
4255    // retrieve the DeclRefExpr* for the array variable if it indeed
4256    // has local storage.
4257    return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
4258  }
4259
4260  case Stmt::ConditionalOperatorClass: {
4261    // For conditional operators we need to see if either the LHS or RHS are
4262    // non-NULL Expr's.  If one is non-NULL, we return it.
4263    ConditionalOperator *C = cast<ConditionalOperator>(E);
4264
4265    // Handle the GNU extension for missing LHS.
4266    if (Expr *lhsExpr = C->getLHS())
4267      if (Expr *LHS = EvalVal(lhsExpr, refVars, ParentDecl))
4268        return LHS;
4269
4270    return EvalVal(C->getRHS(), refVars, ParentDecl);
4271  }
4272
4273  // Accesses to members are potential references to data on the stack.
4274  case Stmt::MemberExprClass: {
4275    MemberExpr *M = cast<MemberExpr>(E);
4276
4277    // Check for indirect access.  We only want direct field accesses.
4278    if (M->isArrow())
4279      return NULL;
4280
4281    // Check whether the member type is itself a reference, in which case
4282    // we're not going to refer to the member, but to what the member refers to.
4283    if (M->getMemberDecl()->getType()->isReferenceType())
4284      return NULL;
4285
4286    return EvalVal(M->getBase(), refVars, ParentDecl);
4287  }
4288
4289  case Stmt::MaterializeTemporaryExprClass:
4290    if (Expr *Result = EvalVal(
4291                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
4292                               refVars, ParentDecl))
4293      return Result;
4294
4295    return E;
4296
4297  default:
4298    // Check that we don't return or take the address of a reference to a
4299    // temporary. This is only useful in C++.
4300    if (!E->isTypeDependent() && E->isRValue())
4301      return E;
4302
4303    // Everything else: we simply don't reason about them.
4304    return NULL;
4305  }
4306} while (true);
4307}
4308
4309//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
4310
4311/// Check for comparisons of floating point operands using != and ==.
4312/// Issue a warning if these are no self-comparisons, as they are not likely
4313/// to do what the programmer intended.
4314void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
4315  Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
4316  Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
4317
4318  // Special case: check for x == x (which is OK).
4319  // Do not emit warnings for such cases.
4320  if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
4321    if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
4322      if (DRL->getDecl() == DRR->getDecl())
4323        return;
4324
4325
4326  // Special case: check for comparisons against literals that can be exactly
4327  //  represented by APFloat.  In such cases, do not emit a warning.  This
4328  //  is a heuristic: often comparison against such literals are used to
4329  //  detect if a value in a variable has not changed.  This clearly can
4330  //  lead to false negatives.
4331  if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
4332    if (FLL->isExact())
4333      return;
4334  } else
4335    if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
4336      if (FLR->isExact())
4337        return;
4338
4339  // Check for comparisons with builtin types.
4340  if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
4341    if (CL->isBuiltinCall())
4342      return;
4343
4344  if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
4345    if (CR->isBuiltinCall())
4346      return;
4347
4348  // Emit the diagnostic.
4349  Diag(Loc, diag::warn_floatingpoint_eq)
4350    << LHS->getSourceRange() << RHS->getSourceRange();
4351}
4352
4353//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
4354//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
4355
4356namespace {
4357
4358/// Structure recording the 'active' range of an integer-valued
4359/// expression.
4360struct IntRange {
4361  /// The number of bits active in the int.
4362  unsigned Width;
4363
4364  /// True if the int is known not to have negative values.
4365  bool NonNegative;
4366
4367  IntRange(unsigned Width, bool NonNegative)
4368    : Width(Width), NonNegative(NonNegative)
4369  {}
4370
4371  /// Returns the range of the bool type.
4372  static IntRange forBoolType() {
4373    return IntRange(1, true);
4374  }
4375
4376  /// Returns the range of an opaque value of the given integral type.
4377  static IntRange forValueOfType(ASTContext &C, QualType T) {
4378    return forValueOfCanonicalType(C,
4379                          T->getCanonicalTypeInternal().getTypePtr());
4380  }
4381
4382  /// Returns the range of an opaque value of a canonical integral type.
4383  static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
4384    assert(T->isCanonicalUnqualified());
4385
4386    if (const VectorType *VT = dyn_cast<VectorType>(T))
4387      T = VT->getElementType().getTypePtr();
4388    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4389      T = CT->getElementType().getTypePtr();
4390
4391    // For enum types, use the known bit width of the enumerators.
4392    if (const EnumType *ET = dyn_cast<EnumType>(T)) {
4393      EnumDecl *Enum = ET->getDecl();
4394      if (!Enum->isCompleteDefinition())
4395        return IntRange(C.getIntWidth(QualType(T, 0)), false);
4396
4397      unsigned NumPositive = Enum->getNumPositiveBits();
4398      unsigned NumNegative = Enum->getNumNegativeBits();
4399
4400      if (NumNegative == 0)
4401        return IntRange(NumPositive, true/*NonNegative*/);
4402      else
4403        return IntRange(std::max(NumPositive + 1, NumNegative),
4404                        false/*NonNegative*/);
4405    }
4406
4407    const BuiltinType *BT = cast<BuiltinType>(T);
4408    assert(BT->isInteger());
4409
4410    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4411  }
4412
4413  /// Returns the "target" range of a canonical integral type, i.e.
4414  /// the range of values expressible in the type.
4415  ///
4416  /// This matches forValueOfCanonicalType except that enums have the
4417  /// full range of their type, not the range of their enumerators.
4418  static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
4419    assert(T->isCanonicalUnqualified());
4420
4421    if (const VectorType *VT = dyn_cast<VectorType>(T))
4422      T = VT->getElementType().getTypePtr();
4423    if (const ComplexType *CT = dyn_cast<ComplexType>(T))
4424      T = CT->getElementType().getTypePtr();
4425    if (const EnumType *ET = dyn_cast<EnumType>(T))
4426      T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
4427
4428    const BuiltinType *BT = cast<BuiltinType>(T);
4429    assert(BT->isInteger());
4430
4431    return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
4432  }
4433
4434  /// Returns the supremum of two ranges: i.e. their conservative merge.
4435  static IntRange join(IntRange L, IntRange R) {
4436    return IntRange(std::max(L.Width, R.Width),
4437                    L.NonNegative && R.NonNegative);
4438  }
4439
4440  /// Returns the infinum of two ranges: i.e. their aggressive merge.
4441  static IntRange meet(IntRange L, IntRange R) {
4442    return IntRange(std::min(L.Width, R.Width),
4443                    L.NonNegative || R.NonNegative);
4444  }
4445};
4446
4447static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
4448                              unsigned MaxWidth) {
4449  if (value.isSigned() && value.isNegative())
4450    return IntRange(value.getMinSignedBits(), false);
4451
4452  if (value.getBitWidth() > MaxWidth)
4453    value = value.trunc(MaxWidth);
4454
4455  // isNonNegative() just checks the sign bit without considering
4456  // signedness.
4457  return IntRange(value.getActiveBits(), true);
4458}
4459
4460static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
4461                              unsigned MaxWidth) {
4462  if (result.isInt())
4463    return GetValueRange(C, result.getInt(), MaxWidth);
4464
4465  if (result.isVector()) {
4466    IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
4467    for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
4468      IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
4469      R = IntRange::join(R, El);
4470    }
4471    return R;
4472  }
4473
4474  if (result.isComplexInt()) {
4475    IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
4476    IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
4477    return IntRange::join(R, I);
4478  }
4479
4480  // This can happen with lossless casts to intptr_t of "based" lvalues.
4481  // Assume it might use arbitrary bits.
4482  // FIXME: The only reason we need to pass the type in here is to get
4483  // the sign right on this one case.  It would be nice if APValue
4484  // preserved this.
4485  assert(result.isLValue() || result.isAddrLabelDiff());
4486  return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
4487}
4488
4489static QualType GetExprType(Expr *E) {
4490  QualType Ty = E->getType();
4491  if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
4492    Ty = AtomicRHS->getValueType();
4493  return Ty;
4494}
4495
4496/// Pseudo-evaluate the given integer expression, estimating the
4497/// range of values it might take.
4498///
4499/// \param MaxWidth - the width to which the value will be truncated
4500static IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
4501  E = E->IgnoreParens();
4502
4503  // Try a full evaluation first.
4504  Expr::EvalResult result;
4505  if (E->EvaluateAsRValue(result, C))
4506    return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
4507
4508  // I think we only want to look through implicit casts here; if the
4509  // user has an explicit widening cast, we should treat the value as
4510  // being of the new, wider type.
4511  if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
4512    if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
4513      return GetExprRange(C, CE->getSubExpr(), MaxWidth);
4514
4515    IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
4516
4517    bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
4518
4519    // Assume that non-integer casts can span the full range of the type.
4520    if (!isIntegerCast)
4521      return OutputTypeRange;
4522
4523    IntRange SubRange
4524      = GetExprRange(C, CE->getSubExpr(),
4525                     std::min(MaxWidth, OutputTypeRange.Width));
4526
4527    // Bail out if the subexpr's range is as wide as the cast type.
4528    if (SubRange.Width >= OutputTypeRange.Width)
4529      return OutputTypeRange;
4530
4531    // Otherwise, we take the smaller width, and we're non-negative if
4532    // either the output type or the subexpr is.
4533    return IntRange(SubRange.Width,
4534                    SubRange.NonNegative || OutputTypeRange.NonNegative);
4535  }
4536
4537  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
4538    // If we can fold the condition, just take that operand.
4539    bool CondResult;
4540    if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
4541      return GetExprRange(C, CondResult ? CO->getTrueExpr()
4542                                        : CO->getFalseExpr(),
4543                          MaxWidth);
4544
4545    // Otherwise, conservatively merge.
4546    IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
4547    IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
4548    return IntRange::join(L, R);
4549  }
4550
4551  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4552    switch (BO->getOpcode()) {
4553
4554    // Boolean-valued operations are single-bit and positive.
4555    case BO_LAnd:
4556    case BO_LOr:
4557    case BO_LT:
4558    case BO_GT:
4559    case BO_LE:
4560    case BO_GE:
4561    case BO_EQ:
4562    case BO_NE:
4563      return IntRange::forBoolType();
4564
4565    // The type of the assignments is the type of the LHS, so the RHS
4566    // is not necessarily the same type.
4567    case BO_MulAssign:
4568    case BO_DivAssign:
4569    case BO_RemAssign:
4570    case BO_AddAssign:
4571    case BO_SubAssign:
4572    case BO_XorAssign:
4573    case BO_OrAssign:
4574      // TODO: bitfields?
4575      return IntRange::forValueOfType(C, GetExprType(E));
4576
4577    // Simple assignments just pass through the RHS, which will have
4578    // been coerced to the LHS type.
4579    case BO_Assign:
4580      // TODO: bitfields?
4581      return GetExprRange(C, BO->getRHS(), MaxWidth);
4582
4583    // Operations with opaque sources are black-listed.
4584    case BO_PtrMemD:
4585    case BO_PtrMemI:
4586      return IntRange::forValueOfType(C, GetExprType(E));
4587
4588    // Bitwise-and uses the *infinum* of the two source ranges.
4589    case BO_And:
4590    case BO_AndAssign:
4591      return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
4592                            GetExprRange(C, BO->getRHS(), MaxWidth));
4593
4594    // Left shift gets black-listed based on a judgement call.
4595    case BO_Shl:
4596      // ...except that we want to treat '1 << (blah)' as logically
4597      // positive.  It's an important idiom.
4598      if (IntegerLiteral *I
4599            = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
4600        if (I->getValue() == 1) {
4601          IntRange R = IntRange::forValueOfType(C, GetExprType(E));
4602          return IntRange(R.Width, /*NonNegative*/ true);
4603        }
4604      }
4605      // fallthrough
4606
4607    case BO_ShlAssign:
4608      return IntRange::forValueOfType(C, GetExprType(E));
4609
4610    // Right shift by a constant can narrow its left argument.
4611    case BO_Shr:
4612    case BO_ShrAssign: {
4613      IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4614
4615      // If the shift amount is a positive constant, drop the width by
4616      // that much.
4617      llvm::APSInt shift;
4618      if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
4619          shift.isNonNegative()) {
4620        unsigned zext = shift.getZExtValue();
4621        if (zext >= L.Width)
4622          L.Width = (L.NonNegative ? 0 : 1);
4623        else
4624          L.Width -= zext;
4625      }
4626
4627      return L;
4628    }
4629
4630    // Comma acts as its right operand.
4631    case BO_Comma:
4632      return GetExprRange(C, BO->getRHS(), MaxWidth);
4633
4634    // Black-list pointer subtractions.
4635    case BO_Sub:
4636      if (BO->getLHS()->getType()->isPointerType())
4637        return IntRange::forValueOfType(C, GetExprType(E));
4638      break;
4639
4640    // The width of a division result is mostly determined by the size
4641    // of the LHS.
4642    case BO_Div: {
4643      // Don't 'pre-truncate' the operands.
4644      unsigned opWidth = C.getIntWidth(GetExprType(E));
4645      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4646
4647      // If the divisor is constant, use that.
4648      llvm::APSInt divisor;
4649      if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
4650        unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
4651        if (log2 >= L.Width)
4652          L.Width = (L.NonNegative ? 0 : 1);
4653        else
4654          L.Width = std::min(L.Width - log2, MaxWidth);
4655        return L;
4656      }
4657
4658      // Otherwise, just use the LHS's width.
4659      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4660      return IntRange(L.Width, L.NonNegative && R.NonNegative);
4661    }
4662
4663    // The result of a remainder can't be larger than the result of
4664    // either side.
4665    case BO_Rem: {
4666      // Don't 'pre-truncate' the operands.
4667      unsigned opWidth = C.getIntWidth(GetExprType(E));
4668      IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
4669      IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
4670
4671      IntRange meet = IntRange::meet(L, R);
4672      meet.Width = std::min(meet.Width, MaxWidth);
4673      return meet;
4674    }
4675
4676    // The default behavior is okay for these.
4677    case BO_Mul:
4678    case BO_Add:
4679    case BO_Xor:
4680    case BO_Or:
4681      break;
4682    }
4683
4684    // The default case is to treat the operation as if it were closed
4685    // on the narrowest type that encompasses both operands.
4686    IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
4687    IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
4688    return IntRange::join(L, R);
4689  }
4690
4691  if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
4692    switch (UO->getOpcode()) {
4693    // Boolean-valued operations are white-listed.
4694    case UO_LNot:
4695      return IntRange::forBoolType();
4696
4697    // Operations with opaque sources are black-listed.
4698    case UO_Deref:
4699    case UO_AddrOf: // should be impossible
4700      return IntRange::forValueOfType(C, GetExprType(E));
4701
4702    default:
4703      return GetExprRange(C, UO->getSubExpr(), MaxWidth);
4704    }
4705  }
4706
4707  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
4708    return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
4709
4710  if (FieldDecl *BitField = E->getSourceBitField())
4711    return IntRange(BitField->getBitWidthValue(C),
4712                    BitField->getType()->isUnsignedIntegerOrEnumerationType());
4713
4714  return IntRange::forValueOfType(C, GetExprType(E));
4715}
4716
4717static IntRange GetExprRange(ASTContext &C, Expr *E) {
4718  return GetExprRange(C, E, C.getIntWidth(GetExprType(E)));
4719}
4720
4721/// Checks whether the given value, which currently has the given
4722/// source semantics, has the same value when coerced through the
4723/// target semantics.
4724static bool IsSameFloatAfterCast(const llvm::APFloat &value,
4725                                 const llvm::fltSemantics &Src,
4726                                 const llvm::fltSemantics &Tgt) {
4727  llvm::APFloat truncated = value;
4728
4729  bool ignored;
4730  truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
4731  truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
4732
4733  return truncated.bitwiseIsEqual(value);
4734}
4735
4736/// Checks whether the given value, which currently has the given
4737/// source semantics, has the same value when coerced through the
4738/// target semantics.
4739///
4740/// The value might be a vector of floats (or a complex number).
4741static bool IsSameFloatAfterCast(const APValue &value,
4742                                 const llvm::fltSemantics &Src,
4743                                 const llvm::fltSemantics &Tgt) {
4744  if (value.isFloat())
4745    return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
4746
4747  if (value.isVector()) {
4748    for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
4749      if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
4750        return false;
4751    return true;
4752  }
4753
4754  assert(value.isComplexFloat());
4755  return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
4756          IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
4757}
4758
4759static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
4760
4761static bool IsZero(Sema &S, Expr *E) {
4762  // Suppress cases where we are comparing against an enum constant.
4763  if (const DeclRefExpr *DR =
4764      dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
4765    if (isa<EnumConstantDecl>(DR->getDecl()))
4766      return false;
4767
4768  // Suppress cases where the '0' value is expanded from a macro.
4769  if (E->getLocStart().isMacroID())
4770    return false;
4771
4772  llvm::APSInt Value;
4773  return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
4774}
4775
4776static bool HasEnumType(Expr *E) {
4777  // Strip off implicit integral promotions.
4778  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4779    if (ICE->getCastKind() != CK_IntegralCast &&
4780        ICE->getCastKind() != CK_NoOp)
4781      break;
4782    E = ICE->getSubExpr();
4783  }
4784
4785  return E->getType()->isEnumeralType();
4786}
4787
4788static void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
4789  // Disable warning in template instantiations.
4790  if (!S.ActiveTemplateInstantiations.empty())
4791    return;
4792
4793  BinaryOperatorKind op = E->getOpcode();
4794  if (E->isValueDependent())
4795    return;
4796
4797  if (op == BO_LT && IsZero(S, E->getRHS())) {
4798    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4799      << "< 0" << "false" << HasEnumType(E->getLHS())
4800      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4801  } else if (op == BO_GE && IsZero(S, E->getRHS())) {
4802    S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
4803      << ">= 0" << "true" << HasEnumType(E->getLHS())
4804      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4805  } else if (op == BO_GT && IsZero(S, E->getLHS())) {
4806    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4807      << "0 >" << "false" << HasEnumType(E->getRHS())
4808      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4809  } else if (op == BO_LE && IsZero(S, E->getLHS())) {
4810    S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
4811      << "0 <=" << "true" << HasEnumType(E->getRHS())
4812      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4813  }
4814}
4815
4816static void DiagnoseOutOfRangeComparison(Sema &S, BinaryOperator *E,
4817                                         Expr *Constant, Expr *Other,
4818                                         llvm::APSInt Value,
4819                                         bool RhsConstant) {
4820  // Disable warning in template instantiations.
4821  if (!S.ActiveTemplateInstantiations.empty())
4822    return;
4823
4824  // 0 values are handled later by CheckTrivialUnsignedComparison().
4825  if (Value == 0)
4826    return;
4827
4828  BinaryOperatorKind op = E->getOpcode();
4829  QualType OtherT = Other->getType();
4830  QualType ConstantT = Constant->getType();
4831  QualType CommonT = E->getLHS()->getType();
4832  if (S.Context.hasSameUnqualifiedType(OtherT, ConstantT))
4833    return;
4834  assert((OtherT->isIntegerType() && ConstantT->isIntegerType())
4835         && "comparison with non-integer type");
4836
4837  bool ConstantSigned = ConstantT->isSignedIntegerType();
4838  bool CommonSigned = CommonT->isSignedIntegerType();
4839
4840  bool EqualityOnly = false;
4841
4842  // TODO: Investigate using GetExprRange() to get tighter bounds on
4843  // on the bit ranges.
4844  IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT);
4845  unsigned OtherWidth = OtherRange.Width;
4846
4847  if (CommonSigned) {
4848    // The common type is signed, therefore no signed to unsigned conversion.
4849    if (!OtherRange.NonNegative) {
4850      // Check that the constant is representable in type OtherT.
4851      if (ConstantSigned) {
4852        if (OtherWidth >= Value.getMinSignedBits())
4853          return;
4854      } else { // !ConstantSigned
4855        if (OtherWidth >= Value.getActiveBits() + 1)
4856          return;
4857      }
4858    } else { // !OtherSigned
4859      // Check that the constant is representable in type OtherT.
4860      // Negative values are out of range.
4861      if (ConstantSigned) {
4862        if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
4863          return;
4864      } else { // !ConstantSigned
4865        if (OtherWidth >= Value.getActiveBits())
4866          return;
4867      }
4868    }
4869  } else {  // !CommonSigned
4870    if (OtherRange.NonNegative) {
4871      if (OtherWidth >= Value.getActiveBits())
4872        return;
4873    } else if (!OtherRange.NonNegative && !ConstantSigned) {
4874      // Check to see if the constant is representable in OtherT.
4875      if (OtherWidth > Value.getActiveBits())
4876        return;
4877      // Check to see if the constant is equivalent to a negative value
4878      // cast to CommonT.
4879      if (S.Context.getIntWidth(ConstantT) == S.Context.getIntWidth(CommonT) &&
4880          Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
4881        return;
4882      // The constant value rests between values that OtherT can represent after
4883      // conversion.  Relational comparison still works, but equality
4884      // comparisons will be tautological.
4885      EqualityOnly = true;
4886    } else { // OtherSigned && ConstantSigned
4887      assert(0 && "Two signed types converted to unsigned types.");
4888    }
4889  }
4890
4891  bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
4892
4893  bool IsTrue = true;
4894  if (op == BO_EQ || op == BO_NE) {
4895    IsTrue = op == BO_NE;
4896  } else if (EqualityOnly) {
4897    return;
4898  } else if (RhsConstant) {
4899    if (op == BO_GT || op == BO_GE)
4900      IsTrue = !PositiveConstant;
4901    else // op == BO_LT || op == BO_LE
4902      IsTrue = PositiveConstant;
4903  } else {
4904    if (op == BO_LT || op == BO_LE)
4905      IsTrue = !PositiveConstant;
4906    else // op == BO_GT || op == BO_GE
4907      IsTrue = PositiveConstant;
4908  }
4909
4910  // If this is a comparison to an enum constant, include that
4911  // constant in the diagnostic.
4912  const EnumConstantDecl *ED = 0;
4913  if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
4914    ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
4915
4916  SmallString<64> PrettySourceValue;
4917  llvm::raw_svector_ostream OS(PrettySourceValue);
4918  if (ED)
4919    OS << '\'' << *ED << "' (" << Value << ")";
4920  else
4921    OS << Value;
4922
4923  S.Diag(E->getOperatorLoc(), diag::warn_out_of_range_compare)
4924      << OS.str() << OtherT << IsTrue
4925      << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
4926}
4927
4928/// Analyze the operands of the given comparison.  Implements the
4929/// fallback case from AnalyzeComparison.
4930static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
4931  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
4932  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
4933}
4934
4935/// \brief Implements -Wsign-compare.
4936///
4937/// \param E the binary operator to check for warnings
4938static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
4939  // The type the comparison is being performed in.
4940  QualType T = E->getLHS()->getType();
4941  assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
4942         && "comparison with mismatched types");
4943  if (E->isValueDependent())
4944    return AnalyzeImpConvsInComparison(S, E);
4945
4946  Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
4947  Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
4948
4949  bool IsComparisonConstant = false;
4950
4951  // Check whether an integer constant comparison results in a value
4952  // of 'true' or 'false'.
4953  if (T->isIntegralType(S.Context)) {
4954    llvm::APSInt RHSValue;
4955    bool IsRHSIntegralLiteral =
4956      RHS->isIntegerConstantExpr(RHSValue, S.Context);
4957    llvm::APSInt LHSValue;
4958    bool IsLHSIntegralLiteral =
4959      LHS->isIntegerConstantExpr(LHSValue, S.Context);
4960    if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
4961        DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue, true);
4962    else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
4963      DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue, false);
4964    else
4965      IsComparisonConstant =
4966        (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
4967  } else if (!T->hasUnsignedIntegerRepresentation())
4968      IsComparisonConstant = E->isIntegerConstantExpr(S.Context);
4969
4970  // We don't do anything special if this isn't an unsigned integral
4971  // comparison:  we're only interested in integral comparisons, and
4972  // signed comparisons only happen in cases we don't care to warn about.
4973  //
4974  // We also don't care about value-dependent expressions or expressions
4975  // whose result is a constant.
4976  if (!T->hasUnsignedIntegerRepresentation() || IsComparisonConstant)
4977    return AnalyzeImpConvsInComparison(S, E);
4978
4979  // Check to see if one of the (unmodified) operands is of different
4980  // signedness.
4981  Expr *signedOperand, *unsignedOperand;
4982  if (LHS->getType()->hasSignedIntegerRepresentation()) {
4983    assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
4984           "unsigned comparison between two signed integer expressions?");
4985    signedOperand = LHS;
4986    unsignedOperand = RHS;
4987  } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
4988    signedOperand = RHS;
4989    unsignedOperand = LHS;
4990  } else {
4991    CheckTrivialUnsignedComparison(S, E);
4992    return AnalyzeImpConvsInComparison(S, E);
4993  }
4994
4995  // Otherwise, calculate the effective range of the signed operand.
4996  IntRange signedRange = GetExprRange(S.Context, signedOperand);
4997
4998  // Go ahead and analyze implicit conversions in the operands.  Note
4999  // that we skip the implicit conversions on both sides.
5000  AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
5001  AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
5002
5003  // If the signed range is non-negative, -Wsign-compare won't fire,
5004  // but we should still check for comparisons which are always true
5005  // or false.
5006  if (signedRange.NonNegative)
5007    return CheckTrivialUnsignedComparison(S, E);
5008
5009  // For (in)equality comparisons, if the unsigned operand is a
5010  // constant which cannot collide with a overflowed signed operand,
5011  // then reinterpreting the signed operand as unsigned will not
5012  // change the result of the comparison.
5013  if (E->isEqualityOp()) {
5014    unsigned comparisonWidth = S.Context.getIntWidth(T);
5015    IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
5016
5017    // We should never be unable to prove that the unsigned operand is
5018    // non-negative.
5019    assert(unsignedRange.NonNegative && "unsigned range includes negative?");
5020
5021    if (unsignedRange.Width < comparisonWidth)
5022      return;
5023  }
5024
5025  S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
5026    S.PDiag(diag::warn_mixed_sign_comparison)
5027      << LHS->getType() << RHS->getType()
5028      << LHS->getSourceRange() << RHS->getSourceRange());
5029}
5030
5031/// Analyzes an attempt to assign the given value to a bitfield.
5032///
5033/// Returns true if there was something fishy about the attempt.
5034static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
5035                                      SourceLocation InitLoc) {
5036  assert(Bitfield->isBitField());
5037  if (Bitfield->isInvalidDecl())
5038    return false;
5039
5040  // White-list bool bitfields.
5041  if (Bitfield->getType()->isBooleanType())
5042    return false;
5043
5044  // Ignore value- or type-dependent expressions.
5045  if (Bitfield->getBitWidth()->isValueDependent() ||
5046      Bitfield->getBitWidth()->isTypeDependent() ||
5047      Init->isValueDependent() ||
5048      Init->isTypeDependent())
5049    return false;
5050
5051  Expr *OriginalInit = Init->IgnoreParenImpCasts();
5052
5053  llvm::APSInt Value;
5054  if (!OriginalInit->EvaluateAsInt(Value, S.Context, Expr::SE_AllowSideEffects))
5055    return false;
5056
5057  unsigned OriginalWidth = Value.getBitWidth();
5058  unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
5059
5060  if (OriginalWidth <= FieldWidth)
5061    return false;
5062
5063  // Compute the value which the bitfield will contain.
5064  llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
5065  TruncatedValue.setIsSigned(Bitfield->getType()->isSignedIntegerType());
5066
5067  // Check whether the stored value is equal to the original value.
5068  TruncatedValue = TruncatedValue.extend(OriginalWidth);
5069  if (llvm::APSInt::isSameValue(Value, TruncatedValue))
5070    return false;
5071
5072  // Special-case bitfields of width 1: booleans are naturally 0/1, and
5073  // therefore don't strictly fit into a signed bitfield of width 1.
5074  if (FieldWidth == 1 && Value == 1)
5075    return false;
5076
5077  std::string PrettyValue = Value.toString(10);
5078  std::string PrettyTrunc = TruncatedValue.toString(10);
5079
5080  S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
5081    << PrettyValue << PrettyTrunc << OriginalInit->getType()
5082    << Init->getSourceRange();
5083
5084  return true;
5085}
5086
5087/// Analyze the given simple or compound assignment for warning-worthy
5088/// operations.
5089static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
5090  // Just recurse on the LHS.
5091  AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
5092
5093  // We want to recurse on the RHS as normal unless we're assigning to
5094  // a bitfield.
5095  if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
5096    if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
5097                                  E->getOperatorLoc())) {
5098      // Recurse, ignoring any implicit conversions on the RHS.
5099      return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
5100                                        E->getOperatorLoc());
5101    }
5102  }
5103
5104  AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
5105}
5106
5107/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5108static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
5109                            SourceLocation CContext, unsigned diag,
5110                            bool pruneControlFlow = false) {
5111  if (pruneControlFlow) {
5112    S.DiagRuntimeBehavior(E->getExprLoc(), E,
5113                          S.PDiag(diag)
5114                            << SourceType << T << E->getSourceRange()
5115                            << SourceRange(CContext));
5116    return;
5117  }
5118  S.Diag(E->getExprLoc(), diag)
5119    << SourceType << T << E->getSourceRange() << SourceRange(CContext);
5120}
5121
5122/// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
5123static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
5124                            SourceLocation CContext, unsigned diag,
5125                            bool pruneControlFlow = false) {
5126  DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
5127}
5128
5129/// Diagnose an implicit cast from a literal expression. Does not warn when the
5130/// cast wouldn't lose information.
5131void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
5132                                    SourceLocation CContext) {
5133  // Try to convert the literal exactly to an integer. If we can, don't warn.
5134  bool isExact = false;
5135  const llvm::APFloat &Value = FL->getValue();
5136  llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
5137                            T->hasUnsignedIntegerRepresentation());
5138  if (Value.convertToInteger(IntegerValue,
5139                             llvm::APFloat::rmTowardZero, &isExact)
5140      == llvm::APFloat::opOK && isExact)
5141    return;
5142
5143  // FIXME: Force the precision of the source value down so we don't print
5144  // digits which are usually useless (we don't really care here if we
5145  // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
5146  // would automatically print the shortest representation, but it's a bit
5147  // tricky to implement.
5148  SmallString<16> PrettySourceValue;
5149  unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
5150  precision = (precision * 59 + 195) / 196;
5151  Value.toString(PrettySourceValue, precision);
5152
5153  SmallString<16> PrettyTargetValue;
5154  if (T->isSpecificBuiltinType(BuiltinType::Bool))
5155    PrettyTargetValue = IntegerValue == 0 ? "false" : "true";
5156  else
5157    IntegerValue.toString(PrettyTargetValue);
5158
5159  S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
5160    << FL->getType() << T.getUnqualifiedType() << PrettySourceValue
5161    << PrettyTargetValue << FL->getSourceRange() << SourceRange(CContext);
5162}
5163
5164std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
5165  if (!Range.Width) return "0";
5166
5167  llvm::APSInt ValueInRange = Value;
5168  ValueInRange.setIsSigned(!Range.NonNegative);
5169  ValueInRange = ValueInRange.trunc(Range.Width);
5170  return ValueInRange.toString(10);
5171}
5172
5173static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
5174  if (!isa<ImplicitCastExpr>(Ex))
5175    return false;
5176
5177  Expr *InnerE = Ex->IgnoreParenImpCasts();
5178  const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
5179  const Type *Source =
5180    S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5181  if (Target->isDependentType())
5182    return false;
5183
5184  const BuiltinType *FloatCandidateBT =
5185    dyn_cast<BuiltinType>(ToBool ? Source : Target);
5186  const Type *BoolCandidateType = ToBool ? Target : Source;
5187
5188  return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
5189          FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
5190}
5191
5192void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
5193                                      SourceLocation CC) {
5194  unsigned NumArgs = TheCall->getNumArgs();
5195  for (unsigned i = 0; i < NumArgs; ++i) {
5196    Expr *CurrA = TheCall->getArg(i);
5197    if (!IsImplicitBoolFloatConversion(S, CurrA, true))
5198      continue;
5199
5200    bool IsSwapped = ((i > 0) &&
5201        IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
5202    IsSwapped |= ((i < (NumArgs - 1)) &&
5203        IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
5204    if (IsSwapped) {
5205      // Warn on this floating-point to bool conversion.
5206      DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
5207                      CurrA->getType(), CC,
5208                      diag::warn_impcast_floating_point_to_bool);
5209    }
5210  }
5211}
5212
5213void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
5214                             SourceLocation CC, bool *ICContext = 0) {
5215  if (E->isTypeDependent() || E->isValueDependent()) return;
5216
5217  const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
5218  const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
5219  if (Source == Target) return;
5220  if (Target->isDependentType()) return;
5221
5222  // If the conversion context location is invalid don't complain. We also
5223  // don't want to emit a warning if the issue occurs from the expansion of
5224  // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
5225  // delay this check as long as possible. Once we detect we are in that
5226  // scenario, we just return.
5227  if (CC.isInvalid())
5228    return;
5229
5230  // Diagnose implicit casts to bool.
5231  if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
5232    if (isa<StringLiteral>(E))
5233      // Warn on string literal to bool.  Checks for string literals in logical
5234      // expressions, for instances, assert(0 && "error here"), is prevented
5235      // by a check in AnalyzeImplicitConversions().
5236      return DiagnoseImpCast(S, E, T, CC,
5237                             diag::warn_impcast_string_literal_to_bool);
5238    if (Source->isFunctionType()) {
5239      // Warn on function to bool. Checks free functions and static member
5240      // functions. Weakly imported functions are excluded from the check,
5241      // since it's common to test their value to check whether the linker
5242      // found a definition for them.
5243      ValueDecl *D = 0;
5244      if (DeclRefExpr* R = dyn_cast<DeclRefExpr>(E)) {
5245        D = R->getDecl();
5246      } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
5247        D = M->getMemberDecl();
5248      }
5249
5250      if (D && !D->isWeak()) {
5251        if (FunctionDecl* F = dyn_cast<FunctionDecl>(D)) {
5252          S.Diag(E->getExprLoc(), diag::warn_impcast_function_to_bool)
5253            << F << E->getSourceRange() << SourceRange(CC);
5254          S.Diag(E->getExprLoc(), diag::note_function_to_bool_silence)
5255            << FixItHint::CreateInsertion(E->getExprLoc(), "&");
5256          QualType ReturnType;
5257          UnresolvedSet<4> NonTemplateOverloads;
5258          S.tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
5259          if (!ReturnType.isNull()
5260              && ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
5261            S.Diag(E->getExprLoc(), diag::note_function_to_bool_call)
5262              << FixItHint::CreateInsertion(
5263                 S.getPreprocessor().getLocForEndOfToken(E->getLocEnd()), "()");
5264          return;
5265        }
5266      }
5267    }
5268  }
5269
5270  // Strip vector types.
5271  if (isa<VectorType>(Source)) {
5272    if (!isa<VectorType>(Target)) {
5273      if (S.SourceMgr.isInSystemMacro(CC))
5274        return;
5275      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
5276    }
5277
5278    // If the vector cast is cast between two vectors of the same size, it is
5279    // a bitcast, not a conversion.
5280    if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
5281      return;
5282
5283    Source = cast<VectorType>(Source)->getElementType().getTypePtr();
5284    Target = cast<VectorType>(Target)->getElementType().getTypePtr();
5285  }
5286
5287  // Strip complex types.
5288  if (isa<ComplexType>(Source)) {
5289    if (!isa<ComplexType>(Target)) {
5290      if (S.SourceMgr.isInSystemMacro(CC))
5291        return;
5292
5293      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
5294    }
5295
5296    Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
5297    Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
5298  }
5299
5300  const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
5301  const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
5302
5303  // If the source is floating point...
5304  if (SourceBT && SourceBT->isFloatingPoint()) {
5305    // ...and the target is floating point...
5306    if (TargetBT && TargetBT->isFloatingPoint()) {
5307      // ...then warn if we're dropping FP rank.
5308
5309      // Builtin FP kinds are ordered by increasing FP rank.
5310      if (SourceBT->getKind() > TargetBT->getKind()) {
5311        // Don't warn about float constants that are precisely
5312        // representable in the target type.
5313        Expr::EvalResult result;
5314        if (E->EvaluateAsRValue(result, S.Context)) {
5315          // Value might be a float, a float vector, or a float complex.
5316          if (IsSameFloatAfterCast(result.Val,
5317                   S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
5318                   S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
5319            return;
5320        }
5321
5322        if (S.SourceMgr.isInSystemMacro(CC))
5323          return;
5324
5325        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
5326      }
5327      return;
5328    }
5329
5330    // If the target is integral, always warn.
5331    if (TargetBT && TargetBT->isInteger()) {
5332      if (S.SourceMgr.isInSystemMacro(CC))
5333        return;
5334
5335      Expr *InnerE = E->IgnoreParenImpCasts();
5336      // We also want to warn on, e.g., "int i = -1.234"
5337      if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
5338        if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
5339          InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
5340
5341      if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
5342        DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
5343      } else {
5344        DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
5345      }
5346    }
5347
5348    // If the target is bool, warn if expr is a function or method call.
5349    if (Target->isSpecificBuiltinType(BuiltinType::Bool) &&
5350        isa<CallExpr>(E)) {
5351      // Check last argument of function call to see if it is an
5352      // implicit cast from a type matching the type the result
5353      // is being cast to.
5354      CallExpr *CEx = cast<CallExpr>(E);
5355      unsigned NumArgs = CEx->getNumArgs();
5356      if (NumArgs > 0) {
5357        Expr *LastA = CEx->getArg(NumArgs - 1);
5358        Expr *InnerE = LastA->IgnoreParenImpCasts();
5359        const Type *InnerType =
5360          S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
5361        if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
5362          // Warn on this floating-point to bool conversion
5363          DiagnoseImpCast(S, E, T, CC,
5364                          diag::warn_impcast_floating_point_to_bool);
5365        }
5366      }
5367    }
5368    return;
5369  }
5370
5371  if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
5372           == Expr::NPCK_GNUNull) && !Target->isAnyPointerType()
5373      && !Target->isBlockPointerType() && !Target->isMemberPointerType()
5374      && Target->isScalarType() && !Target->isNullPtrType()) {
5375    SourceLocation Loc = E->getSourceRange().getBegin();
5376    if (Loc.isMacroID())
5377      Loc = S.SourceMgr.getImmediateExpansionRange(Loc).first;
5378    if (!Loc.isMacroID() || CC.isMacroID())
5379      S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
5380          << T << clang::SourceRange(CC)
5381          << FixItHint::CreateReplacement(Loc,
5382                                          S.getFixItZeroLiteralForType(T, Loc));
5383  }
5384
5385  if (!Source->isIntegerType() || !Target->isIntegerType())
5386    return;
5387
5388  // TODO: remove this early return once the false positives for constant->bool
5389  // in templates, macros, etc, are reduced or removed.
5390  if (Target->isSpecificBuiltinType(BuiltinType::Bool))
5391    return;
5392
5393  IntRange SourceRange = GetExprRange(S.Context, E);
5394  IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
5395
5396  if (SourceRange.Width > TargetRange.Width) {
5397    // If the source is a constant, use a default-on diagnostic.
5398    // TODO: this should happen for bitfield stores, too.
5399    llvm::APSInt Value(32);
5400    if (E->isIntegerConstantExpr(Value, S.Context)) {
5401      if (S.SourceMgr.isInSystemMacro(CC))
5402        return;
5403
5404      std::string PrettySourceValue = Value.toString(10);
5405      std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
5406
5407      S.DiagRuntimeBehavior(E->getExprLoc(), E,
5408        S.PDiag(diag::warn_impcast_integer_precision_constant)
5409            << PrettySourceValue << PrettyTargetValue
5410            << E->getType() << T << E->getSourceRange()
5411            << clang::SourceRange(CC));
5412      return;
5413    }
5414
5415    // People want to build with -Wshorten-64-to-32 and not -Wconversion.
5416    if (S.SourceMgr.isInSystemMacro(CC))
5417      return;
5418
5419    if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
5420      return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
5421                             /* pruneControlFlow */ true);
5422    return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
5423  }
5424
5425  if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
5426      (!TargetRange.NonNegative && SourceRange.NonNegative &&
5427       SourceRange.Width == TargetRange.Width)) {
5428
5429    if (S.SourceMgr.isInSystemMacro(CC))
5430      return;
5431
5432    unsigned DiagID = diag::warn_impcast_integer_sign;
5433
5434    // Traditionally, gcc has warned about this under -Wsign-compare.
5435    // We also want to warn about it in -Wconversion.
5436    // So if -Wconversion is off, use a completely identical diagnostic
5437    // in the sign-compare group.
5438    // The conditional-checking code will
5439    if (ICContext) {
5440      DiagID = diag::warn_impcast_integer_sign_conditional;
5441      *ICContext = true;
5442    }
5443
5444    return DiagnoseImpCast(S, E, T, CC, DiagID);
5445  }
5446
5447  // Diagnose conversions between different enumeration types.
5448  // In C, we pretend that the type of an EnumConstantDecl is its enumeration
5449  // type, to give us better diagnostics.
5450  QualType SourceType = E->getType();
5451  if (!S.getLangOpts().CPlusPlus) {
5452    if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5453      if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
5454        EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
5455        SourceType = S.Context.getTypeDeclType(Enum);
5456        Source = S.Context.getCanonicalType(SourceType).getTypePtr();
5457      }
5458  }
5459
5460  if (const EnumType *SourceEnum = Source->getAs<EnumType>())
5461    if (const EnumType *TargetEnum = Target->getAs<EnumType>())
5462      if (SourceEnum->getDecl()->hasNameForLinkage() &&
5463          TargetEnum->getDecl()->hasNameForLinkage() &&
5464          SourceEnum != TargetEnum) {
5465        if (S.SourceMgr.isInSystemMacro(CC))
5466          return;
5467
5468        return DiagnoseImpCast(S, E, SourceType, T, CC,
5469                               diag::warn_impcast_different_enum_types);
5470      }
5471
5472  return;
5473}
5474
5475void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5476                              SourceLocation CC, QualType T);
5477
5478void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
5479                             SourceLocation CC, bool &ICContext) {
5480  E = E->IgnoreParenImpCasts();
5481
5482  if (isa<ConditionalOperator>(E))
5483    return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
5484
5485  AnalyzeImplicitConversions(S, E, CC);
5486  if (E->getType() != T)
5487    return CheckImplicitConversion(S, E, T, CC, &ICContext);
5488  return;
5489}
5490
5491void CheckConditionalOperator(Sema &S, ConditionalOperator *E,
5492                              SourceLocation CC, QualType T) {
5493  AnalyzeImplicitConversions(S, E->getCond(), CC);
5494
5495  bool Suspicious = false;
5496  CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
5497  CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
5498
5499  // If -Wconversion would have warned about either of the candidates
5500  // for a signedness conversion to the context type...
5501  if (!Suspicious) return;
5502
5503  // ...but it's currently ignored...
5504  if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
5505                                 CC))
5506    return;
5507
5508  // ...then check whether it would have warned about either of the
5509  // candidates for a signedness conversion to the condition type.
5510  if (E->getType() == T) return;
5511
5512  Suspicious = false;
5513  CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
5514                          E->getType(), CC, &Suspicious);
5515  if (!Suspicious)
5516    CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
5517                            E->getType(), CC, &Suspicious);
5518}
5519
5520/// AnalyzeImplicitConversions - Find and report any interesting
5521/// implicit conversions in the given expression.  There are a couple
5522/// of competing diagnostics here, -Wconversion and -Wsign-compare.
5523void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
5524  QualType T = OrigE->getType();
5525  Expr *E = OrigE->IgnoreParenImpCasts();
5526
5527  if (E->isTypeDependent() || E->isValueDependent())
5528    return;
5529
5530  // For conditional operators, we analyze the arguments as if they
5531  // were being fed directly into the output.
5532  if (isa<ConditionalOperator>(E)) {
5533    ConditionalOperator *CO = cast<ConditionalOperator>(E);
5534    CheckConditionalOperator(S, CO, CC, T);
5535    return;
5536  }
5537
5538  // Check implicit argument conversions for function calls.
5539  if (CallExpr *Call = dyn_cast<CallExpr>(E))
5540    CheckImplicitArgumentConversions(S, Call, CC);
5541
5542  // Go ahead and check any implicit conversions we might have skipped.
5543  // The non-canonical typecheck is just an optimization;
5544  // CheckImplicitConversion will filter out dead implicit conversions.
5545  if (E->getType() != T)
5546    CheckImplicitConversion(S, E, T, CC);
5547
5548  // Now continue drilling into this expression.
5549
5550  if (PseudoObjectExpr * POE = dyn_cast<PseudoObjectExpr>(E)) {
5551    if (POE->getResultExpr())
5552      E = POE->getResultExpr();
5553  }
5554
5555  if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E))
5556    return AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
5557
5558  // Skip past explicit casts.
5559  if (isa<ExplicitCastExpr>(E)) {
5560    E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
5561    return AnalyzeImplicitConversions(S, E, CC);
5562  }
5563
5564  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5565    // Do a somewhat different check with comparison operators.
5566    if (BO->isComparisonOp())
5567      return AnalyzeComparison(S, BO);
5568
5569    // And with simple assignments.
5570    if (BO->getOpcode() == BO_Assign)
5571      return AnalyzeAssignment(S, BO);
5572  }
5573
5574  // These break the otherwise-useful invariant below.  Fortunately,
5575  // we don't really need to recurse into them, because any internal
5576  // expressions should have been analyzed already when they were
5577  // built into statements.
5578  if (isa<StmtExpr>(E)) return;
5579
5580  // Don't descend into unevaluated contexts.
5581  if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
5582
5583  // Now just recurse over the expression's children.
5584  CC = E->getExprLoc();
5585  BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
5586  bool IsLogicalOperator = BO && BO->isLogicalOp();
5587  for (Stmt::child_range I = E->children(); I; ++I) {
5588    Expr *ChildExpr = dyn_cast_or_null<Expr>(*I);
5589    if (!ChildExpr)
5590      continue;
5591
5592    if (IsLogicalOperator &&
5593        isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
5594      // Ignore checking string literals that are in logical operators.
5595      continue;
5596    AnalyzeImplicitConversions(S, ChildExpr, CC);
5597  }
5598}
5599
5600} // end anonymous namespace
5601
5602/// Diagnoses "dangerous" implicit conversions within the given
5603/// expression (which is a full expression).  Implements -Wconversion
5604/// and -Wsign-compare.
5605///
5606/// \param CC the "context" location of the implicit conversion, i.e.
5607///   the most location of the syntactic entity requiring the implicit
5608///   conversion
5609void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
5610  // Don't diagnose in unevaluated contexts.
5611  if (isUnevaluatedContext())
5612    return;
5613
5614  // Don't diagnose for value- or type-dependent expressions.
5615  if (E->isTypeDependent() || E->isValueDependent())
5616    return;
5617
5618  // Check for array bounds violations in cases where the check isn't triggered
5619  // elsewhere for other Expr types (like BinaryOperators), e.g. when an
5620  // ArraySubscriptExpr is on the RHS of a variable initialization.
5621  CheckArrayAccess(E);
5622
5623  // This is not the right CC for (e.g.) a variable initialization.
5624  AnalyzeImplicitConversions(*this, E, CC);
5625}
5626
5627/// Diagnose when expression is an integer constant expression and its evaluation
5628/// results in integer overflow
5629void Sema::CheckForIntOverflow (Expr *E) {
5630  if (isa<BinaryOperator>(E->IgnoreParens()))
5631    E->EvaluateForOverflow(Context);
5632}
5633
5634namespace {
5635/// \brief Visitor for expressions which looks for unsequenced operations on the
5636/// same object.
5637class SequenceChecker : public EvaluatedExprVisitor<SequenceChecker> {
5638  typedef EvaluatedExprVisitor<SequenceChecker> Base;
5639
5640  /// \brief A tree of sequenced regions within an expression. Two regions are
5641  /// unsequenced if one is an ancestor or a descendent of the other. When we
5642  /// finish processing an expression with sequencing, such as a comma
5643  /// expression, we fold its tree nodes into its parent, since they are
5644  /// unsequenced with respect to nodes we will visit later.
5645  class SequenceTree {
5646    struct Value {
5647      explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
5648      unsigned Parent : 31;
5649      bool Merged : 1;
5650    };
5651    SmallVector<Value, 8> Values;
5652
5653  public:
5654    /// \brief A region within an expression which may be sequenced with respect
5655    /// to some other region.
5656    class Seq {
5657      explicit Seq(unsigned N) : Index(N) {}
5658      unsigned Index;
5659      friend class SequenceTree;
5660    public:
5661      Seq() : Index(0) {}
5662    };
5663
5664    SequenceTree() { Values.push_back(Value(0)); }
5665    Seq root() const { return Seq(0); }
5666
5667    /// \brief Create a new sequence of operations, which is an unsequenced
5668    /// subset of \p Parent. This sequence of operations is sequenced with
5669    /// respect to other children of \p Parent.
5670    Seq allocate(Seq Parent) {
5671      Values.push_back(Value(Parent.Index));
5672      return Seq(Values.size() - 1);
5673    }
5674
5675    /// \brief Merge a sequence of operations into its parent.
5676    void merge(Seq S) {
5677      Values[S.Index].Merged = true;
5678    }
5679
5680    /// \brief Determine whether two operations are unsequenced. This operation
5681    /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
5682    /// should have been merged into its parent as appropriate.
5683    bool isUnsequenced(Seq Cur, Seq Old) {
5684      unsigned C = representative(Cur.Index);
5685      unsigned Target = representative(Old.Index);
5686      while (C >= Target) {
5687        if (C == Target)
5688          return true;
5689        C = Values[C].Parent;
5690      }
5691      return false;
5692    }
5693
5694  private:
5695    /// \brief Pick a representative for a sequence.
5696    unsigned representative(unsigned K) {
5697      if (Values[K].Merged)
5698        // Perform path compression as we go.
5699        return Values[K].Parent = representative(Values[K].Parent);
5700      return K;
5701    }
5702  };
5703
5704  /// An object for which we can track unsequenced uses.
5705  typedef NamedDecl *Object;
5706
5707  /// Different flavors of object usage which we track. We only track the
5708  /// least-sequenced usage of each kind.
5709  enum UsageKind {
5710    /// A read of an object. Multiple unsequenced reads are OK.
5711    UK_Use,
5712    /// A modification of an object which is sequenced before the value
5713    /// computation of the expression, such as ++n in C++.
5714    UK_ModAsValue,
5715    /// A modification of an object which is not sequenced before the value
5716    /// computation of the expression, such as n++.
5717    UK_ModAsSideEffect,
5718
5719    UK_Count = UK_ModAsSideEffect + 1
5720  };
5721
5722  struct Usage {
5723    Usage() : Use(0), Seq() {}
5724    Expr *Use;
5725    SequenceTree::Seq Seq;
5726  };
5727
5728  struct UsageInfo {
5729    UsageInfo() : Diagnosed(false) {}
5730    Usage Uses[UK_Count];
5731    /// Have we issued a diagnostic for this variable already?
5732    bool Diagnosed;
5733  };
5734  typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
5735
5736  Sema &SemaRef;
5737  /// Sequenced regions within the expression.
5738  SequenceTree Tree;
5739  /// Declaration modifications and references which we have seen.
5740  UsageInfoMap UsageMap;
5741  /// The region we are currently within.
5742  SequenceTree::Seq Region;
5743  /// Filled in with declarations which were modified as a side-effect
5744  /// (that is, post-increment operations).
5745  SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
5746  /// Expressions to check later. We defer checking these to reduce
5747  /// stack usage.
5748  SmallVectorImpl<Expr *> &WorkList;
5749
5750  /// RAII object wrapping the visitation of a sequenced subexpression of an
5751  /// expression. At the end of this process, the side-effects of the evaluation
5752  /// become sequenced with respect to the value computation of the result, so
5753  /// we downgrade any UK_ModAsSideEffect within the evaluation to
5754  /// UK_ModAsValue.
5755  struct SequencedSubexpression {
5756    SequencedSubexpression(SequenceChecker &Self)
5757      : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
5758      Self.ModAsSideEffect = &ModAsSideEffect;
5759    }
5760    ~SequencedSubexpression() {
5761      for (unsigned I = 0, E = ModAsSideEffect.size(); I != E; ++I) {
5762        UsageInfo &U = Self.UsageMap[ModAsSideEffect[I].first];
5763        U.Uses[UK_ModAsSideEffect] = ModAsSideEffect[I].second;
5764        Self.addUsage(U, ModAsSideEffect[I].first,
5765                      ModAsSideEffect[I].second.Use, UK_ModAsValue);
5766      }
5767      Self.ModAsSideEffect = OldModAsSideEffect;
5768    }
5769
5770    SequenceChecker &Self;
5771    SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
5772    SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
5773  };
5774
5775  /// RAII object wrapping the visitation of a subexpression which we might
5776  /// choose to evaluate as a constant. If any subexpression is evaluated and
5777  /// found to be non-constant, this allows us to suppress the evaluation of
5778  /// the outer expression.
5779  class EvaluationTracker {
5780  public:
5781    EvaluationTracker(SequenceChecker &Self)
5782        : Self(Self), Prev(Self.EvalTracker), EvalOK(true) {
5783      Self.EvalTracker = this;
5784    }
5785    ~EvaluationTracker() {
5786      Self.EvalTracker = Prev;
5787      if (Prev)
5788        Prev->EvalOK &= EvalOK;
5789    }
5790
5791    bool evaluate(const Expr *E, bool &Result) {
5792      if (!EvalOK || E->isValueDependent())
5793        return false;
5794      EvalOK = E->EvaluateAsBooleanCondition(Result, Self.SemaRef.Context);
5795      return EvalOK;
5796    }
5797
5798  private:
5799    SequenceChecker &Self;
5800    EvaluationTracker *Prev;
5801    bool EvalOK;
5802  } *EvalTracker;
5803
5804  /// \brief Find the object which is produced by the specified expression,
5805  /// if any.
5806  Object getObject(Expr *E, bool Mod) const {
5807    E = E->IgnoreParenCasts();
5808    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
5809      if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
5810        return getObject(UO->getSubExpr(), Mod);
5811    } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5812      if (BO->getOpcode() == BO_Comma)
5813        return getObject(BO->getRHS(), Mod);
5814      if (Mod && BO->isAssignmentOp())
5815        return getObject(BO->getLHS(), Mod);
5816    } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5817      // FIXME: Check for more interesting cases, like "x.n = ++x.n".
5818      if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
5819        return ME->getMemberDecl();
5820    } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5821      // FIXME: If this is a reference, map through to its value.
5822      return DRE->getDecl();
5823    return 0;
5824  }
5825
5826  /// \brief Note that an object was modified or used by an expression.
5827  void addUsage(UsageInfo &UI, Object O, Expr *Ref, UsageKind UK) {
5828    Usage &U = UI.Uses[UK];
5829    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
5830      if (UK == UK_ModAsSideEffect && ModAsSideEffect)
5831        ModAsSideEffect->push_back(std::make_pair(O, U));
5832      U.Use = Ref;
5833      U.Seq = Region;
5834    }
5835  }
5836  /// \brief Check whether a modification or use conflicts with a prior usage.
5837  void checkUsage(Object O, UsageInfo &UI, Expr *Ref, UsageKind OtherKind,
5838                  bool IsModMod) {
5839    if (UI.Diagnosed)
5840      return;
5841
5842    const Usage &U = UI.Uses[OtherKind];
5843    if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
5844      return;
5845
5846    Expr *Mod = U.Use;
5847    Expr *ModOrUse = Ref;
5848    if (OtherKind == UK_Use)
5849      std::swap(Mod, ModOrUse);
5850
5851    SemaRef.Diag(Mod->getExprLoc(),
5852                 IsModMod ? diag::warn_unsequenced_mod_mod
5853                          : diag::warn_unsequenced_mod_use)
5854      << O << SourceRange(ModOrUse->getExprLoc());
5855    UI.Diagnosed = true;
5856  }
5857
5858  void notePreUse(Object O, Expr *Use) {
5859    UsageInfo &U = UsageMap[O];
5860    // Uses conflict with other modifications.
5861    checkUsage(O, U, Use, UK_ModAsValue, false);
5862  }
5863  void notePostUse(Object O, Expr *Use) {
5864    UsageInfo &U = UsageMap[O];
5865    checkUsage(O, U, Use, UK_ModAsSideEffect, false);
5866    addUsage(U, O, Use, UK_Use);
5867  }
5868
5869  void notePreMod(Object O, Expr *Mod) {
5870    UsageInfo &U = UsageMap[O];
5871    // Modifications conflict with other modifications and with uses.
5872    checkUsage(O, U, Mod, UK_ModAsValue, true);
5873    checkUsage(O, U, Mod, UK_Use, false);
5874  }
5875  void notePostMod(Object O, Expr *Use, UsageKind UK) {
5876    UsageInfo &U = UsageMap[O];
5877    checkUsage(O, U, Use, UK_ModAsSideEffect, true);
5878    addUsage(U, O, Use, UK);
5879  }
5880
5881public:
5882  SequenceChecker(Sema &S, Expr *E, SmallVectorImpl<Expr *> &WorkList)
5883      : Base(S.Context), SemaRef(S), Region(Tree.root()), ModAsSideEffect(0),
5884        WorkList(WorkList), EvalTracker(0) {
5885    Visit(E);
5886  }
5887
5888  void VisitStmt(Stmt *S) {
5889    // Skip all statements which aren't expressions for now.
5890  }
5891
5892  void VisitExpr(Expr *E) {
5893    // By default, just recurse to evaluated subexpressions.
5894    Base::VisitStmt(E);
5895  }
5896
5897  void VisitCastExpr(CastExpr *E) {
5898    Object O = Object();
5899    if (E->getCastKind() == CK_LValueToRValue)
5900      O = getObject(E->getSubExpr(), false);
5901
5902    if (O)
5903      notePreUse(O, E);
5904    VisitExpr(E);
5905    if (O)
5906      notePostUse(O, E);
5907  }
5908
5909  void VisitBinComma(BinaryOperator *BO) {
5910    // C++11 [expr.comma]p1:
5911    //   Every value computation and side effect associated with the left
5912    //   expression is sequenced before every value computation and side
5913    //   effect associated with the right expression.
5914    SequenceTree::Seq LHS = Tree.allocate(Region);
5915    SequenceTree::Seq RHS = Tree.allocate(Region);
5916    SequenceTree::Seq OldRegion = Region;
5917
5918    {
5919      SequencedSubexpression SeqLHS(*this);
5920      Region = LHS;
5921      Visit(BO->getLHS());
5922    }
5923
5924    Region = RHS;
5925    Visit(BO->getRHS());
5926
5927    Region = OldRegion;
5928
5929    // Forget that LHS and RHS are sequenced. They are both unsequenced
5930    // with respect to other stuff.
5931    Tree.merge(LHS);
5932    Tree.merge(RHS);
5933  }
5934
5935  void VisitBinAssign(BinaryOperator *BO) {
5936    // The modification is sequenced after the value computation of the LHS
5937    // and RHS, so check it before inspecting the operands and update the
5938    // map afterwards.
5939    Object O = getObject(BO->getLHS(), true);
5940    if (!O)
5941      return VisitExpr(BO);
5942
5943    notePreMod(O, BO);
5944
5945    // C++11 [expr.ass]p7:
5946    //   E1 op= E2 is equivalent to E1 = E1 op E2, except that E1 is evaluated
5947    //   only once.
5948    //
5949    // Therefore, for a compound assignment operator, O is considered used
5950    // everywhere except within the evaluation of E1 itself.
5951    if (isa<CompoundAssignOperator>(BO))
5952      notePreUse(O, BO);
5953
5954    Visit(BO->getLHS());
5955
5956    if (isa<CompoundAssignOperator>(BO))
5957      notePostUse(O, BO);
5958
5959    Visit(BO->getRHS());
5960
5961    // C++11 [expr.ass]p1:
5962    //   the assignment is sequenced [...] before the value computation of the
5963    //   assignment expression.
5964    // C11 6.5.16/3 has no such rule.
5965    notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5966                                                       : UK_ModAsSideEffect);
5967  }
5968  void VisitCompoundAssignOperator(CompoundAssignOperator *CAO) {
5969    VisitBinAssign(CAO);
5970  }
5971
5972  void VisitUnaryPreInc(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5973  void VisitUnaryPreDec(UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
5974  void VisitUnaryPreIncDec(UnaryOperator *UO) {
5975    Object O = getObject(UO->getSubExpr(), true);
5976    if (!O)
5977      return VisitExpr(UO);
5978
5979    notePreMod(O, UO);
5980    Visit(UO->getSubExpr());
5981    // C++11 [expr.pre.incr]p1:
5982    //   the expression ++x is equivalent to x+=1
5983    notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
5984                                                       : UK_ModAsSideEffect);
5985  }
5986
5987  void VisitUnaryPostInc(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5988  void VisitUnaryPostDec(UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
5989  void VisitUnaryPostIncDec(UnaryOperator *UO) {
5990    Object O = getObject(UO->getSubExpr(), true);
5991    if (!O)
5992      return VisitExpr(UO);
5993
5994    notePreMod(O, UO);
5995    Visit(UO->getSubExpr());
5996    notePostMod(O, UO, UK_ModAsSideEffect);
5997  }
5998
5999  /// Don't visit the RHS of '&&' or '||' if it might not be evaluated.
6000  void VisitBinLOr(BinaryOperator *BO) {
6001    // The side-effects of the LHS of an '&&' are sequenced before the
6002    // value computation of the RHS, and hence before the value computation
6003    // of the '&&' itself, unless the LHS evaluates to zero. We treat them
6004    // as if they were unconditionally sequenced.
6005    EvaluationTracker Eval(*this);
6006    {
6007      SequencedSubexpression Sequenced(*this);
6008      Visit(BO->getLHS());
6009    }
6010
6011    bool Result;
6012    if (Eval.evaluate(BO->getLHS(), Result)) {
6013      if (!Result)
6014        Visit(BO->getRHS());
6015    } else {
6016      // Check for unsequenced operations in the RHS, treating it as an
6017      // entirely separate evaluation.
6018      //
6019      // FIXME: If there are operations in the RHS which are unsequenced
6020      // with respect to operations outside the RHS, and those operations
6021      // are unconditionally evaluated, diagnose them.
6022      WorkList.push_back(BO->getRHS());
6023    }
6024  }
6025  void VisitBinLAnd(BinaryOperator *BO) {
6026    EvaluationTracker Eval(*this);
6027    {
6028      SequencedSubexpression Sequenced(*this);
6029      Visit(BO->getLHS());
6030    }
6031
6032    bool Result;
6033    if (Eval.evaluate(BO->getLHS(), Result)) {
6034      if (Result)
6035        Visit(BO->getRHS());
6036    } else {
6037      WorkList.push_back(BO->getRHS());
6038    }
6039  }
6040
6041  // Only visit the condition, unless we can be sure which subexpression will
6042  // be chosen.
6043  void VisitAbstractConditionalOperator(AbstractConditionalOperator *CO) {
6044    EvaluationTracker Eval(*this);
6045    {
6046      SequencedSubexpression Sequenced(*this);
6047      Visit(CO->getCond());
6048    }
6049
6050    bool Result;
6051    if (Eval.evaluate(CO->getCond(), Result))
6052      Visit(Result ? CO->getTrueExpr() : CO->getFalseExpr());
6053    else {
6054      WorkList.push_back(CO->getTrueExpr());
6055      WorkList.push_back(CO->getFalseExpr());
6056    }
6057  }
6058
6059  void VisitCallExpr(CallExpr *CE) {
6060    // C++11 [intro.execution]p15:
6061    //   When calling a function [...], every value computation and side effect
6062    //   associated with any argument expression, or with the postfix expression
6063    //   designating the called function, is sequenced before execution of every
6064    //   expression or statement in the body of the function [and thus before
6065    //   the value computation of its result].
6066    SequencedSubexpression Sequenced(*this);
6067    Base::VisitCallExpr(CE);
6068
6069    // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
6070  }
6071
6072  void VisitCXXConstructExpr(CXXConstructExpr *CCE) {
6073    // This is a call, so all subexpressions are sequenced before the result.
6074    SequencedSubexpression Sequenced(*this);
6075
6076    if (!CCE->isListInitialization())
6077      return VisitExpr(CCE);
6078
6079    // In C++11, list initializations are sequenced.
6080    SmallVector<SequenceTree::Seq, 32> Elts;
6081    SequenceTree::Seq Parent = Region;
6082    for (CXXConstructExpr::arg_iterator I = CCE->arg_begin(),
6083                                        E = CCE->arg_end();
6084         I != E; ++I) {
6085      Region = Tree.allocate(Parent);
6086      Elts.push_back(Region);
6087      Visit(*I);
6088    }
6089
6090    // Forget that the initializers are sequenced.
6091    Region = Parent;
6092    for (unsigned I = 0; I < Elts.size(); ++I)
6093      Tree.merge(Elts[I]);
6094  }
6095
6096  void VisitInitListExpr(InitListExpr *ILE) {
6097    if (!SemaRef.getLangOpts().CPlusPlus11)
6098      return VisitExpr(ILE);
6099
6100    // In C++11, list initializations are sequenced.
6101    SmallVector<SequenceTree::Seq, 32> Elts;
6102    SequenceTree::Seq Parent = Region;
6103    for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
6104      Expr *E = ILE->getInit(I);
6105      if (!E) continue;
6106      Region = Tree.allocate(Parent);
6107      Elts.push_back(Region);
6108      Visit(E);
6109    }
6110
6111    // Forget that the initializers are sequenced.
6112    Region = Parent;
6113    for (unsigned I = 0; I < Elts.size(); ++I)
6114      Tree.merge(Elts[I]);
6115  }
6116};
6117}
6118
6119void Sema::CheckUnsequencedOperations(Expr *E) {
6120  SmallVector<Expr *, 8> WorkList;
6121  WorkList.push_back(E);
6122  while (!WorkList.empty()) {
6123    Expr *Item = WorkList.pop_back_val();
6124    SequenceChecker(*this, Item, WorkList);
6125  }
6126}
6127
6128void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
6129                              bool IsConstexpr) {
6130  CheckImplicitConversions(E, CheckLoc);
6131  CheckUnsequencedOperations(E);
6132  if (!IsConstexpr && !E->isValueDependent())
6133    CheckForIntOverflow(E);
6134}
6135
6136void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
6137                                       FieldDecl *BitField,
6138                                       Expr *Init) {
6139  (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
6140}
6141
6142/// CheckParmsForFunctionDef - Check that the parameters of the given
6143/// function are appropriate for the definition of a function. This
6144/// takes care of any checks that cannot be performed on the
6145/// declaration itself, e.g., that the types of each of the function
6146/// parameters are complete.
6147bool Sema::CheckParmsForFunctionDef(ParmVarDecl *const *P,
6148                                    ParmVarDecl *const *PEnd,
6149                                    bool CheckParameterNames) {
6150  bool HasInvalidParm = false;
6151  for (; P != PEnd; ++P) {
6152    ParmVarDecl *Param = *P;
6153
6154    // C99 6.7.5.3p4: the parameters in a parameter type list in a
6155    // function declarator that is part of a function definition of
6156    // that function shall not have incomplete type.
6157    //
6158    // This is also C++ [dcl.fct]p6.
6159    if (!Param->isInvalidDecl() &&
6160        RequireCompleteType(Param->getLocation(), Param->getType(),
6161                            diag::err_typecheck_decl_incomplete_type)) {
6162      Param->setInvalidDecl();
6163      HasInvalidParm = true;
6164    }
6165
6166    // C99 6.9.1p5: If the declarator includes a parameter type list, the
6167    // declaration of each parameter shall include an identifier.
6168    if (CheckParameterNames &&
6169        Param->getIdentifier() == 0 &&
6170        !Param->isImplicit() &&
6171        !getLangOpts().CPlusPlus)
6172      Diag(Param->getLocation(), diag::err_parameter_name_omitted);
6173
6174    // C99 6.7.5.3p12:
6175    //   If the function declarator is not part of a definition of that
6176    //   function, parameters may have incomplete type and may use the [*]
6177    //   notation in their sequences of declarator specifiers to specify
6178    //   variable length array types.
6179    QualType PType = Param->getOriginalType();
6180    while (const ArrayType *AT = Context.getAsArrayType(PType)) {
6181      if (AT->getSizeModifier() == ArrayType::Star) {
6182        // FIXME: This diagnostic should point the '[*]' if source-location
6183        // information is added for it.
6184        Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
6185        break;
6186      }
6187      PType= AT->getElementType();
6188    }
6189
6190    // MSVC destroys objects passed by value in the callee.  Therefore a
6191    // function definition which takes such a parameter must be able to call the
6192    // object's destructor.
6193    if (getLangOpts().CPlusPlus &&
6194        Context.getTargetInfo().getCXXABI().isArgumentDestroyedByCallee()) {
6195      if (const RecordType *RT = Param->getType()->getAs<RecordType>())
6196        FinalizeVarWithDestructor(Param, RT);
6197    }
6198  }
6199
6200  return HasInvalidParm;
6201}
6202
6203/// CheckCastAlign - Implements -Wcast-align, which warns when a
6204/// pointer cast increases the alignment requirements.
6205void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
6206  // This is actually a lot of work to potentially be doing on every
6207  // cast; don't do it if we're ignoring -Wcast_align (as is the default).
6208  if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
6209                                          TRange.getBegin())
6210        == DiagnosticsEngine::Ignored)
6211    return;
6212
6213  // Ignore dependent types.
6214  if (T->isDependentType() || Op->getType()->isDependentType())
6215    return;
6216
6217  // Require that the destination be a pointer type.
6218  const PointerType *DestPtr = T->getAs<PointerType>();
6219  if (!DestPtr) return;
6220
6221  // If the destination has alignment 1, we're done.
6222  QualType DestPointee = DestPtr->getPointeeType();
6223  if (DestPointee->isIncompleteType()) return;
6224  CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
6225  if (DestAlign.isOne()) return;
6226
6227  // Require that the source be a pointer type.
6228  const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
6229  if (!SrcPtr) return;
6230  QualType SrcPointee = SrcPtr->getPointeeType();
6231
6232  // Whitelist casts from cv void*.  We already implicitly
6233  // whitelisted casts to cv void*, since they have alignment 1.
6234  // Also whitelist casts involving incomplete types, which implicitly
6235  // includes 'void'.
6236  if (SrcPointee->isIncompleteType()) return;
6237
6238  CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
6239  if (SrcAlign >= DestAlign) return;
6240
6241  Diag(TRange.getBegin(), diag::warn_cast_align)
6242    << Op->getType() << T
6243    << static_cast<unsigned>(SrcAlign.getQuantity())
6244    << static_cast<unsigned>(DestAlign.getQuantity())
6245    << TRange << Op->getSourceRange();
6246}
6247
6248static const Type* getElementType(const Expr *BaseExpr) {
6249  const Type* EltType = BaseExpr->getType().getTypePtr();
6250  if (EltType->isAnyPointerType())
6251    return EltType->getPointeeType().getTypePtr();
6252  else if (EltType->isArrayType())
6253    return EltType->getBaseElementTypeUnsafe();
6254  return EltType;
6255}
6256
6257/// \brief Check whether this array fits the idiom of a size-one tail padded
6258/// array member of a struct.
6259///
6260/// We avoid emitting out-of-bounds access warnings for such arrays as they are
6261/// commonly used to emulate flexible arrays in C89 code.
6262static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
6263                                    const NamedDecl *ND) {
6264  if (Size != 1 || !ND) return false;
6265
6266  const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
6267  if (!FD) return false;
6268
6269  // Don't consider sizes resulting from macro expansions or template argument
6270  // substitution to form C89 tail-padded arrays.
6271
6272  TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
6273  while (TInfo) {
6274    TypeLoc TL = TInfo->getTypeLoc();
6275    // Look through typedefs.
6276    if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
6277      const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
6278      TInfo = TDL->getTypeSourceInfo();
6279      continue;
6280    }
6281    if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
6282      const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
6283      if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
6284        return false;
6285    }
6286    break;
6287  }
6288
6289  const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
6290  if (!RD) return false;
6291  if (RD->isUnion()) return false;
6292  if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6293    if (!CRD->isStandardLayout()) return false;
6294  }
6295
6296  // See if this is the last field decl in the record.
6297  const Decl *D = FD;
6298  while ((D = D->getNextDeclInContext()))
6299    if (isa<FieldDecl>(D))
6300      return false;
6301  return true;
6302}
6303
6304void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
6305                            const ArraySubscriptExpr *ASE,
6306                            bool AllowOnePastEnd, bool IndexNegated) {
6307  IndexExpr = IndexExpr->IgnoreParenImpCasts();
6308  if (IndexExpr->isValueDependent())
6309    return;
6310
6311  const Type *EffectiveType = getElementType(BaseExpr);
6312  BaseExpr = BaseExpr->IgnoreParenCasts();
6313  const ConstantArrayType *ArrayTy =
6314    Context.getAsConstantArrayType(BaseExpr->getType());
6315  if (!ArrayTy)
6316    return;
6317
6318  llvm::APSInt index;
6319  if (!IndexExpr->EvaluateAsInt(index, Context))
6320    return;
6321  if (IndexNegated)
6322    index = -index;
6323
6324  const NamedDecl *ND = NULL;
6325  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6326    ND = dyn_cast<NamedDecl>(DRE->getDecl());
6327  if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6328    ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6329
6330  if (index.isUnsigned() || !index.isNegative()) {
6331    llvm::APInt size = ArrayTy->getSize();
6332    if (!size.isStrictlyPositive())
6333      return;
6334
6335    const Type* BaseType = getElementType(BaseExpr);
6336    if (BaseType != EffectiveType) {
6337      // Make sure we're comparing apples to apples when comparing index to size
6338      uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
6339      uint64_t array_typesize = Context.getTypeSize(BaseType);
6340      // Handle ptrarith_typesize being zero, such as when casting to void*
6341      if (!ptrarith_typesize) ptrarith_typesize = 1;
6342      if (ptrarith_typesize != array_typesize) {
6343        // There's a cast to a different size type involved
6344        uint64_t ratio = array_typesize / ptrarith_typesize;
6345        // TODO: Be smarter about handling cases where array_typesize is not a
6346        // multiple of ptrarith_typesize
6347        if (ptrarith_typesize * ratio == array_typesize)
6348          size *= llvm::APInt(size.getBitWidth(), ratio);
6349      }
6350    }
6351
6352    if (size.getBitWidth() > index.getBitWidth())
6353      index = index.zext(size.getBitWidth());
6354    else if (size.getBitWidth() < index.getBitWidth())
6355      size = size.zext(index.getBitWidth());
6356
6357    // For array subscripting the index must be less than size, but for pointer
6358    // arithmetic also allow the index (offset) to be equal to size since
6359    // computing the next address after the end of the array is legal and
6360    // commonly done e.g. in C++ iterators and range-based for loops.
6361    if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
6362      return;
6363
6364    // Also don't warn for arrays of size 1 which are members of some
6365    // structure. These are often used to approximate flexible arrays in C89
6366    // code.
6367    if (IsTailPaddedMemberArray(*this, size, ND))
6368      return;
6369
6370    // Suppress the warning if the subscript expression (as identified by the
6371    // ']' location) and the index expression are both from macro expansions
6372    // within a system header.
6373    if (ASE) {
6374      SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
6375          ASE->getRBracketLoc());
6376      if (SourceMgr.isInSystemHeader(RBracketLoc)) {
6377        SourceLocation IndexLoc = SourceMgr.getSpellingLoc(
6378            IndexExpr->getLocStart());
6379        if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
6380          return;
6381      }
6382    }
6383
6384    unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
6385    if (ASE)
6386      DiagID = diag::warn_array_index_exceeds_bounds;
6387
6388    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6389                        PDiag(DiagID) << index.toString(10, true)
6390                          << size.toString(10, true)
6391                          << (unsigned)size.getLimitedValue(~0U)
6392                          << IndexExpr->getSourceRange());
6393  } else {
6394    unsigned DiagID = diag::warn_array_index_precedes_bounds;
6395    if (!ASE) {
6396      DiagID = diag::warn_ptr_arith_precedes_bounds;
6397      if (index.isNegative()) index = -index;
6398    }
6399
6400    DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
6401                        PDiag(DiagID) << index.toString(10, true)
6402                          << IndexExpr->getSourceRange());
6403  }
6404
6405  if (!ND) {
6406    // Try harder to find a NamedDecl to point at in the note.
6407    while (const ArraySubscriptExpr *ASE =
6408           dyn_cast<ArraySubscriptExpr>(BaseExpr))
6409      BaseExpr = ASE->getBase()->IgnoreParenCasts();
6410    if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
6411      ND = dyn_cast<NamedDecl>(DRE->getDecl());
6412    if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
6413      ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
6414  }
6415
6416  if (ND)
6417    DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
6418                        PDiag(diag::note_array_index_out_of_bounds)
6419                          << ND->getDeclName());
6420}
6421
6422void Sema::CheckArrayAccess(const Expr *expr) {
6423  int AllowOnePastEnd = 0;
6424  while (expr) {
6425    expr = expr->IgnoreParenImpCasts();
6426    switch (expr->getStmtClass()) {
6427      case Stmt::ArraySubscriptExprClass: {
6428        const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
6429        CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
6430                         AllowOnePastEnd > 0);
6431        return;
6432      }
6433      case Stmt::UnaryOperatorClass: {
6434        // Only unwrap the * and & unary operators
6435        const UnaryOperator *UO = cast<UnaryOperator>(expr);
6436        expr = UO->getSubExpr();
6437        switch (UO->getOpcode()) {
6438          case UO_AddrOf:
6439            AllowOnePastEnd++;
6440            break;
6441          case UO_Deref:
6442            AllowOnePastEnd--;
6443            break;
6444          default:
6445            return;
6446        }
6447        break;
6448      }
6449      case Stmt::ConditionalOperatorClass: {
6450        const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
6451        if (const Expr *lhs = cond->getLHS())
6452          CheckArrayAccess(lhs);
6453        if (const Expr *rhs = cond->getRHS())
6454          CheckArrayAccess(rhs);
6455        return;
6456      }
6457      default:
6458        return;
6459    }
6460  }
6461}
6462
6463//===--- CHECK: Objective-C retain cycles ----------------------------------//
6464
6465namespace {
6466  struct RetainCycleOwner {
6467    RetainCycleOwner() : Variable(0), Indirect(false) {}
6468    VarDecl *Variable;
6469    SourceRange Range;
6470    SourceLocation Loc;
6471    bool Indirect;
6472
6473    void setLocsFrom(Expr *e) {
6474      Loc = e->getExprLoc();
6475      Range = e->getSourceRange();
6476    }
6477  };
6478}
6479
6480/// Consider whether capturing the given variable can possibly lead to
6481/// a retain cycle.
6482static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
6483  // In ARC, it's captured strongly iff the variable has __strong
6484  // lifetime.  In MRR, it's captured strongly if the variable is
6485  // __block and has an appropriate type.
6486  if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6487    return false;
6488
6489  owner.Variable = var;
6490  if (ref)
6491    owner.setLocsFrom(ref);
6492  return true;
6493}
6494
6495static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
6496  while (true) {
6497    e = e->IgnoreParens();
6498    if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
6499      switch (cast->getCastKind()) {
6500      case CK_BitCast:
6501      case CK_LValueBitCast:
6502      case CK_LValueToRValue:
6503      case CK_ARCReclaimReturnedObject:
6504        e = cast->getSubExpr();
6505        continue;
6506
6507      default:
6508        return false;
6509      }
6510    }
6511
6512    if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
6513      ObjCIvarDecl *ivar = ref->getDecl();
6514      if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
6515        return false;
6516
6517      // Try to find a retain cycle in the base.
6518      if (!findRetainCycleOwner(S, ref->getBase(), owner))
6519        return false;
6520
6521      if (ref->isFreeIvar()) owner.setLocsFrom(ref);
6522      owner.Indirect = true;
6523      return true;
6524    }
6525
6526    if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
6527      VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
6528      if (!var) return false;
6529      return considerVariable(var, ref, owner);
6530    }
6531
6532    if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
6533      if (member->isArrow()) return false;
6534
6535      // Don't count this as an indirect ownership.
6536      e = member->getBase();
6537      continue;
6538    }
6539
6540    if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
6541      // Only pay attention to pseudo-objects on property references.
6542      ObjCPropertyRefExpr *pre
6543        = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
6544                                              ->IgnoreParens());
6545      if (!pre) return false;
6546      if (pre->isImplicitProperty()) return false;
6547      ObjCPropertyDecl *property = pre->getExplicitProperty();
6548      if (!property->isRetaining() &&
6549          !(property->getPropertyIvarDecl() &&
6550            property->getPropertyIvarDecl()->getType()
6551              .getObjCLifetime() == Qualifiers::OCL_Strong))
6552          return false;
6553
6554      owner.Indirect = true;
6555      if (pre->isSuperReceiver()) {
6556        owner.Variable = S.getCurMethodDecl()->getSelfDecl();
6557        if (!owner.Variable)
6558          return false;
6559        owner.Loc = pre->getLocation();
6560        owner.Range = pre->getSourceRange();
6561        return true;
6562      }
6563      e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
6564                              ->getSourceExpr());
6565      continue;
6566    }
6567
6568    // Array ivars?
6569
6570    return false;
6571  }
6572}
6573
6574namespace {
6575  struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
6576    FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
6577      : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
6578        Variable(variable), Capturer(0) {}
6579
6580    VarDecl *Variable;
6581    Expr *Capturer;
6582
6583    void VisitDeclRefExpr(DeclRefExpr *ref) {
6584      if (ref->getDecl() == Variable && !Capturer)
6585        Capturer = ref;
6586    }
6587
6588    void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
6589      if (Capturer) return;
6590      Visit(ref->getBase());
6591      if (Capturer && ref->isFreeIvar())
6592        Capturer = ref;
6593    }
6594
6595    void VisitBlockExpr(BlockExpr *block) {
6596      // Look inside nested blocks
6597      if (block->getBlockDecl()->capturesVariable(Variable))
6598        Visit(block->getBlockDecl()->getBody());
6599    }
6600
6601    void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
6602      if (Capturer) return;
6603      if (OVE->getSourceExpr())
6604        Visit(OVE->getSourceExpr());
6605    }
6606  };
6607}
6608
6609/// Check whether the given argument is a block which captures a
6610/// variable.
6611static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
6612  assert(owner.Variable && owner.Loc.isValid());
6613
6614  e = e->IgnoreParenCasts();
6615
6616  // Look through [^{...} copy] and Block_copy(^{...}).
6617  if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
6618    Selector Cmd = ME->getSelector();
6619    if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
6620      e = ME->getInstanceReceiver();
6621      if (!e)
6622        return 0;
6623      e = e->IgnoreParenCasts();
6624    }
6625  } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
6626    if (CE->getNumArgs() == 1) {
6627      FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
6628      if (Fn) {
6629        const IdentifierInfo *FnI = Fn->getIdentifier();
6630        if (FnI && FnI->isStr("_Block_copy")) {
6631          e = CE->getArg(0)->IgnoreParenCasts();
6632        }
6633      }
6634    }
6635  }
6636
6637  BlockExpr *block = dyn_cast<BlockExpr>(e);
6638  if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
6639    return 0;
6640
6641  FindCaptureVisitor visitor(S.Context, owner.Variable);
6642  visitor.Visit(block->getBlockDecl()->getBody());
6643  return visitor.Capturer;
6644}
6645
6646static void diagnoseRetainCycle(Sema &S, Expr *capturer,
6647                                RetainCycleOwner &owner) {
6648  assert(capturer);
6649  assert(owner.Variable && owner.Loc.isValid());
6650
6651  S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
6652    << owner.Variable << capturer->getSourceRange();
6653  S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
6654    << owner.Indirect << owner.Range;
6655}
6656
6657/// Check for a keyword selector that starts with the word 'add' or
6658/// 'set'.
6659static bool isSetterLikeSelector(Selector sel) {
6660  if (sel.isUnarySelector()) return false;
6661
6662  StringRef str = sel.getNameForSlot(0);
6663  while (!str.empty() && str.front() == '_') str = str.substr(1);
6664  if (str.startswith("set"))
6665    str = str.substr(3);
6666  else if (str.startswith("add")) {
6667    // Specially whitelist 'addOperationWithBlock:'.
6668    if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
6669      return false;
6670    str = str.substr(3);
6671  }
6672  else
6673    return false;
6674
6675  if (str.empty()) return true;
6676  return !isLowercase(str.front());
6677}
6678
6679/// Check a message send to see if it's likely to cause a retain cycle.
6680void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
6681  // Only check instance methods whose selector looks like a setter.
6682  if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
6683    return;
6684
6685  // Try to find a variable that the receiver is strongly owned by.
6686  RetainCycleOwner owner;
6687  if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
6688    if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
6689      return;
6690  } else {
6691    assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
6692    owner.Variable = getCurMethodDecl()->getSelfDecl();
6693    owner.Loc = msg->getSuperLoc();
6694    owner.Range = msg->getSuperLoc();
6695  }
6696
6697  // Check whether the receiver is captured by any of the arguments.
6698  for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
6699    if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
6700      return diagnoseRetainCycle(*this, capturer, owner);
6701}
6702
6703/// Check a property assign to see if it's likely to cause a retain cycle.
6704void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
6705  RetainCycleOwner owner;
6706  if (!findRetainCycleOwner(*this, receiver, owner))
6707    return;
6708
6709  if (Expr *capturer = findCapturingExpr(*this, argument, owner))
6710    diagnoseRetainCycle(*this, capturer, owner);
6711}
6712
6713void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
6714  RetainCycleOwner Owner;
6715  if (!considerVariable(Var, /*DeclRefExpr=*/0, Owner))
6716    return;
6717
6718  // Because we don't have an expression for the variable, we have to set the
6719  // location explicitly here.
6720  Owner.Loc = Var->getLocation();
6721  Owner.Range = Var->getSourceRange();
6722
6723  if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
6724    diagnoseRetainCycle(*this, Capturer, Owner);
6725}
6726
6727static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
6728                                     Expr *RHS, bool isProperty) {
6729  // Check if RHS is an Objective-C object literal, which also can get
6730  // immediately zapped in a weak reference.  Note that we explicitly
6731  // allow ObjCStringLiterals, since those are designed to never really die.
6732  RHS = RHS->IgnoreParenImpCasts();
6733
6734  // This enum needs to match with the 'select' in
6735  // warn_objc_arc_literal_assign (off-by-1).
6736  Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
6737  if (Kind == Sema::LK_String || Kind == Sema::LK_None)
6738    return false;
6739
6740  S.Diag(Loc, diag::warn_arc_literal_assign)
6741    << (unsigned) Kind
6742    << (isProperty ? 0 : 1)
6743    << RHS->getSourceRange();
6744
6745  return true;
6746}
6747
6748static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
6749                                    Qualifiers::ObjCLifetime LT,
6750                                    Expr *RHS, bool isProperty) {
6751  // Strip off any implicit cast added to get to the one ARC-specific.
6752  while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6753    if (cast->getCastKind() == CK_ARCConsumeObject) {
6754      S.Diag(Loc, diag::warn_arc_retained_assign)
6755        << (LT == Qualifiers::OCL_ExplicitNone)
6756        << (isProperty ? 0 : 1)
6757        << RHS->getSourceRange();
6758      return true;
6759    }
6760    RHS = cast->getSubExpr();
6761  }
6762
6763  if (LT == Qualifiers::OCL_Weak &&
6764      checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
6765    return true;
6766
6767  return false;
6768}
6769
6770bool Sema::checkUnsafeAssigns(SourceLocation Loc,
6771                              QualType LHS, Expr *RHS) {
6772  Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
6773
6774  if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
6775    return false;
6776
6777  if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
6778    return true;
6779
6780  return false;
6781}
6782
6783void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
6784                              Expr *LHS, Expr *RHS) {
6785  QualType LHSType;
6786  // PropertyRef on LHS type need be directly obtained from
6787  // its declaration as it has a PsuedoType.
6788  ObjCPropertyRefExpr *PRE
6789    = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
6790  if (PRE && !PRE->isImplicitProperty()) {
6791    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6792    if (PD)
6793      LHSType = PD->getType();
6794  }
6795
6796  if (LHSType.isNull())
6797    LHSType = LHS->getType();
6798
6799  Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
6800
6801  if (LT == Qualifiers::OCL_Weak) {
6802    DiagnosticsEngine::Level Level =
6803      Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
6804    if (Level != DiagnosticsEngine::Ignored)
6805      getCurFunction()->markSafeWeakUse(LHS);
6806  }
6807
6808  if (checkUnsafeAssigns(Loc, LHSType, RHS))
6809    return;
6810
6811  // FIXME. Check for other life times.
6812  if (LT != Qualifiers::OCL_None)
6813    return;
6814
6815  if (PRE) {
6816    if (PRE->isImplicitProperty())
6817      return;
6818    const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
6819    if (!PD)
6820      return;
6821
6822    unsigned Attributes = PD->getPropertyAttributes();
6823    if (Attributes & ObjCPropertyDecl::OBJC_PR_assign) {
6824      // when 'assign' attribute was not explicitly specified
6825      // by user, ignore it and rely on property type itself
6826      // for lifetime info.
6827      unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
6828      if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
6829          LHSType->isObjCRetainableType())
6830        return;
6831
6832      while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
6833        if (cast->getCastKind() == CK_ARCConsumeObject) {
6834          Diag(Loc, diag::warn_arc_retained_property_assign)
6835          << RHS->getSourceRange();
6836          return;
6837        }
6838        RHS = cast->getSubExpr();
6839      }
6840    }
6841    else if (Attributes & ObjCPropertyDecl::OBJC_PR_weak) {
6842      if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
6843        return;
6844    }
6845  }
6846}
6847
6848//===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
6849
6850namespace {
6851bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
6852                                 SourceLocation StmtLoc,
6853                                 const NullStmt *Body) {
6854  // Do not warn if the body is a macro that expands to nothing, e.g:
6855  //
6856  // #define CALL(x)
6857  // if (condition)
6858  //   CALL(0);
6859  //
6860  if (Body->hasLeadingEmptyMacro())
6861    return false;
6862
6863  // Get line numbers of statement and body.
6864  bool StmtLineInvalid;
6865  unsigned StmtLine = SourceMgr.getSpellingLineNumber(StmtLoc,
6866                                                      &StmtLineInvalid);
6867  if (StmtLineInvalid)
6868    return false;
6869
6870  bool BodyLineInvalid;
6871  unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
6872                                                      &BodyLineInvalid);
6873  if (BodyLineInvalid)
6874    return false;
6875
6876  // Warn if null statement and body are on the same line.
6877  if (StmtLine != BodyLine)
6878    return false;
6879
6880  return true;
6881}
6882} // Unnamed namespace
6883
6884void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
6885                                 const Stmt *Body,
6886                                 unsigned DiagID) {
6887  // Since this is a syntactic check, don't emit diagnostic for template
6888  // instantiations, this just adds noise.
6889  if (CurrentInstantiationScope)
6890    return;
6891
6892  // The body should be a null statement.
6893  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6894  if (!NBody)
6895    return;
6896
6897  // Do the usual checks.
6898  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6899    return;
6900
6901  Diag(NBody->getSemiLoc(), DiagID);
6902  Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6903}
6904
6905void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
6906                                 const Stmt *PossibleBody) {
6907  assert(!CurrentInstantiationScope); // Ensured by caller
6908
6909  SourceLocation StmtLoc;
6910  const Stmt *Body;
6911  unsigned DiagID;
6912  if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
6913    StmtLoc = FS->getRParenLoc();
6914    Body = FS->getBody();
6915    DiagID = diag::warn_empty_for_body;
6916  } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
6917    StmtLoc = WS->getCond()->getSourceRange().getEnd();
6918    Body = WS->getBody();
6919    DiagID = diag::warn_empty_while_body;
6920  } else
6921    return; // Neither `for' nor `while'.
6922
6923  // The body should be a null statement.
6924  const NullStmt *NBody = dyn_cast<NullStmt>(Body);
6925  if (!NBody)
6926    return;
6927
6928  // Skip expensive checks if diagnostic is disabled.
6929  if (Diags.getDiagnosticLevel(DiagID, NBody->getSemiLoc()) ==
6930          DiagnosticsEngine::Ignored)
6931    return;
6932
6933  // Do the usual checks.
6934  if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
6935    return;
6936
6937  // `for(...);' and `while(...);' are popular idioms, so in order to keep
6938  // noise level low, emit diagnostics only if for/while is followed by a
6939  // CompoundStmt, e.g.:
6940  //    for (int i = 0; i < n; i++);
6941  //    {
6942  //      a(i);
6943  //    }
6944  // or if for/while is followed by a statement with more indentation
6945  // than for/while itself:
6946  //    for (int i = 0; i < n; i++);
6947  //      a(i);
6948  bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
6949  if (!ProbableTypo) {
6950    bool BodyColInvalid;
6951    unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
6952                             PossibleBody->getLocStart(),
6953                             &BodyColInvalid);
6954    if (BodyColInvalid)
6955      return;
6956
6957    bool StmtColInvalid;
6958    unsigned StmtCol = SourceMgr.getPresumedColumnNumber(
6959                             S->getLocStart(),
6960                             &StmtColInvalid);
6961    if (StmtColInvalid)
6962      return;
6963
6964    if (BodyCol > StmtCol)
6965      ProbableTypo = true;
6966  }
6967
6968  if (ProbableTypo) {
6969    Diag(NBody->getSemiLoc(), DiagID);
6970    Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
6971  }
6972}
6973
6974//===--- Layout compatibility ----------------------------------------------//
6975
6976namespace {
6977
6978bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
6979
6980/// \brief Check if two enumeration types are layout-compatible.
6981bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
6982  // C++11 [dcl.enum] p8:
6983  // Two enumeration types are layout-compatible if they have the same
6984  // underlying type.
6985  return ED1->isComplete() && ED2->isComplete() &&
6986         C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
6987}
6988
6989/// \brief Check if two fields are layout-compatible.
6990bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, FieldDecl *Field2) {
6991  if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
6992    return false;
6993
6994  if (Field1->isBitField() != Field2->isBitField())
6995    return false;
6996
6997  if (Field1->isBitField()) {
6998    // Make sure that the bit-fields are the same length.
6999    unsigned Bits1 = Field1->getBitWidthValue(C);
7000    unsigned Bits2 = Field2->getBitWidthValue(C);
7001
7002    if (Bits1 != Bits2)
7003      return false;
7004  }
7005
7006  return true;
7007}
7008
7009/// \brief Check if two standard-layout structs are layout-compatible.
7010/// (C++11 [class.mem] p17)
7011bool isLayoutCompatibleStruct(ASTContext &C,
7012                              RecordDecl *RD1,
7013                              RecordDecl *RD2) {
7014  // If both records are C++ classes, check that base classes match.
7015  if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
7016    // If one of records is a CXXRecordDecl we are in C++ mode,
7017    // thus the other one is a CXXRecordDecl, too.
7018    const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
7019    // Check number of base classes.
7020    if (D1CXX->getNumBases() != D2CXX->getNumBases())
7021      return false;
7022
7023    // Check the base classes.
7024    for (CXXRecordDecl::base_class_const_iterator
7025               Base1 = D1CXX->bases_begin(),
7026           BaseEnd1 = D1CXX->bases_end(),
7027              Base2 = D2CXX->bases_begin();
7028         Base1 != BaseEnd1;
7029         ++Base1, ++Base2) {
7030      if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
7031        return false;
7032    }
7033  } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
7034    // If only RD2 is a C++ class, it should have zero base classes.
7035    if (D2CXX->getNumBases() > 0)
7036      return false;
7037  }
7038
7039  // Check the fields.
7040  RecordDecl::field_iterator Field2 = RD2->field_begin(),
7041                             Field2End = RD2->field_end(),
7042                             Field1 = RD1->field_begin(),
7043                             Field1End = RD1->field_end();
7044  for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
7045    if (!isLayoutCompatible(C, *Field1, *Field2))
7046      return false;
7047  }
7048  if (Field1 != Field1End || Field2 != Field2End)
7049    return false;
7050
7051  return true;
7052}
7053
7054/// \brief Check if two standard-layout unions are layout-compatible.
7055/// (C++11 [class.mem] p18)
7056bool isLayoutCompatibleUnion(ASTContext &C,
7057                             RecordDecl *RD1,
7058                             RecordDecl *RD2) {
7059  llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
7060  for (RecordDecl::field_iterator Field2 = RD2->field_begin(),
7061                                  Field2End = RD2->field_end();
7062       Field2 != Field2End; ++Field2) {
7063    UnmatchedFields.insert(*Field2);
7064  }
7065
7066  for (RecordDecl::field_iterator Field1 = RD1->field_begin(),
7067                                  Field1End = RD1->field_end();
7068       Field1 != Field1End; ++Field1) {
7069    llvm::SmallPtrSet<FieldDecl *, 8>::iterator
7070        I = UnmatchedFields.begin(),
7071        E = UnmatchedFields.end();
7072
7073    for ( ; I != E; ++I) {
7074      if (isLayoutCompatible(C, *Field1, *I)) {
7075        bool Result = UnmatchedFields.erase(*I);
7076        (void) Result;
7077        assert(Result);
7078        break;
7079      }
7080    }
7081    if (I == E)
7082      return false;
7083  }
7084
7085  return UnmatchedFields.empty();
7086}
7087
7088bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, RecordDecl *RD2) {
7089  if (RD1->isUnion() != RD2->isUnion())
7090    return false;
7091
7092  if (RD1->isUnion())
7093    return isLayoutCompatibleUnion(C, RD1, RD2);
7094  else
7095    return isLayoutCompatibleStruct(C, RD1, RD2);
7096}
7097
7098/// \brief Check if two types are layout-compatible in C++11 sense.
7099bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
7100  if (T1.isNull() || T2.isNull())
7101    return false;
7102
7103  // C++11 [basic.types] p11:
7104  // If two types T1 and T2 are the same type, then T1 and T2 are
7105  // layout-compatible types.
7106  if (C.hasSameType(T1, T2))
7107    return true;
7108
7109  T1 = T1.getCanonicalType().getUnqualifiedType();
7110  T2 = T2.getCanonicalType().getUnqualifiedType();
7111
7112  const Type::TypeClass TC1 = T1->getTypeClass();
7113  const Type::TypeClass TC2 = T2->getTypeClass();
7114
7115  if (TC1 != TC2)
7116    return false;
7117
7118  if (TC1 == Type::Enum) {
7119    return isLayoutCompatible(C,
7120                              cast<EnumType>(T1)->getDecl(),
7121                              cast<EnumType>(T2)->getDecl());
7122  } else if (TC1 == Type::Record) {
7123    if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
7124      return false;
7125
7126    return isLayoutCompatible(C,
7127                              cast<RecordType>(T1)->getDecl(),
7128                              cast<RecordType>(T2)->getDecl());
7129  }
7130
7131  return false;
7132}
7133}
7134
7135//===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
7136
7137namespace {
7138/// \brief Given a type tag expression find the type tag itself.
7139///
7140/// \param TypeExpr Type tag expression, as it appears in user's code.
7141///
7142/// \param VD Declaration of an identifier that appears in a type tag.
7143///
7144/// \param MagicValue Type tag magic value.
7145bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
7146                     const ValueDecl **VD, uint64_t *MagicValue) {
7147  while(true) {
7148    if (!TypeExpr)
7149      return false;
7150
7151    TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
7152
7153    switch (TypeExpr->getStmtClass()) {
7154    case Stmt::UnaryOperatorClass: {
7155      const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
7156      if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
7157        TypeExpr = UO->getSubExpr();
7158        continue;
7159      }
7160      return false;
7161    }
7162
7163    case Stmt::DeclRefExprClass: {
7164      const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
7165      *VD = DRE->getDecl();
7166      return true;
7167    }
7168
7169    case Stmt::IntegerLiteralClass: {
7170      const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
7171      llvm::APInt MagicValueAPInt = IL->getValue();
7172      if (MagicValueAPInt.getActiveBits() <= 64) {
7173        *MagicValue = MagicValueAPInt.getZExtValue();
7174        return true;
7175      } else
7176        return false;
7177    }
7178
7179    case Stmt::BinaryConditionalOperatorClass:
7180    case Stmt::ConditionalOperatorClass: {
7181      const AbstractConditionalOperator *ACO =
7182          cast<AbstractConditionalOperator>(TypeExpr);
7183      bool Result;
7184      if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx)) {
7185        if (Result)
7186          TypeExpr = ACO->getTrueExpr();
7187        else
7188          TypeExpr = ACO->getFalseExpr();
7189        continue;
7190      }
7191      return false;
7192    }
7193
7194    case Stmt::BinaryOperatorClass: {
7195      const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
7196      if (BO->getOpcode() == BO_Comma) {
7197        TypeExpr = BO->getRHS();
7198        continue;
7199      }
7200      return false;
7201    }
7202
7203    default:
7204      return false;
7205    }
7206  }
7207}
7208
7209/// \brief Retrieve the C type corresponding to type tag TypeExpr.
7210///
7211/// \param TypeExpr Expression that specifies a type tag.
7212///
7213/// \param MagicValues Registered magic values.
7214///
7215/// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
7216///        kind.
7217///
7218/// \param TypeInfo Information about the corresponding C type.
7219///
7220/// \returns true if the corresponding C type was found.
7221bool GetMatchingCType(
7222        const IdentifierInfo *ArgumentKind,
7223        const Expr *TypeExpr, const ASTContext &Ctx,
7224        const llvm::DenseMap<Sema::TypeTagMagicValue,
7225                             Sema::TypeTagData> *MagicValues,
7226        bool &FoundWrongKind,
7227        Sema::TypeTagData &TypeInfo) {
7228  FoundWrongKind = false;
7229
7230  // Variable declaration that has type_tag_for_datatype attribute.
7231  const ValueDecl *VD = NULL;
7232
7233  uint64_t MagicValue;
7234
7235  if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
7236    return false;
7237
7238  if (VD) {
7239    for (specific_attr_iterator<TypeTagForDatatypeAttr>
7240             I = VD->specific_attr_begin<TypeTagForDatatypeAttr>(),
7241             E = VD->specific_attr_end<TypeTagForDatatypeAttr>();
7242         I != E; ++I) {
7243      if (I->getArgumentKind() != ArgumentKind) {
7244        FoundWrongKind = true;
7245        return false;
7246      }
7247      TypeInfo.Type = I->getMatchingCType();
7248      TypeInfo.LayoutCompatible = I->getLayoutCompatible();
7249      TypeInfo.MustBeNull = I->getMustBeNull();
7250      return true;
7251    }
7252    return false;
7253  }
7254
7255  if (!MagicValues)
7256    return false;
7257
7258  llvm::DenseMap<Sema::TypeTagMagicValue,
7259                 Sema::TypeTagData>::const_iterator I =
7260      MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
7261  if (I == MagicValues->end())
7262    return false;
7263
7264  TypeInfo = I->second;
7265  return true;
7266}
7267} // unnamed namespace
7268
7269void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
7270                                      uint64_t MagicValue, QualType Type,
7271                                      bool LayoutCompatible,
7272                                      bool MustBeNull) {
7273  if (!TypeTagForDatatypeMagicValues)
7274    TypeTagForDatatypeMagicValues.reset(
7275        new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
7276
7277  TypeTagMagicValue Magic(ArgumentKind, MagicValue);
7278  (*TypeTagForDatatypeMagicValues)[Magic] =
7279      TypeTagData(Type, LayoutCompatible, MustBeNull);
7280}
7281
7282namespace {
7283bool IsSameCharType(QualType T1, QualType T2) {
7284  const BuiltinType *BT1 = T1->getAs<BuiltinType>();
7285  if (!BT1)
7286    return false;
7287
7288  const BuiltinType *BT2 = T2->getAs<BuiltinType>();
7289  if (!BT2)
7290    return false;
7291
7292  BuiltinType::Kind T1Kind = BT1->getKind();
7293  BuiltinType::Kind T2Kind = BT2->getKind();
7294
7295  return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
7296         (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
7297         (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
7298         (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
7299}
7300} // unnamed namespace
7301
7302void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
7303                                    const Expr * const *ExprArgs) {
7304  const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
7305  bool IsPointerAttr = Attr->getIsPointer();
7306
7307  const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
7308  bool FoundWrongKind;
7309  TypeTagData TypeInfo;
7310  if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
7311                        TypeTagForDatatypeMagicValues.get(),
7312                        FoundWrongKind, TypeInfo)) {
7313    if (FoundWrongKind)
7314      Diag(TypeTagExpr->getExprLoc(),
7315           diag::warn_type_tag_for_datatype_wrong_kind)
7316        << TypeTagExpr->getSourceRange();
7317    return;
7318  }
7319
7320  const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
7321  if (IsPointerAttr) {
7322    // Skip implicit cast of pointer to `void *' (as a function argument).
7323    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
7324      if (ICE->getType()->isVoidPointerType() &&
7325          ICE->getCastKind() == CK_BitCast)
7326        ArgumentExpr = ICE->getSubExpr();
7327  }
7328  QualType ArgumentType = ArgumentExpr->getType();
7329
7330  // Passing a `void*' pointer shouldn't trigger a warning.
7331  if (IsPointerAttr && ArgumentType->isVoidPointerType())
7332    return;
7333
7334  if (TypeInfo.MustBeNull) {
7335    // Type tag with matching void type requires a null pointer.
7336    if (!ArgumentExpr->isNullPointerConstant(Context,
7337                                             Expr::NPC_ValueDependentIsNotNull)) {
7338      Diag(ArgumentExpr->getExprLoc(),
7339           diag::warn_type_safety_null_pointer_required)
7340          << ArgumentKind->getName()
7341          << ArgumentExpr->getSourceRange()
7342          << TypeTagExpr->getSourceRange();
7343    }
7344    return;
7345  }
7346
7347  QualType RequiredType = TypeInfo.Type;
7348  if (IsPointerAttr)
7349    RequiredType = Context.getPointerType(RequiredType);
7350
7351  bool mismatch = false;
7352  if (!TypeInfo.LayoutCompatible) {
7353    mismatch = !Context.hasSameType(ArgumentType, RequiredType);
7354
7355    // C++11 [basic.fundamental] p1:
7356    // Plain char, signed char, and unsigned char are three distinct types.
7357    //
7358    // But we treat plain `char' as equivalent to `signed char' or `unsigned
7359    // char' depending on the current char signedness mode.
7360    if (mismatch)
7361      if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
7362                                           RequiredType->getPointeeType())) ||
7363          (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
7364        mismatch = false;
7365  } else
7366    if (IsPointerAttr)
7367      mismatch = !isLayoutCompatible(Context,
7368                                     ArgumentType->getPointeeType(),
7369                                     RequiredType->getPointeeType());
7370    else
7371      mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
7372
7373  if (mismatch)
7374    Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
7375        << ArgumentType << ArgumentKind->getName()
7376        << TypeInfo.LayoutCompatible << RequiredType
7377        << ArgumentExpr->getSourceRange()
7378        << TypeTagExpr->getSourceRange();
7379}
7380