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