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