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