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