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