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