]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaChecking.cpp
MFC r227735:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / Sema / SemaChecking.cpp
1 //===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements extra semantic analysis beyond what is enforced
11 //  by the C type system.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Sema/Initialization.h"
16 #include "clang/Sema/Sema.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Analysis/Analyses/FormatString.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CharUnits.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/EvaluatedExprVisitor.h"
28 #include "clang/AST/DeclObjC.h"
29 #include "clang/AST/StmtCXX.h"
30 #include "clang/AST/StmtObjC.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "clang/Basic/TargetBuiltins.h"
36 #include "clang/Basic/TargetInfo.h"
37 #include "clang/Basic/ConvertUTF.h"
38 #include <limits>
39 using namespace clang;
40 using namespace sema;
41
42 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43                                                     unsigned ByteNo) const {
44   return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45                                PP.getLangOptions(), PP.getTargetInfo());
46 }
47   
48
49 /// CheckablePrintfAttr - does a function call have a "printf" attribute
50 /// and arguments that merit checking?
51 bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52   if (Format->getType() == "printf") return true;
53   if (Format->getType() == "printf0") {
54     // printf0 allows null "format" string; if so don't check format/args
55     unsigned format_idx = Format->getFormatIdx() - 1;
56     // Does the index refer to the implicit object argument?
57     if (isa<CXXMemberCallExpr>(TheCall)) {
58       if (format_idx == 0)
59         return false;
60       --format_idx;
61     }
62     if (format_idx < TheCall->getNumArgs()) {
63       Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
64       if (!Format->isNullPointerConstant(Context,
65                                          Expr::NPC_ValueDependentIsNull))
66         return true;
67     }
68   }
69   return false;
70 }
71
72 /// Checks that a call expression's argument count is the desired number.
73 /// This is useful when doing custom type-checking.  Returns true on error.
74 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75   unsigned argCount = call->getNumArgs();
76   if (argCount == desiredArgCount) return false;
77
78   if (argCount < desiredArgCount)
79     return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80         << 0 /*function call*/ << desiredArgCount << argCount
81         << call->getSourceRange();
82
83   // Highlight all the excess arguments.
84   SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85                     call->getArg(argCount - 1)->getLocEnd());
86     
87   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88     << 0 /*function call*/ << desiredArgCount << argCount
89     << call->getArg(1)->getSourceRange();
90 }
91
92 /// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93 /// annotation is a non wide string literal.
94 static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95   Arg = Arg->IgnoreParenCasts();
96   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97   if (!Literal || !Literal->isAscii()) {
98     S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99       << Arg->getSourceRange();
100     return true;
101   }
102   return false;
103 }
104
105 ExprResult
106 Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
107   ExprResult TheCallResult(Owned(TheCall));
108
109   // Find out if any arguments are required to be integer constant expressions.
110   unsigned ICEArguments = 0;
111   ASTContext::GetBuiltinTypeError Error;
112   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113   if (Error != ASTContext::GE_None)
114     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
115   
116   // If any arguments are required to be ICE's, check and diagnose.
117   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118     // Skip arguments not required to be ICE's.
119     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120     
121     llvm::APSInt Result;
122     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123       return true;
124     ICEArguments &= ~(1 << ArgNo);
125   }
126   
127   switch (BuiltinID) {
128   case Builtin::BI__builtin___CFStringMakeConstantString:
129     assert(TheCall->getNumArgs() == 1 &&
130            "Wrong # arguments to builtin CFStringMakeConstantString");
131     if (CheckObjCString(TheCall->getArg(0)))
132       return ExprError();
133     break;
134   case Builtin::BI__builtin_stdarg_start:
135   case Builtin::BI__builtin_va_start:
136     if (SemaBuiltinVAStart(TheCall))
137       return ExprError();
138     break;
139   case Builtin::BI__builtin_isgreater:
140   case Builtin::BI__builtin_isgreaterequal:
141   case Builtin::BI__builtin_isless:
142   case Builtin::BI__builtin_islessequal:
143   case Builtin::BI__builtin_islessgreater:
144   case Builtin::BI__builtin_isunordered:
145     if (SemaBuiltinUnorderedCompare(TheCall))
146       return ExprError();
147     break;
148   case Builtin::BI__builtin_fpclassify:
149     if (SemaBuiltinFPClassification(TheCall, 6))
150       return ExprError();
151     break;
152   case Builtin::BI__builtin_isfinite:
153   case Builtin::BI__builtin_isinf:
154   case Builtin::BI__builtin_isinf_sign:
155   case Builtin::BI__builtin_isnan:
156   case Builtin::BI__builtin_isnormal:
157     if (SemaBuiltinFPClassification(TheCall, 1))
158       return ExprError();
159     break;
160   case Builtin::BI__builtin_shufflevector:
161     return SemaBuiltinShuffleVector(TheCall);
162     // TheCall will be freed by the smart pointer here, but that's fine, since
163     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
164   case Builtin::BI__builtin_prefetch:
165     if (SemaBuiltinPrefetch(TheCall))
166       return ExprError();
167     break;
168   case Builtin::BI__builtin_object_size:
169     if (SemaBuiltinObjectSize(TheCall))
170       return ExprError();
171     break;
172   case Builtin::BI__builtin_longjmp:
173     if (SemaBuiltinLongjmp(TheCall))
174       return ExprError();
175     break;
176
177   case Builtin::BI__builtin_classify_type:
178     if (checkArgCount(*this, TheCall, 1)) return true;
179     TheCall->setType(Context.IntTy);
180     break;
181   case Builtin::BI__builtin_constant_p:
182     if (checkArgCount(*this, TheCall, 1)) return true;
183     TheCall->setType(Context.IntTy);
184     break;
185   case Builtin::BI__sync_fetch_and_add:
186   case Builtin::BI__sync_fetch_and_sub:
187   case Builtin::BI__sync_fetch_and_or:
188   case Builtin::BI__sync_fetch_and_and:
189   case Builtin::BI__sync_fetch_and_xor:
190   case Builtin::BI__sync_add_and_fetch:
191   case Builtin::BI__sync_sub_and_fetch:
192   case Builtin::BI__sync_and_and_fetch:
193   case Builtin::BI__sync_or_and_fetch:
194   case Builtin::BI__sync_xor_and_fetch:
195   case Builtin::BI__sync_val_compare_and_swap:
196   case Builtin::BI__sync_bool_compare_and_swap:
197   case Builtin::BI__sync_lock_test_and_set:
198   case Builtin::BI__sync_lock_release:
199   case Builtin::BI__sync_swap:
200     return SemaBuiltinAtomicOverloaded(move(TheCallResult));
201   case Builtin::BI__atomic_load:
202     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203   case Builtin::BI__atomic_store:
204     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205   case Builtin::BI__atomic_exchange:
206     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207   case Builtin::BI__atomic_compare_exchange_strong:
208     return SemaAtomicOpsOverloaded(move(TheCallResult),
209                                    AtomicExpr::CmpXchgStrong);
210   case Builtin::BI__atomic_compare_exchange_weak:
211     return SemaAtomicOpsOverloaded(move(TheCallResult),
212                                    AtomicExpr::CmpXchgWeak);
213   case Builtin::BI__atomic_fetch_add:
214     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215   case Builtin::BI__atomic_fetch_sub:
216     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217   case Builtin::BI__atomic_fetch_and:
218     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219   case Builtin::BI__atomic_fetch_or:
220     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221   case Builtin::BI__atomic_fetch_xor:
222     return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
223   case Builtin::BI__builtin_annotation:
224     if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225       return ExprError();
226     break;
227   }
228   
229   // Since the target specific builtins for each arch overlap, only check those
230   // of the arch we are compiling for.
231   if (BuiltinID >= Builtin::FirstTSBuiltin) {
232     switch (Context.getTargetInfo().getTriple().getArch()) {
233       case llvm::Triple::arm:
234       case llvm::Triple::thumb:
235         if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236           return ExprError();
237         break;
238       default:
239         break;
240     }
241   }
242
243   return move(TheCallResult);
244 }
245
246 // Get the valid immediate range for the specified NEON type code.
247 static unsigned RFT(unsigned t, bool shift = false) {
248   bool quad = t & 0x10;
249   
250   switch (t & 0x7) {
251     case 0: // i8
252       return shift ? 7 : (8 << (int)quad) - 1;
253     case 1: // i16
254       return shift ? 15 : (4 << (int)quad) - 1;
255     case 2: // i32
256       return shift ? 31 : (2 << (int)quad) - 1;
257     case 3: // i64
258       return shift ? 63 : (1 << (int)quad) - 1;
259     case 4: // f32
260       assert(!shift && "cannot shift float types!");
261       return (2 << (int)quad) - 1;
262     case 5: // poly8
263       return shift ? 7 : (8 << (int)quad) - 1;
264     case 6: // poly16
265       return shift ? 15 : (4 << (int)quad) - 1;
266     case 7: // float16
267       assert(!shift && "cannot shift float types!");
268       return (4 << (int)quad) - 1;
269   }
270   return 0;
271 }
272
273 bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
274   llvm::APSInt Result;
275
276   unsigned mask = 0;
277   unsigned TV = 0;
278   switch (BuiltinID) {
279 #define GET_NEON_OVERLOAD_CHECK
280 #include "clang/Basic/arm_neon.inc"
281 #undef GET_NEON_OVERLOAD_CHECK
282   }
283   
284   // For NEON intrinsics which are overloaded on vector element type, validate
285   // the immediate which specifies which variant to emit.
286   if (mask) {
287     unsigned ArgNo = TheCall->getNumArgs()-1;
288     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
289       return true;
290     
291     TV = Result.getLimitedValue(32);
292     if ((TV > 31) || (mask & (1 << TV)) == 0)
293       return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
294         << TheCall->getArg(ArgNo)->getSourceRange();
295   }
296   
297   // For NEON intrinsics which take an immediate value as part of the 
298   // instruction, range check them here.
299   unsigned i = 0, l = 0, u = 0;
300   switch (BuiltinID) {
301   default: return false;
302   case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
303   case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
304   case ARM::BI__builtin_arm_vcvtr_f:
305   case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
306 #define GET_NEON_IMMEDIATE_CHECK
307 #include "clang/Basic/arm_neon.inc"
308 #undef GET_NEON_IMMEDIATE_CHECK
309   };
310
311   // Check that the immediate argument is actually a constant.
312   if (SemaBuiltinConstantArg(TheCall, i, Result))
313     return true;
314
315   // Range check against the upper/lower values for this isntruction.
316   unsigned Val = Result.getZExtValue();
317   if (Val < l || Val > (u + l))
318     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
319       << l << u+l << TheCall->getArg(i)->getSourceRange();
320
321   // FIXME: VFP Intrinsics should error if VFP not present.
322   return false;
323 }
324
325 /// CheckFunctionCall - Check a direct function call for various correctness
326 /// and safety properties not strictly enforced by the C type system.
327 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
328   // Get the IdentifierInfo* for the called function.
329   IdentifierInfo *FnInfo = FDecl->getIdentifier();
330
331   // None of the checks below are needed for functions that don't have
332   // simple names (e.g., C++ conversion functions).
333   if (!FnInfo)
334     return false;
335
336   // FIXME: This mechanism should be abstracted to be less fragile and
337   // more efficient. For example, just map function ids to custom
338   // handlers.
339
340   // Printf and scanf checking.
341   for (specific_attr_iterator<FormatAttr>
342          i = FDecl->specific_attr_begin<FormatAttr>(),
343          e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
344
345     const FormatAttr *Format = *i;
346     const bool b = Format->getType() == "scanf";
347     if (b || CheckablePrintfAttr(Format, TheCall)) {
348       bool HasVAListArg = Format->getFirstArg() == 0;
349       CheckPrintfScanfArguments(TheCall, HasVAListArg,
350                                 Format->getFormatIdx() - 1,
351                                 HasVAListArg ? 0 : Format->getFirstArg() - 1,
352                                 !b);
353     }
354   }
355
356   for (specific_attr_iterator<NonNullAttr>
357          i = FDecl->specific_attr_begin<NonNullAttr>(),
358          e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
359     CheckNonNullArguments(*i, TheCall->getArgs(),
360                           TheCall->getCallee()->getLocStart());
361   }
362
363   // Builtin handling
364   int CMF = -1;
365   switch (FDecl->getBuiltinID()) {
366   case Builtin::BI__builtin_memset:
367   case Builtin::BI__builtin___memset_chk:
368   case Builtin::BImemset:
369     CMF = CMF_Memset;
370     break;
371     
372   case Builtin::BI__builtin_memcpy:
373   case Builtin::BI__builtin___memcpy_chk:
374   case Builtin::BImemcpy:
375     CMF = CMF_Memcpy;
376     break;
377     
378   case Builtin::BI__builtin_memmove:
379   case Builtin::BI__builtin___memmove_chk:
380   case Builtin::BImemmove:
381     CMF = CMF_Memmove;
382     break;
383
384   case Builtin::BIstrlcpy:
385   case Builtin::BIstrlcat:
386     CheckStrlcpycatArguments(TheCall, FnInfo);
387     break;
388     
389   case Builtin::BI__builtin_memcmp:
390     CMF = CMF_Memcmp;
391     break;
392     
393   case Builtin::BI__builtin_strncpy:
394   case Builtin::BI__builtin___strncpy_chk:
395   case Builtin::BIstrncpy:
396     CMF = CMF_Strncpy;
397     break;
398
399   case Builtin::BI__builtin_strncmp:
400     CMF = CMF_Strncmp;
401     break;
402
403   case Builtin::BI__builtin_strncasecmp:
404     CMF = CMF_Strncasecmp;
405     break;
406
407   case Builtin::BI__builtin_strncat:
408   case Builtin::BIstrncat:
409     CMF = CMF_Strncat;
410     break;
411
412   case Builtin::BI__builtin_strndup:
413   case Builtin::BIstrndup:
414     CMF = CMF_Strndup;
415     break;
416
417   default:
418     if (FDecl->getLinkage() == ExternalLinkage &&
419         (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
420       if (FnInfo->isStr("memset"))
421         CMF = CMF_Memset;
422       else if (FnInfo->isStr("memcpy"))
423         CMF = CMF_Memcpy;
424       else if (FnInfo->isStr("memmove"))
425         CMF = CMF_Memmove;
426       else if (FnInfo->isStr("memcmp"))
427         CMF = CMF_Memcmp;
428       else if (FnInfo->isStr("strncpy"))
429         CMF = CMF_Strncpy;
430       else if (FnInfo->isStr("strncmp"))
431         CMF = CMF_Strncmp;
432       else if (FnInfo->isStr("strncasecmp"))
433         CMF = CMF_Strncasecmp;
434       else if (FnInfo->isStr("strncat"))
435         CMF = CMF_Strncat;
436       else if (FnInfo->isStr("strndup"))
437         CMF = CMF_Strndup;
438     }
439     break;
440   }
441    
442   // Memset/memcpy/memmove handling
443   if (CMF != -1)
444     CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
445
446   return false;
447 }
448
449 bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
450   // Printf checking.
451   const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
452   if (!Format)
453     return false;
454
455   const VarDecl *V = dyn_cast<VarDecl>(NDecl);
456   if (!V)
457     return false;
458
459   QualType Ty = V->getType();
460   if (!Ty->isBlockPointerType())
461     return false;
462
463   const bool b = Format->getType() == "scanf";
464   if (!b && !CheckablePrintfAttr(Format, TheCall))
465     return false;
466
467   bool HasVAListArg = Format->getFirstArg() == 0;
468   CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
469                             HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
470
471   return false;
472 }
473
474 ExprResult
475 Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
476   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
477   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
478
479   // All these operations take one of the following four forms:
480   // T   __atomic_load(_Atomic(T)*, int)                              (loads)
481   // T*  __atomic_add(_Atomic(T*)*, ptrdiff_t, int)         (pointer add/sub)
482   // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
483   //                                                                (cmpxchg)
484   // T   __atomic_exchange(_Atomic(T)*, T, int)             (everything else)
485   // where T is an appropriate type, and the int paremeterss are for orderings.
486   unsigned NumVals = 1;
487   unsigned NumOrders = 1;
488   if (Op == AtomicExpr::Load) {
489     NumVals = 0;
490   } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
491     NumVals = 2;
492     NumOrders = 2;
493   }
494
495   if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
496     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
497       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
498       << TheCall->getCallee()->getSourceRange();
499     return ExprError();
500   } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
501     Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
502          diag::err_typecheck_call_too_many_args)
503       << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
504       << TheCall->getCallee()->getSourceRange();
505     return ExprError();
506   }
507
508   // Inspect the first argument of the atomic operation.  This should always be
509   // a pointer to an _Atomic type.
510   Expr *Ptr = TheCall->getArg(0);
511   Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
512   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
513   if (!pointerType) {
514     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
515       << Ptr->getType() << Ptr->getSourceRange();
516     return ExprError();
517   }
518
519   QualType AtomTy = pointerType->getPointeeType();
520   if (!AtomTy->isAtomicType()) {
521     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
522       << Ptr->getType() << Ptr->getSourceRange();
523     return ExprError();
524   }
525   QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
526
527   if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
528       !ValType->isIntegerType() && !ValType->isPointerType()) {
529     Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
530       << Ptr->getType() << Ptr->getSourceRange();
531     return ExprError();
532   }
533
534   if (!ValType->isIntegerType() &&
535       (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
536     Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
537       << Ptr->getType() << Ptr->getSourceRange();
538     return ExprError();
539   }
540
541   switch (ValType.getObjCLifetime()) {
542   case Qualifiers::OCL_None:
543   case Qualifiers::OCL_ExplicitNone:
544     // okay
545     break;
546
547   case Qualifiers::OCL_Weak:
548   case Qualifiers::OCL_Strong:
549   case Qualifiers::OCL_Autoreleasing:
550     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
551       << ValType << Ptr->getSourceRange();
552     return ExprError();
553   }
554
555   QualType ResultType = ValType;
556   if (Op == AtomicExpr::Store)
557     ResultType = Context.VoidTy;
558   else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
559     ResultType = Context.BoolTy;
560
561   // The first argument --- the pointer --- has a fixed type; we
562   // deduce the types of the rest of the arguments accordingly.  Walk
563   // the remaining arguments, converting them to the deduced value type.
564   for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
565     ExprResult Arg = TheCall->getArg(i);
566     QualType Ty;
567     if (i < NumVals+1) {
568       // The second argument to a cmpxchg is a pointer to the data which will
569       // be exchanged. The second argument to a pointer add/subtract is the
570       // amount to add/subtract, which must be a ptrdiff_t.  The third
571       // argument to a cmpxchg and the second argument in all other cases
572       // is the type of the value.
573       if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
574                      Op == AtomicExpr::CmpXchgStrong))
575          Ty = Context.getPointerType(ValType.getUnqualifiedType());
576       else if (!ValType->isIntegerType() &&
577                (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
578         Ty = Context.getPointerDiffType();
579       else
580         Ty = ValType;
581     } else {
582       // The order(s) are always converted to int.
583       Ty = Context.IntTy;
584     }
585     InitializedEntity Entity =
586         InitializedEntity::InitializeParameter(Context, Ty, false);
587     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
588     if (Arg.isInvalid())
589       return true;
590     TheCall->setArg(i, Arg.get());
591   }
592
593   SmallVector<Expr*, 5> SubExprs;
594   SubExprs.push_back(Ptr);
595   if (Op == AtomicExpr::Load) {
596     SubExprs.push_back(TheCall->getArg(1)); // Order
597   } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
598     SubExprs.push_back(TheCall->getArg(2)); // Order
599     SubExprs.push_back(TheCall->getArg(1)); // Val1
600   } else {
601     SubExprs.push_back(TheCall->getArg(3)); // Order
602     SubExprs.push_back(TheCall->getArg(1)); // Val1
603     SubExprs.push_back(TheCall->getArg(2)); // Val2
604     SubExprs.push_back(TheCall->getArg(4)); // OrderFail
605   }
606
607   return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
608                                         SubExprs.data(), SubExprs.size(),
609                                         ResultType, Op,
610                                         TheCall->getRParenLoc()));
611 }
612
613
614 /// checkBuiltinArgument - Given a call to a builtin function, perform
615 /// normal type-checking on the given argument, updating the call in
616 /// place.  This is useful when a builtin function requires custom
617 /// type-checking for some of its arguments but not necessarily all of
618 /// them.
619 ///
620 /// Returns true on error.
621 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
622   FunctionDecl *Fn = E->getDirectCallee();
623   assert(Fn && "builtin call without direct callee!");
624
625   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
626   InitializedEntity Entity =
627     InitializedEntity::InitializeParameter(S.Context, Param);
628
629   ExprResult Arg = E->getArg(0);
630   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
631   if (Arg.isInvalid())
632     return true;
633
634   E->setArg(ArgIndex, Arg.take());
635   return false;
636 }
637
638 /// SemaBuiltinAtomicOverloaded - We have a call to a function like
639 /// __sync_fetch_and_add, which is an overloaded function based on the pointer
640 /// type of its first argument.  The main ActOnCallExpr routines have already
641 /// promoted the types of arguments because all of these calls are prototyped as
642 /// void(...).
643 ///
644 /// This function goes through and does final semantic checking for these
645 /// builtins,
646 ExprResult
647 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
648   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
649   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
650   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
651
652   // Ensure that we have at least one argument to do type inference from.
653   if (TheCall->getNumArgs() < 1) {
654     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
655       << 0 << 1 << TheCall->getNumArgs()
656       << TheCall->getCallee()->getSourceRange();
657     return ExprError();
658   }
659
660   // Inspect the first argument of the atomic builtin.  This should always be
661   // a pointer type, whose element is an integral scalar or pointer type.
662   // Because it is a pointer type, we don't have to worry about any implicit
663   // casts here.
664   // FIXME: We don't allow floating point scalars as input.
665   Expr *FirstArg = TheCall->getArg(0);
666   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
667   if (!pointerType) {
668     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
669       << FirstArg->getType() << FirstArg->getSourceRange();
670     return ExprError();
671   }
672
673   QualType ValType = pointerType->getPointeeType();
674   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
675       !ValType->isBlockPointerType()) {
676     Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
677       << FirstArg->getType() << FirstArg->getSourceRange();
678     return ExprError();
679   }
680
681   switch (ValType.getObjCLifetime()) {
682   case Qualifiers::OCL_None:
683   case Qualifiers::OCL_ExplicitNone:
684     // okay
685     break;
686
687   case Qualifiers::OCL_Weak:
688   case Qualifiers::OCL_Strong:
689   case Qualifiers::OCL_Autoreleasing:
690     Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
691       << ValType << FirstArg->getSourceRange();
692     return ExprError();
693   }
694
695   // Strip any qualifiers off ValType.
696   ValType = ValType.getUnqualifiedType();
697
698   // The majority of builtins return a value, but a few have special return
699   // types, so allow them to override appropriately below.
700   QualType ResultType = ValType;
701
702   // We need to figure out which concrete builtin this maps onto.  For example,
703   // __sync_fetch_and_add with a 2 byte object turns into
704   // __sync_fetch_and_add_2.
705 #define BUILTIN_ROW(x) \
706   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
707     Builtin::BI##x##_8, Builtin::BI##x##_16 }
708
709   static const unsigned BuiltinIndices[][5] = {
710     BUILTIN_ROW(__sync_fetch_and_add),
711     BUILTIN_ROW(__sync_fetch_and_sub),
712     BUILTIN_ROW(__sync_fetch_and_or),
713     BUILTIN_ROW(__sync_fetch_and_and),
714     BUILTIN_ROW(__sync_fetch_and_xor),
715
716     BUILTIN_ROW(__sync_add_and_fetch),
717     BUILTIN_ROW(__sync_sub_and_fetch),
718     BUILTIN_ROW(__sync_and_and_fetch),
719     BUILTIN_ROW(__sync_or_and_fetch),
720     BUILTIN_ROW(__sync_xor_and_fetch),
721
722     BUILTIN_ROW(__sync_val_compare_and_swap),
723     BUILTIN_ROW(__sync_bool_compare_and_swap),
724     BUILTIN_ROW(__sync_lock_test_and_set),
725     BUILTIN_ROW(__sync_lock_release),
726     BUILTIN_ROW(__sync_swap)
727   };
728 #undef BUILTIN_ROW
729
730   // Determine the index of the size.
731   unsigned SizeIndex;
732   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
733   case 1: SizeIndex = 0; break;
734   case 2: SizeIndex = 1; break;
735   case 4: SizeIndex = 2; break;
736   case 8: SizeIndex = 3; break;
737   case 16: SizeIndex = 4; break;
738   default:
739     Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
740       << FirstArg->getType() << FirstArg->getSourceRange();
741     return ExprError();
742   }
743
744   // Each of these builtins has one pointer argument, followed by some number of
745   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
746   // that we ignore.  Find out which row of BuiltinIndices to read from as well
747   // as the number of fixed args.
748   unsigned BuiltinID = FDecl->getBuiltinID();
749   unsigned BuiltinIndex, NumFixed = 1;
750   switch (BuiltinID) {
751   default: llvm_unreachable("Unknown overloaded atomic builtin!");
752   case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
753   case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
754   case Builtin::BI__sync_fetch_and_or:  BuiltinIndex = 2; break;
755   case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
756   case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
757
758   case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
759   case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
760   case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
761   case Builtin::BI__sync_or_and_fetch:  BuiltinIndex = 8; break;
762   case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
763
764   case Builtin::BI__sync_val_compare_and_swap:
765     BuiltinIndex = 10;
766     NumFixed = 2;
767     break;
768   case Builtin::BI__sync_bool_compare_and_swap:
769     BuiltinIndex = 11;
770     NumFixed = 2;
771     ResultType = Context.BoolTy;
772     break;
773   case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
774   case Builtin::BI__sync_lock_release:
775     BuiltinIndex = 13;
776     NumFixed = 0;
777     ResultType = Context.VoidTy;
778     break;
779   case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
780   }
781
782   // Now that we know how many fixed arguments we expect, first check that we
783   // have at least that many.
784   if (TheCall->getNumArgs() < 1+NumFixed) {
785     Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
786       << 0 << 1+NumFixed << TheCall->getNumArgs()
787       << TheCall->getCallee()->getSourceRange();
788     return ExprError();
789   }
790
791   // Get the decl for the concrete builtin from this, we can tell what the
792   // concrete integer type we should convert to is.
793   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
794   const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
795   IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
796   FunctionDecl *NewBuiltinDecl =
797     cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
798                                            TUScope, false, DRE->getLocStart()));
799
800   // The first argument --- the pointer --- has a fixed type; we
801   // deduce the types of the rest of the arguments accordingly.  Walk
802   // the remaining arguments, converting them to the deduced value type.
803   for (unsigned i = 0; i != NumFixed; ++i) {
804     ExprResult Arg = TheCall->getArg(i+1);
805
806     // GCC does an implicit conversion to the pointer or integer ValType.  This
807     // can fail in some cases (1i -> int**), check for this error case now.
808     // Initialize the argument.
809     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
810                                                    ValType, /*consume*/ false);
811     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
812     if (Arg.isInvalid())
813       return ExprError();
814
815     // Okay, we have something that *can* be converted to the right type.  Check
816     // to see if there is a potentially weird extension going on here.  This can
817     // happen when you do an atomic operation on something like an char* and
818     // pass in 42.  The 42 gets converted to char.  This is even more strange
819     // for things like 45.123 -> char, etc.
820     // FIXME: Do this check.
821     TheCall->setArg(i+1, Arg.take());
822   }
823
824   ASTContext& Context = this->getASTContext();
825
826   // Create a new DeclRefExpr to refer to the new decl.
827   DeclRefExpr* NewDRE = DeclRefExpr::Create(
828       Context,
829       DRE->getQualifierLoc(),
830       NewBuiltinDecl,
831       DRE->getLocation(),
832       NewBuiltinDecl->getType(),
833       DRE->getValueKind());
834
835   // Set the callee in the CallExpr.
836   // FIXME: This leaks the original parens and implicit casts.
837   ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
838   if (PromotedCall.isInvalid())
839     return ExprError();
840   TheCall->setCallee(PromotedCall.take());
841
842   // Change the result type of the call to match the original value type. This
843   // is arbitrary, but the codegen for these builtins ins design to handle it
844   // gracefully.
845   TheCall->setType(ResultType);
846
847   return move(TheCallResult);
848 }
849
850 /// CheckObjCString - Checks that the argument to the builtin
851 /// CFString constructor is correct
852 /// Note: It might also make sense to do the UTF-16 conversion here (would
853 /// simplify the backend).
854 bool Sema::CheckObjCString(Expr *Arg) {
855   Arg = Arg->IgnoreParenCasts();
856   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
857
858   if (!Literal || !Literal->isAscii()) {
859     Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
860       << Arg->getSourceRange();
861     return true;
862   }
863
864   if (Literal->containsNonAsciiOrNull()) {
865     StringRef String = Literal->getString();
866     unsigned NumBytes = String.size();
867     SmallVector<UTF16, 128> ToBuf(NumBytes);
868     const UTF8 *FromPtr = (UTF8 *)String.data();
869     UTF16 *ToPtr = &ToBuf[0];
870     
871     ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
872                                                  &ToPtr, ToPtr + NumBytes,
873                                                  strictConversion);
874     // Check for conversion failure.
875     if (Result != conversionOK)
876       Diag(Arg->getLocStart(),
877            diag::warn_cfstring_truncated) << Arg->getSourceRange();
878   }
879   return false;
880 }
881
882 /// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
883 /// Emit an error and return true on failure, return false on success.
884 bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
885   Expr *Fn = TheCall->getCallee();
886   if (TheCall->getNumArgs() > 2) {
887     Diag(TheCall->getArg(2)->getLocStart(),
888          diag::err_typecheck_call_too_many_args)
889       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
890       << Fn->getSourceRange()
891       << SourceRange(TheCall->getArg(2)->getLocStart(),
892                      (*(TheCall->arg_end()-1))->getLocEnd());
893     return true;
894   }
895
896   if (TheCall->getNumArgs() < 2) {
897     return Diag(TheCall->getLocEnd(),
898       diag::err_typecheck_call_too_few_args_at_least)
899       << 0 /*function call*/ << 2 << TheCall->getNumArgs();
900   }
901
902   // Type-check the first argument normally.
903   if (checkBuiltinArgument(*this, TheCall, 0))
904     return true;
905
906   // Determine whether the current function is variadic or not.
907   BlockScopeInfo *CurBlock = getCurBlock();
908   bool isVariadic;
909   if (CurBlock)
910     isVariadic = CurBlock->TheDecl->isVariadic();
911   else if (FunctionDecl *FD = getCurFunctionDecl())
912     isVariadic = FD->isVariadic();
913   else
914     isVariadic = getCurMethodDecl()->isVariadic();
915
916   if (!isVariadic) {
917     Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
918     return true;
919   }
920
921   // Verify that the second argument to the builtin is the last argument of the
922   // current function or method.
923   bool SecondArgIsLastNamedArgument = false;
924   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
925
926   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
927     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
928       // FIXME: This isn't correct for methods (results in bogus warning).
929       // Get the last formal in the current function.
930       const ParmVarDecl *LastArg;
931       if (CurBlock)
932         LastArg = *(CurBlock->TheDecl->param_end()-1);
933       else if (FunctionDecl *FD = getCurFunctionDecl())
934         LastArg = *(FD->param_end()-1);
935       else
936         LastArg = *(getCurMethodDecl()->param_end()-1);
937       SecondArgIsLastNamedArgument = PV == LastArg;
938     }
939   }
940
941   if (!SecondArgIsLastNamedArgument)
942     Diag(TheCall->getArg(1)->getLocStart(),
943          diag::warn_second_parameter_of_va_start_not_last_named_argument);
944   return false;
945 }
946
947 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
948 /// friends.  This is declared to take (...), so we have to check everything.
949 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
950   if (TheCall->getNumArgs() < 2)
951     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
952       << 0 << 2 << TheCall->getNumArgs()/*function call*/;
953   if (TheCall->getNumArgs() > 2)
954     return Diag(TheCall->getArg(2)->getLocStart(),
955                 diag::err_typecheck_call_too_many_args)
956       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
957       << SourceRange(TheCall->getArg(2)->getLocStart(),
958                      (*(TheCall->arg_end()-1))->getLocEnd());
959
960   ExprResult OrigArg0 = TheCall->getArg(0);
961   ExprResult OrigArg1 = TheCall->getArg(1);
962
963   // Do standard promotions between the two arguments, returning their common
964   // type.
965   QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
966   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
967     return true;
968
969   // Make sure any conversions are pushed back into the call; this is
970   // type safe since unordered compare builtins are declared as "_Bool
971   // foo(...)".
972   TheCall->setArg(0, OrigArg0.get());
973   TheCall->setArg(1, OrigArg1.get());
974
975   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
976     return false;
977
978   // If the common type isn't a real floating type, then the arguments were
979   // invalid for this operation.
980   if (!Res->isRealFloatingType())
981     return Diag(OrigArg0.get()->getLocStart(),
982                 diag::err_typecheck_call_invalid_ordered_compare)
983       << OrigArg0.get()->getType() << OrigArg1.get()->getType()
984       << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
985
986   return false;
987 }
988
989 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
990 /// __builtin_isnan and friends.  This is declared to take (...), so we have
991 /// to check everything. We expect the last argument to be a floating point
992 /// value.
993 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
994   if (TheCall->getNumArgs() < NumArgs)
995     return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
996       << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
997   if (TheCall->getNumArgs() > NumArgs)
998     return Diag(TheCall->getArg(NumArgs)->getLocStart(),
999                 diag::err_typecheck_call_too_many_args)
1000       << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
1001       << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
1002                      (*(TheCall->arg_end()-1))->getLocEnd());
1003
1004   Expr *OrigArg = TheCall->getArg(NumArgs-1);
1005
1006   if (OrigArg->isTypeDependent())
1007     return false;
1008
1009   // This operation requires a non-_Complex floating-point number.
1010   if (!OrigArg->getType()->isRealFloatingType())
1011     return Diag(OrigArg->getLocStart(),
1012                 diag::err_typecheck_call_invalid_unary_fp)
1013       << OrigArg->getType() << OrigArg->getSourceRange();
1014
1015   // If this is an implicit conversion from float -> double, remove it.
1016   if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1017     Expr *CastArg = Cast->getSubExpr();
1018     if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1019       assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1020              "promotion from float to double is the only expected cast here");
1021       Cast->setSubExpr(0);
1022       TheCall->setArg(NumArgs-1, CastArg);
1023       OrigArg = CastArg;
1024     }
1025   }
1026   
1027   return false;
1028 }
1029
1030 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1031 // This is declared to take (...), so we have to check everything.
1032 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
1033   if (TheCall->getNumArgs() < 2)
1034     return ExprError(Diag(TheCall->getLocEnd(),
1035                           diag::err_typecheck_call_too_few_args_at_least)
1036       << 0 /*function call*/ << 2 << TheCall->getNumArgs()
1037       << TheCall->getSourceRange());
1038
1039   // Determine which of the following types of shufflevector we're checking:
1040   // 1) unary, vector mask: (lhs, mask)
1041   // 2) binary, vector mask: (lhs, rhs, mask)
1042   // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1043   QualType resType = TheCall->getArg(0)->getType();
1044   unsigned numElements = 0;
1045   
1046   if (!TheCall->getArg(0)->isTypeDependent() &&
1047       !TheCall->getArg(1)->isTypeDependent()) {
1048     QualType LHSType = TheCall->getArg(0)->getType();
1049     QualType RHSType = TheCall->getArg(1)->getType();
1050     
1051     if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
1052       Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
1053         << SourceRange(TheCall->getArg(0)->getLocStart(),
1054                        TheCall->getArg(1)->getLocEnd());
1055       return ExprError();
1056     }
1057     
1058     numElements = LHSType->getAs<VectorType>()->getNumElements();
1059     unsigned numResElements = TheCall->getNumArgs() - 2;
1060
1061     // Check to see if we have a call with 2 vector arguments, the unary shuffle
1062     // with mask.  If so, verify that RHS is an integer vector type with the
1063     // same number of elts as lhs.
1064     if (TheCall->getNumArgs() == 2) {
1065       if (!RHSType->hasIntegerRepresentation() || 
1066           RHSType->getAs<VectorType>()->getNumElements() != numElements)
1067         Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1068           << SourceRange(TheCall->getArg(1)->getLocStart(),
1069                          TheCall->getArg(1)->getLocEnd());
1070       numResElements = numElements;
1071     }
1072     else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
1073       Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1074         << SourceRange(TheCall->getArg(0)->getLocStart(),
1075                        TheCall->getArg(1)->getLocEnd());
1076       return ExprError();
1077     } else if (numElements != numResElements) {
1078       QualType eltType = LHSType->getAs<VectorType>()->getElementType();
1079       resType = Context.getVectorType(eltType, numResElements,
1080                                       VectorType::GenericVector);
1081     }
1082   }
1083
1084   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
1085     if (TheCall->getArg(i)->isTypeDependent() ||
1086         TheCall->getArg(i)->isValueDependent())
1087       continue;
1088
1089     llvm::APSInt Result(32);
1090     if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1091       return ExprError(Diag(TheCall->getLocStart(),
1092                   diag::err_shufflevector_nonconstant_argument)
1093                 << TheCall->getArg(i)->getSourceRange());
1094
1095     if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
1096       return ExprError(Diag(TheCall->getLocStart(),
1097                   diag::err_shufflevector_argument_too_large)
1098                << TheCall->getArg(i)->getSourceRange());
1099   }
1100
1101   SmallVector<Expr*, 32> exprs;
1102
1103   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
1104     exprs.push_back(TheCall->getArg(i));
1105     TheCall->setArg(i, 0);
1106   }
1107
1108   return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
1109                                             exprs.size(), resType,
1110                                             TheCall->getCallee()->getLocStart(),
1111                                             TheCall->getRParenLoc()));
1112 }
1113
1114 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1115 // This is declared to take (const void*, ...) and can take two
1116 // optional constant int args.
1117 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
1118   unsigned NumArgs = TheCall->getNumArgs();
1119
1120   if (NumArgs > 3)
1121     return Diag(TheCall->getLocEnd(),
1122              diag::err_typecheck_call_too_many_args_at_most)
1123              << 0 /*function call*/ << 3 << NumArgs
1124              << TheCall->getSourceRange();
1125
1126   // Argument 0 is checked for us and the remaining arguments must be
1127   // constant integers.
1128   for (unsigned i = 1; i != NumArgs; ++i) {
1129     Expr *Arg = TheCall->getArg(i);
1130     
1131     llvm::APSInt Result;
1132     if (SemaBuiltinConstantArg(TheCall, i, Result))
1133       return true;
1134
1135     // FIXME: gcc issues a warning and rewrites these to 0. These
1136     // seems especially odd for the third argument since the default
1137     // is 3.
1138     if (i == 1) {
1139       if (Result.getLimitedValue() > 1)
1140         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1141              << "0" << "1" << Arg->getSourceRange();
1142     } else {
1143       if (Result.getLimitedValue() > 3)
1144         return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1145             << "0" << "3" << Arg->getSourceRange();
1146     }
1147   }
1148
1149   return false;
1150 }
1151
1152 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1153 /// TheCall is a constant expression.
1154 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1155                                   llvm::APSInt &Result) {
1156   Expr *Arg = TheCall->getArg(ArgNum);
1157   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1158   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1159   
1160   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1161   
1162   if (!Arg->isIntegerConstantExpr(Result, Context))
1163     return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
1164                 << FDecl->getDeclName() <<  Arg->getSourceRange();
1165   
1166   return false;
1167 }
1168
1169 /// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1170 /// int type). This simply type checks that type is one of the defined
1171 /// constants (0-3).
1172 // For compatibility check 0-3, llvm only handles 0 and 2.
1173 bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
1174   llvm::APSInt Result;
1175   
1176   // Check constant-ness first.
1177   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1178     return true;
1179
1180   Expr *Arg = TheCall->getArg(1);
1181   if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
1182     return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1183              << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1184   }
1185
1186   return false;
1187 }
1188
1189 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
1190 /// This checks that val is a constant 1.
1191 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1192   Expr *Arg = TheCall->getArg(1);
1193   llvm::APSInt Result;
1194
1195   // TODO: This is less than ideal. Overload this to take a value.
1196   if (SemaBuiltinConstantArg(TheCall, 1, Result))
1197     return true;
1198   
1199   if (Result != 1)
1200     return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1201              << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1202
1203   return false;
1204 }
1205
1206 // Handle i > 1 ? "x" : "y", recursively.
1207 bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1208                                   bool HasVAListArg,
1209                                   unsigned format_idx, unsigned firstDataArg,
1210                                   bool isPrintf) {
1211  tryAgain:
1212   if (E->isTypeDependent() || E->isValueDependent())
1213     return false;
1214
1215   E = E->IgnoreParens();
1216
1217   switch (E->getStmtClass()) {
1218   case Stmt::BinaryConditionalOperatorClass:
1219   case Stmt::ConditionalOperatorClass: {
1220     const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
1221     return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1222                                   format_idx, firstDataArg, isPrintf)
1223         && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
1224                                   format_idx, firstDataArg, isPrintf);
1225   }
1226
1227   case Stmt::IntegerLiteralClass:
1228     // Technically -Wformat-nonliteral does not warn about this case.
1229     // The behavior of printf and friends in this case is implementation
1230     // dependent.  Ideally if the format string cannot be null then
1231     // it should have a 'nonnull' attribute in the function prototype.
1232     return true;
1233
1234   case Stmt::ImplicitCastExprClass: {
1235     E = cast<ImplicitCastExpr>(E)->getSubExpr();
1236     goto tryAgain;
1237   }
1238
1239   case Stmt::OpaqueValueExprClass:
1240     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1241       E = src;
1242       goto tryAgain;
1243     }
1244     return false;
1245
1246   case Stmt::PredefinedExprClass:
1247     // While __func__, etc., are technically not string literals, they
1248     // cannot contain format specifiers and thus are not a security
1249     // liability.
1250     return true;
1251       
1252   case Stmt::DeclRefExprClass: {
1253     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
1254
1255     // As an exception, do not flag errors for variables binding to
1256     // const string literals.
1257     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1258       bool isConstant = false;
1259       QualType T = DR->getType();
1260
1261       if (const ArrayType *AT = Context.getAsArrayType(T)) {
1262         isConstant = AT->getElementType().isConstant(Context);
1263       } else if (const PointerType *PT = T->getAs<PointerType>()) {
1264         isConstant = T.isConstant(Context) &&
1265                      PT->getPointeeType().isConstant(Context);
1266       }
1267
1268       if (isConstant) {
1269         if (const Expr *Init = VD->getAnyInitializer())
1270           return SemaCheckStringLiteral(Init, TheCall,
1271                                         HasVAListArg, format_idx, firstDataArg,
1272                                         isPrintf);
1273       }
1274
1275       // For vprintf* functions (i.e., HasVAListArg==true), we add a
1276       // special check to see if the format string is a function parameter
1277       // of the function calling the printf function.  If the function
1278       // has an attribute indicating it is a printf-like function, then we
1279       // should suppress warnings concerning non-literals being used in a call
1280       // to a vprintf function.  For example:
1281       //
1282       // void
1283       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1284       //      va_list ap;
1285       //      va_start(ap, fmt);
1286       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
1287       //      ...
1288       //
1289       //
1290       //  FIXME: We don't have full attribute support yet, so just check to see
1291       //    if the argument is a DeclRefExpr that references a parameter.  We'll
1292       //    add proper support for checking the attribute later.
1293       if (HasVAListArg)
1294         if (isa<ParmVarDecl>(VD))
1295           return true;
1296     }
1297
1298     return false;
1299   }
1300
1301   case Stmt::CallExprClass: {
1302     const CallExpr *CE = cast<CallExpr>(E);
1303     if (const ImplicitCastExpr *ICE
1304           = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1305       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1306         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
1307           if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
1308             unsigned ArgIndex = FA->getFormatIdx();
1309             const Expr *Arg = CE->getArg(ArgIndex - 1);
1310
1311             return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
1312                                           format_idx, firstDataArg, isPrintf);
1313           }
1314         }
1315       }
1316     }
1317
1318     return false;
1319   }
1320   case Stmt::ObjCStringLiteralClass:
1321   case Stmt::StringLiteralClass: {
1322     const StringLiteral *StrE = NULL;
1323
1324     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
1325       StrE = ObjCFExpr->getString();
1326     else
1327       StrE = cast<StringLiteral>(E);
1328
1329     if (StrE) {
1330       CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1331                         firstDataArg, isPrintf);
1332       return true;
1333     }
1334
1335     return false;
1336   }
1337
1338   default:
1339     return false;
1340   }
1341 }
1342
1343 void
1344 Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1345                             const Expr * const *ExprArgs,
1346                             SourceLocation CallSiteLoc) {
1347   for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1348                                   e = NonNull->args_end();
1349        i != e; ++i) {
1350     const Expr *ArgExpr = ExprArgs[*i];
1351     if (ArgExpr->isNullPointerConstant(Context,
1352                                        Expr::NPC_ValueDependentIsNotNull))
1353       Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1354   }
1355 }
1356
1357 /// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1358 /// functions) for correct use of format strings.
1359 void
1360 Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1361                                 unsigned format_idx, unsigned firstDataArg,
1362                                 bool isPrintf) {
1363
1364   const Expr *Fn = TheCall->getCallee();
1365
1366   // The way the format attribute works in GCC, the implicit this argument
1367   // of member functions is counted. However, it doesn't appear in our own
1368   // lists, so decrement format_idx in that case.
1369   if (isa<CXXMemberCallExpr>(TheCall)) {
1370     const CXXMethodDecl *method_decl =
1371       dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1372     if (method_decl && method_decl->isInstance()) {
1373       // Catch a format attribute mistakenly referring to the object argument.
1374       if (format_idx == 0)
1375         return;
1376       --format_idx;
1377       if(firstDataArg != 0)
1378         --firstDataArg;
1379     }
1380   }
1381
1382   // CHECK: printf/scanf-like function is called with no format string.
1383   if (format_idx >= TheCall->getNumArgs()) {
1384     Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
1385       << Fn->getSourceRange();
1386     return;
1387   }
1388
1389   const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
1390
1391   // CHECK: format string is not a string literal.
1392   //
1393   // Dynamically generated format strings are difficult to
1394   // automatically vet at compile time.  Requiring that format strings
1395   // are string literals: (1) permits the checking of format strings by
1396   // the compiler and thereby (2) can practically remove the source of
1397   // many format string exploits.
1398
1399   // Format string can be either ObjC string (e.g. @"%d") or
1400   // C string (e.g. "%d")
1401   // ObjC string uses the same format specifiers as C string, so we can use
1402   // the same format string checking logic for both ObjC and C strings.
1403   if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
1404                              firstDataArg, isPrintf))
1405     return;  // Literal format string found, check done!
1406
1407   // If there are no arguments specified, warn with -Wformat-security, otherwise
1408   // warn only with -Wformat-nonliteral.
1409   if (TheCall->getNumArgs() == format_idx+1)
1410     Diag(TheCall->getArg(format_idx)->getLocStart(),
1411          diag::warn_format_nonliteral_noargs)
1412       << OrigFormatExpr->getSourceRange();
1413   else
1414     Diag(TheCall->getArg(format_idx)->getLocStart(),
1415          diag::warn_format_nonliteral)
1416            << OrigFormatExpr->getSourceRange();
1417 }
1418
1419 namespace {
1420 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1421 protected:
1422   Sema &S;
1423   const StringLiteral *FExpr;
1424   const Expr *OrigFormatExpr;
1425   const unsigned FirstDataArg;
1426   const unsigned NumDataArgs;
1427   const bool IsObjCLiteral;
1428   const char *Beg; // Start of format string.
1429   const bool HasVAListArg;
1430   const CallExpr *TheCall;
1431   unsigned FormatIdx;
1432   llvm::BitVector CoveredArgs;
1433   bool usesPositionalArgs;
1434   bool atFirstArg;
1435 public:
1436   CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
1437                      const Expr *origFormatExpr, unsigned firstDataArg,
1438                      unsigned numDataArgs, bool isObjCLiteral,
1439                      const char *beg, bool hasVAListArg,
1440                      const CallExpr *theCall, unsigned formatIdx)
1441     : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
1442       FirstDataArg(firstDataArg),
1443       NumDataArgs(numDataArgs),
1444       IsObjCLiteral(isObjCLiteral), Beg(beg),
1445       HasVAListArg(hasVAListArg),
1446       TheCall(theCall), FormatIdx(formatIdx),
1447       usesPositionalArgs(false), atFirstArg(true) {
1448         CoveredArgs.resize(numDataArgs);
1449         CoveredArgs.reset();
1450       }
1451
1452   void DoneProcessing();
1453
1454   void HandleIncompleteSpecifier(const char *startSpecifier,
1455                                  unsigned specifierLen);
1456     
1457   virtual void HandleInvalidPosition(const char *startSpecifier,
1458                                      unsigned specifierLen,
1459                                      analyze_format_string::PositionContext p);
1460
1461   virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1462
1463   void HandleNullChar(const char *nullCharacter);
1464
1465 protected:
1466   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1467                                         const char *startSpec,
1468                                         unsigned specifierLen,
1469                                         const char *csStart, unsigned csLen);
1470   
1471   SourceRange getFormatStringRange();
1472   CharSourceRange getSpecifierRange(const char *startSpecifier,
1473                                     unsigned specifierLen);
1474   SourceLocation getLocationOfByte(const char *x);
1475
1476   const Expr *getDataArg(unsigned i) const;
1477   
1478   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1479                     const analyze_format_string::ConversionSpecifier &CS,
1480                     const char *startSpecifier, unsigned specifierLen,
1481                     unsigned argIndex);
1482 };
1483 }
1484
1485 SourceRange CheckFormatHandler::getFormatStringRange() {
1486   return OrigFormatExpr->getSourceRange();
1487 }
1488
1489 CharSourceRange CheckFormatHandler::
1490 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
1491   SourceLocation Start = getLocationOfByte(startSpecifier);
1492   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
1493
1494   // Advance the end SourceLocation by one due to half-open ranges.
1495   End = End.getLocWithOffset(1);
1496
1497   return CharSourceRange::getCharRange(Start, End);
1498 }
1499
1500 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
1501   return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
1502 }
1503
1504 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1505                                                    unsigned specifierLen){
1506   SourceLocation Loc = getLocationOfByte(startSpecifier);
1507   S.Diag(Loc, diag::warn_printf_incomplete_specifier)
1508     << getSpecifierRange(startSpecifier, specifierLen);
1509 }
1510
1511 void
1512 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1513                                      analyze_format_string::PositionContext p) {
1514   SourceLocation Loc = getLocationOfByte(startPos);
1515   S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1516     << (unsigned) p << getSpecifierRange(startPos, posLen);
1517 }
1518
1519 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
1520                                             unsigned posLen) {
1521   SourceLocation Loc = getLocationOfByte(startPos);
1522   S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1523     << getSpecifierRange(startPos, posLen);
1524 }
1525
1526 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1527   if (!IsObjCLiteral) {
1528     // The presence of a null character is likely an error.
1529     S.Diag(getLocationOfByte(nullCharacter),
1530            diag::warn_printf_format_string_contains_null_char)
1531       << getFormatStringRange();
1532   }
1533 }
1534
1535 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1536   return TheCall->getArg(FirstDataArg + i);
1537 }
1538
1539 void CheckFormatHandler::DoneProcessing() {
1540     // Does the number of data arguments exceed the number of
1541     // format conversions in the format string?
1542   if (!HasVAListArg) {
1543       // Find any arguments that weren't covered.
1544     CoveredArgs.flip();
1545     signed notCoveredArg = CoveredArgs.find_first();
1546     if (notCoveredArg >= 0) {
1547       assert((unsigned)notCoveredArg < NumDataArgs);
1548       S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1549              diag::warn_printf_data_arg_not_used)
1550       << getFormatStringRange();
1551     }
1552   }
1553 }
1554
1555 bool
1556 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1557                                                      SourceLocation Loc,
1558                                                      const char *startSpec,
1559                                                      unsigned specifierLen,
1560                                                      const char *csStart,
1561                                                      unsigned csLen) {
1562   
1563   bool keepGoing = true;
1564   if (argIndex < NumDataArgs) {
1565     // Consider the argument coverered, even though the specifier doesn't
1566     // make sense.
1567     CoveredArgs.set(argIndex);
1568   }
1569   else {
1570     // If argIndex exceeds the number of data arguments we
1571     // don't issue a warning because that is just a cascade of warnings (and
1572     // they may have intended '%%' anyway). We don't want to continue processing
1573     // the format string after this point, however, as we will like just get
1574     // gibberish when trying to match arguments.
1575     keepGoing = false;
1576   }
1577   
1578   S.Diag(Loc, diag::warn_format_invalid_conversion)
1579     << StringRef(csStart, csLen)
1580     << getSpecifierRange(startSpec, specifierLen);
1581   
1582   return keepGoing;
1583 }
1584
1585 bool
1586 CheckFormatHandler::CheckNumArgs(
1587   const analyze_format_string::FormatSpecifier &FS,
1588   const analyze_format_string::ConversionSpecifier &CS,
1589   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1590
1591   if (argIndex >= NumDataArgs) {
1592     if (FS.usesPositionalArg())  {
1593       S.Diag(getLocationOfByte(CS.getStart()),
1594              diag::warn_printf_positional_arg_exceeds_data_args)
1595       << (argIndex+1) << NumDataArgs
1596       << getSpecifierRange(startSpecifier, specifierLen);
1597     }
1598     else {
1599       S.Diag(getLocationOfByte(CS.getStart()),
1600              diag::warn_printf_insufficient_data_args)
1601       << getSpecifierRange(startSpecifier, specifierLen);
1602     }
1603     
1604     return false;
1605   }
1606   return true;
1607 }
1608
1609 //===--- CHECK: Printf format string checking ------------------------------===//
1610
1611 namespace {
1612 class CheckPrintfHandler : public CheckFormatHandler {
1613 public:
1614   CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1615                      const Expr *origFormatExpr, unsigned firstDataArg,
1616                      unsigned numDataArgs, bool isObjCLiteral,
1617                      const char *beg, bool hasVAListArg,
1618                      const CallExpr *theCall, unsigned formatIdx)
1619   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1620                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1621                        theCall, formatIdx) {}
1622   
1623   
1624   bool HandleInvalidPrintfConversionSpecifier(
1625                                       const analyze_printf::PrintfSpecifier &FS,
1626                                       const char *startSpecifier,
1627                                       unsigned specifierLen);
1628   
1629   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1630                              const char *startSpecifier,
1631                              unsigned specifierLen);
1632   
1633   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1634                     const char *startSpecifier, unsigned specifierLen);
1635   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1636                            const analyze_printf::OptionalAmount &Amt,
1637                            unsigned type,
1638                            const char *startSpecifier, unsigned specifierLen);
1639   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1640                   const analyze_printf::OptionalFlag &flag,
1641                   const char *startSpecifier, unsigned specifierLen);
1642   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1643                          const analyze_printf::OptionalFlag &ignoredFlag,
1644                          const analyze_printf::OptionalFlag &flag,
1645                          const char *startSpecifier, unsigned specifierLen);
1646 };  
1647 }
1648
1649 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1650                                       const analyze_printf::PrintfSpecifier &FS,
1651                                       const char *startSpecifier,
1652                                       unsigned specifierLen) {
1653   const analyze_printf::PrintfConversionSpecifier &CS =
1654     FS.getConversionSpecifier();
1655   
1656   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1657                                           getLocationOfByte(CS.getStart()),
1658                                           startSpecifier, specifierLen,
1659                                           CS.getStart(), CS.getLength());
1660 }
1661
1662 bool CheckPrintfHandler::HandleAmount(
1663                                const analyze_format_string::OptionalAmount &Amt,
1664                                unsigned k, const char *startSpecifier,
1665                                unsigned specifierLen) {
1666
1667   if (Amt.hasDataArgument()) {
1668     if (!HasVAListArg) {
1669       unsigned argIndex = Amt.getArgIndex();
1670       if (argIndex >= NumDataArgs) {
1671         S.Diag(getLocationOfByte(Amt.getStart()),
1672                diag::warn_printf_asterisk_missing_arg)
1673           << k << getSpecifierRange(startSpecifier, specifierLen);
1674         // Don't do any more checking.  We will just emit
1675         // spurious errors.
1676         return false;
1677       }
1678
1679       // Type check the data argument.  It should be an 'int'.
1680       // Although not in conformance with C99, we also allow the argument to be
1681       // an 'unsigned int' as that is a reasonably safe case.  GCC also
1682       // doesn't emit a warning for that case.
1683       CoveredArgs.set(argIndex);
1684       const Expr *Arg = getDataArg(argIndex);
1685       QualType T = Arg->getType();
1686
1687       const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1688       assert(ATR.isValid());
1689
1690       if (!ATR.matchesType(S.Context, T)) {
1691         S.Diag(getLocationOfByte(Amt.getStart()),
1692                diag::warn_printf_asterisk_wrong_type)
1693           << k
1694           << ATR.getRepresentativeType(S.Context) << T
1695           << getSpecifierRange(startSpecifier, specifierLen)
1696           << Arg->getSourceRange();
1697         // Don't do any more checking.  We will just emit
1698         // spurious errors.
1699         return false;
1700       }
1701     }
1702   }
1703   return true;
1704 }
1705
1706 void CheckPrintfHandler::HandleInvalidAmount(
1707                                       const analyze_printf::PrintfSpecifier &FS,
1708                                       const analyze_printf::OptionalAmount &Amt,
1709                                       unsigned type,
1710                                       const char *startSpecifier,
1711                                       unsigned specifierLen) {
1712   const analyze_printf::PrintfConversionSpecifier &CS =
1713     FS.getConversionSpecifier();
1714   switch (Amt.getHowSpecified()) {
1715   case analyze_printf::OptionalAmount::Constant:
1716     S.Diag(getLocationOfByte(Amt.getStart()),
1717         diag::warn_printf_nonsensical_optional_amount)
1718       << type
1719       << CS.toString()
1720       << getSpecifierRange(startSpecifier, specifierLen)
1721       << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1722           Amt.getConstantLength()));
1723     break;
1724
1725   default:
1726     S.Diag(getLocationOfByte(Amt.getStart()),
1727         diag::warn_printf_nonsensical_optional_amount)
1728       << type
1729       << CS.toString()
1730       << getSpecifierRange(startSpecifier, specifierLen);
1731     break;
1732   }
1733 }
1734
1735 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1736                                     const analyze_printf::OptionalFlag &flag,
1737                                     const char *startSpecifier,
1738                                     unsigned specifierLen) {
1739   // Warn about pointless flag with a fixit removal.
1740   const analyze_printf::PrintfConversionSpecifier &CS =
1741     FS.getConversionSpecifier();
1742   S.Diag(getLocationOfByte(flag.getPosition()),
1743       diag::warn_printf_nonsensical_flag)
1744     << flag.toString() << CS.toString()
1745     << getSpecifierRange(startSpecifier, specifierLen)
1746     << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
1747 }
1748
1749 void CheckPrintfHandler::HandleIgnoredFlag(
1750                                 const analyze_printf::PrintfSpecifier &FS,
1751                                 const analyze_printf::OptionalFlag &ignoredFlag,
1752                                 const analyze_printf::OptionalFlag &flag,
1753                                 const char *startSpecifier,
1754                                 unsigned specifierLen) {
1755   // Warn about ignored flag with a fixit removal.
1756   S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1757       diag::warn_printf_ignored_flag)
1758     << ignoredFlag.toString() << flag.toString()
1759     << getSpecifierRange(startSpecifier, specifierLen)
1760     << FixItHint::CreateRemoval(getSpecifierRange(
1761         ignoredFlag.getPosition(), 1));
1762 }
1763
1764 bool
1765 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
1766                                             &FS,
1767                                           const char *startSpecifier,
1768                                           unsigned specifierLen) {
1769
1770   using namespace analyze_format_string;
1771   using namespace analyze_printf;  
1772   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
1773
1774   if (FS.consumesDataArgument()) {
1775     if (atFirstArg) {
1776         atFirstArg = false;
1777         usesPositionalArgs = FS.usesPositionalArg();
1778     }
1779     else if (usesPositionalArgs != FS.usesPositionalArg()) {
1780       // Cannot mix-and-match positional and non-positional arguments.
1781       S.Diag(getLocationOfByte(CS.getStart()),
1782              diag::warn_format_mix_positional_nonpositional_args)
1783         << getSpecifierRange(startSpecifier, specifierLen);
1784       return false;
1785     }
1786   }
1787
1788   // First check if the field width, precision, and conversion specifier
1789   // have matching data arguments.
1790   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1791                     startSpecifier, specifierLen)) {
1792     return false;
1793   }
1794
1795   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1796                     startSpecifier, specifierLen)) {
1797     return false;
1798   }
1799
1800   if (!CS.consumesDataArgument()) {
1801     // FIXME: Technically specifying a precision or field width here
1802     // makes no sense.  Worth issuing a warning at some point.
1803     return true;
1804   }
1805
1806   // Consume the argument.
1807   unsigned argIndex = FS.getArgIndex();
1808   if (argIndex < NumDataArgs) {
1809     // The check to see if the argIndex is valid will come later.
1810     // We set the bit here because we may exit early from this
1811     // function if we encounter some other error.
1812     CoveredArgs.set(argIndex);
1813   }
1814
1815   // FreeBSD extensions
1816   if (CS.getKind() == ConversionSpecifier::bArg || CS.getKind() == ConversionSpecifier::DArg) { 
1817      // claim the second argument
1818      CoveredArgs.set(argIndex + 1);
1819
1820     // Now type check the data expression that matches the
1821     // format specifier.
1822     const Expr *Ex = getDataArg(argIndex);
1823     const analyze_printf::ArgTypeResult &ATR = 
1824       (CS.getKind() == ConversionSpecifier::bArg) ?
1825         ArgTypeResult(S.Context.IntTy) : ArgTypeResult::CStrTy;
1826     if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType()))
1827       S.Diag(getLocationOfByte(CS.getStart()),
1828              diag::warn_printf_conversion_argument_type_mismatch)
1829         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1830         << getSpecifierRange(startSpecifier, specifierLen)
1831         << Ex->getSourceRange();
1832
1833     // Now type check the data expression that matches the
1834     // format specifier.
1835     Ex = getDataArg(argIndex + 1);
1836     const analyze_printf::ArgTypeResult &ATR2 = ArgTypeResult::CStrTy;
1837     if (ATR2.isValid() && !ATR2.matchesType(S.Context, Ex->getType()))
1838       S.Diag(getLocationOfByte(CS.getStart()),
1839              diag::warn_printf_conversion_argument_type_mismatch)
1840         << ATR2.getRepresentativeType(S.Context) << Ex->getType()
1841         << getSpecifierRange(startSpecifier, specifierLen)
1842         << Ex->getSourceRange();
1843
1844      return true;
1845   }
1846   // END OF FREEBSD EXTENSIONS
1847
1848   // Check for using an Objective-C specific conversion specifier
1849   // in a non-ObjC literal.
1850   if (!IsObjCLiteral && CS.isObjCArg()) {
1851     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1852                                                   specifierLen);
1853   }
1854
1855   // Check for invalid use of field width
1856   if (!FS.hasValidFieldWidth()) {
1857     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
1858         startSpecifier, specifierLen);
1859   }
1860
1861   // Check for invalid use of precision
1862   if (!FS.hasValidPrecision()) {
1863     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1864         startSpecifier, specifierLen);
1865   }
1866
1867   // Check each flag does not conflict with any other component.
1868   if (!FS.hasValidThousandsGroupingPrefix())
1869     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
1870   if (!FS.hasValidLeadingZeros())
1871     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1872   if (!FS.hasValidPlusPrefix())
1873     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
1874   if (!FS.hasValidSpacePrefix())
1875     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
1876   if (!FS.hasValidAlternativeForm())
1877     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1878   if (!FS.hasValidLeftJustified())
1879     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1880
1881   // Check that flags are not ignored by another flag
1882   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1883     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1884         startSpecifier, specifierLen);
1885   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1886     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1887             startSpecifier, specifierLen);
1888
1889   // Check the length modifier is valid with the given conversion specifier.
1890   const LengthModifier &LM = FS.getLengthModifier();
1891   if (!FS.hasValidLengthModifier())
1892     S.Diag(getLocationOfByte(LM.getStart()),
1893         diag::warn_format_nonsensical_length)
1894       << LM.toString() << CS.toString()
1895       << getSpecifierRange(startSpecifier, specifierLen)
1896       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1897           LM.getLength()));
1898
1899   // Are we using '%n'?
1900   if (CS.getKind() == ConversionSpecifier::nArg) {
1901     // Issue a warning about this being a possible security issue.
1902     S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
1903       << getSpecifierRange(startSpecifier, specifierLen);
1904     // Continue checking the other format specifiers.
1905     return true;
1906   }
1907
1908   // The remaining checks depend on the data arguments.
1909   if (HasVAListArg)
1910     return true;
1911
1912   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
1913     return false;
1914
1915   // Now type check the data expression that matches the
1916   // format specifier.
1917   const Expr *Ex = getDataArg(argIndex);
1918   const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1919   if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1920     // Check if we didn't match because of an implicit cast from a 'char'
1921     // or 'short' to an 'int'.  This is done because printf is a varargs
1922     // function.
1923     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
1924       if (ICE->getType() == S.Context.IntTy) {
1925         // All further checking is done on the subexpression.
1926         Ex = ICE->getSubExpr();
1927         if (ATR.matchesType(S.Context, Ex->getType()))
1928           return true;
1929       }
1930
1931     // We may be able to offer a FixItHint if it is a supported type.
1932     PrintfSpecifier fixedFS = FS;
1933     bool success = fixedFS.fixType(Ex->getType());
1934
1935     if (success) {
1936       // Get the fix string from the fixed format specifier
1937       llvm::SmallString<128> buf;
1938       llvm::raw_svector_ostream os(buf);
1939       fixedFS.toString(os);
1940
1941       // FIXME: getRepresentativeType() perhaps should return a string
1942       // instead of a QualType to better handle when the representative
1943       // type is 'wint_t' (which is defined in the system headers).
1944       S.Diag(getLocationOfByte(CS.getStart()),
1945           diag::warn_printf_conversion_argument_type_mismatch)
1946         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1947         << getSpecifierRange(startSpecifier, specifierLen)
1948         << Ex->getSourceRange()
1949         << FixItHint::CreateReplacement(
1950             getSpecifierRange(startSpecifier, specifierLen),
1951             os.str());
1952     }
1953     else {
1954       S.Diag(getLocationOfByte(CS.getStart()),
1955              diag::warn_printf_conversion_argument_type_mismatch)
1956         << ATR.getRepresentativeType(S.Context) << Ex->getType()
1957         << getSpecifierRange(startSpecifier, specifierLen)
1958         << Ex->getSourceRange();
1959     }
1960   }
1961
1962   return true;
1963 }
1964
1965 //===--- CHECK: Scanf format string checking ------------------------------===//
1966
1967 namespace {  
1968 class CheckScanfHandler : public CheckFormatHandler {
1969 public:
1970   CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1971                     const Expr *origFormatExpr, unsigned firstDataArg,
1972                     unsigned numDataArgs, bool isObjCLiteral,
1973                     const char *beg, bool hasVAListArg,
1974                     const CallExpr *theCall, unsigned formatIdx)
1975   : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1976                        numDataArgs, isObjCLiteral, beg, hasVAListArg,
1977                        theCall, formatIdx) {}
1978   
1979   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1980                             const char *startSpecifier,
1981                             unsigned specifierLen);
1982   
1983   bool HandleInvalidScanfConversionSpecifier(
1984           const analyze_scanf::ScanfSpecifier &FS,
1985           const char *startSpecifier,
1986           unsigned specifierLen);
1987
1988   void HandleIncompleteScanList(const char *start, const char *end);
1989 };
1990 }
1991
1992 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1993                                                  const char *end) {
1994   S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1995     << getSpecifierRange(start, end - start);
1996 }
1997
1998 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1999                                         const analyze_scanf::ScanfSpecifier &FS,
2000                                         const char *startSpecifier,
2001                                         unsigned specifierLen) {
2002
2003   const analyze_scanf::ScanfConversionSpecifier &CS =
2004     FS.getConversionSpecifier();
2005
2006   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2007                                           getLocationOfByte(CS.getStart()),
2008                                           startSpecifier, specifierLen,
2009                                           CS.getStart(), CS.getLength());
2010 }
2011
2012 bool CheckScanfHandler::HandleScanfSpecifier(
2013                                        const analyze_scanf::ScanfSpecifier &FS,
2014                                        const char *startSpecifier,
2015                                        unsigned specifierLen) {
2016   
2017   using namespace analyze_scanf;
2018   using namespace analyze_format_string;  
2019
2020   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
2021
2022   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
2023   // be used to decide if we are using positional arguments consistently.
2024   if (FS.consumesDataArgument()) {
2025     if (atFirstArg) {
2026       atFirstArg = false;
2027       usesPositionalArgs = FS.usesPositionalArg();
2028     }
2029     else if (usesPositionalArgs != FS.usesPositionalArg()) {
2030       // Cannot mix-and-match positional and non-positional arguments.
2031       S.Diag(getLocationOfByte(CS.getStart()),
2032              diag::warn_format_mix_positional_nonpositional_args)
2033         << getSpecifierRange(startSpecifier, specifierLen);
2034       return false;
2035     }
2036   }
2037   
2038   // Check if the field with is non-zero.
2039   const OptionalAmount &Amt = FS.getFieldWidth();
2040   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2041     if (Amt.getConstantAmount() == 0) {
2042       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2043                                                    Amt.getConstantLength());
2044       S.Diag(getLocationOfByte(Amt.getStart()),
2045              diag::warn_scanf_nonzero_width)
2046         << R << FixItHint::CreateRemoval(R);
2047     }
2048   }
2049   
2050   if (!FS.consumesDataArgument()) {
2051     // FIXME: Technically specifying a precision or field width here
2052     // makes no sense.  Worth issuing a warning at some point.
2053     return true;
2054   }
2055   
2056   // Consume the argument.
2057   unsigned argIndex = FS.getArgIndex();
2058   if (argIndex < NumDataArgs) {
2059       // The check to see if the argIndex is valid will come later.
2060       // We set the bit here because we may exit early from this
2061       // function if we encounter some other error.
2062     CoveredArgs.set(argIndex);
2063   }
2064   
2065   // Check the length modifier is valid with the given conversion specifier.
2066   const LengthModifier &LM = FS.getLengthModifier();
2067   if (!FS.hasValidLengthModifier()) {
2068     S.Diag(getLocationOfByte(LM.getStart()),
2069            diag::warn_format_nonsensical_length)
2070       << LM.toString() << CS.toString()
2071       << getSpecifierRange(startSpecifier, specifierLen)
2072       << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2073                                                     LM.getLength()));
2074   }
2075
2076   // The remaining checks depend on the data arguments.
2077   if (HasVAListArg)
2078     return true;
2079   
2080   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
2081     return false;
2082   
2083   // FIXME: Check that the argument type matches the format specifier.
2084   
2085   return true;
2086 }
2087
2088 void Sema::CheckFormatString(const StringLiteral *FExpr,
2089                              const Expr *OrigFormatExpr,
2090                              const CallExpr *TheCall, bool HasVAListArg,
2091                              unsigned format_idx, unsigned firstDataArg,
2092                              bool isPrintf) {
2093   
2094   // CHECK: is the format string a wide literal?
2095   if (!FExpr->isAscii()) {
2096     Diag(FExpr->getLocStart(),
2097          diag::warn_format_string_is_wide_literal)
2098     << OrigFormatExpr->getSourceRange();
2099     return;
2100   }
2101   
2102   // Str - The format string.  NOTE: this is NOT null-terminated!
2103   StringRef StrRef = FExpr->getString();
2104   const char *Str = StrRef.data();
2105   unsigned StrLen = StrRef.size();
2106   const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
2107   
2108   // CHECK: empty format string?
2109   if (StrLen == 0 && numDataArgs > 0) {
2110     Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
2111     << OrigFormatExpr->getSourceRange();
2112     return;
2113   }
2114   
2115   if (isPrintf) {
2116     CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2117                          numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2118                          Str, HasVAListArg, TheCall, format_idx);
2119   
2120     bool FormatExtensions = getLangOptions().FormatExtensions;
2121     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
2122                                                   FormatExtensions))
2123       H.DoneProcessing();
2124   }
2125   else {
2126     CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
2127                         numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2128                         Str, HasVAListArg, TheCall, format_idx);
2129     
2130     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2131       H.DoneProcessing();
2132   }
2133 }
2134
2135 //===--- CHECK: Standard memory functions ---------------------------------===//
2136
2137 /// \brief Determine whether the given type is a dynamic class type (e.g.,
2138 /// whether it has a vtable).
2139 static bool isDynamicClassType(QualType T) {
2140   if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2141     if (CXXRecordDecl *Definition = Record->getDefinition())
2142       if (Definition->isDynamicClass())
2143         return true;
2144   
2145   return false;
2146 }
2147
2148 /// \brief If E is a sizeof expression, returns its argument expression,
2149 /// otherwise returns NULL.
2150 static const Expr *getSizeOfExprArg(const Expr* E) {
2151   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2152       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2153     if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2154       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
2155
2156   return 0;
2157 }
2158
2159 /// \brief If E is a sizeof expression, returns its argument type.
2160 static QualType getSizeOfArgType(const Expr* E) {
2161   if (const UnaryExprOrTypeTraitExpr *SizeOf =
2162       dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2163     if (SizeOf->getKind() == clang::UETT_SizeOf)
2164       return SizeOf->getTypeOfArgument();
2165
2166   return QualType();
2167 }
2168
2169 /// \brief Check for dangerous or invalid arguments to memset().
2170 ///
2171 /// This issues warnings on known problematic, dangerous or unspecified
2172 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2173 /// function calls.
2174 ///
2175 /// \param Call The call expression to diagnose.
2176 void Sema::CheckMemaccessArguments(const CallExpr *Call,
2177                                    CheckedMemoryFunction CMF,
2178                                    IdentifierInfo *FnName) {
2179   // It is possible to have a non-standard definition of memset.  Validate
2180   // we have enough arguments, and if not, abort further checking.
2181   unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2182   if (Call->getNumArgs() < ExpectedNumArgs)
2183     return;
2184
2185   unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2186   unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2187   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
2188
2189   // We have special checking when the length is a sizeof expression.
2190   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2191   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2192   llvm::FoldingSetNodeID SizeOfArgID;
2193
2194   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2195     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
2196     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
2197
2198     QualType DestTy = Dest->getType();
2199     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2200       QualType PointeeTy = DestPtrTy->getPointeeType();
2201
2202       // Never warn about void type pointers. This can be used to suppress
2203       // false positives.
2204       if (PointeeTy->isVoidType())
2205         continue;
2206
2207       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2208       // actually comparing the expressions for equality. Because computing the
2209       // expression IDs can be expensive, we only do this if the diagnostic is
2210       // enabled.
2211       if (SizeOfArg &&
2212           Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2213                                    SizeOfArg->getExprLoc())) {
2214         // We only compute IDs for expressions if the warning is enabled, and
2215         // cache the sizeof arg's ID.
2216         if (SizeOfArgID == llvm::FoldingSetNodeID())
2217           SizeOfArg->Profile(SizeOfArgID, Context, true);
2218         llvm::FoldingSetNodeID DestID;
2219         Dest->Profile(DestID, Context, true);
2220         if (DestID == SizeOfArgID) {
2221           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2222           //       over sizeof(src) as well.
2223           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2224           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2225             if (UnaryOp->getOpcode() == UO_AddrOf)
2226               ActionIdx = 1; // If its an address-of operator, just remove it.
2227           if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2228             ActionIdx = 2; // If the pointee's size is sizeof(char),
2229                            // suggest an explicit length.
2230           unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
2231           DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2232                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
2233                                 << FnName << DestSrcSelect << ActionIdx
2234                                 << Dest->getSourceRange()
2235                                 << SizeOfArg->getSourceRange());
2236           break;
2237         }
2238       }
2239
2240       // Also check for cases where the sizeof argument is the exact same
2241       // type as the memory argument, and where it points to a user-defined
2242       // record type.
2243       if (SizeOfArgTy != QualType()) {
2244         if (PointeeTy->isRecordType() &&
2245             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2246           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2247                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
2248                                 << FnName << SizeOfArgTy << ArgIdx
2249                                 << PointeeTy << Dest->getSourceRange()
2250                                 << LenExpr->getSourceRange());
2251           break;
2252         }
2253       }
2254
2255       // Always complain about dynamic classes.
2256       if (isDynamicClassType(PointeeTy))
2257         DiagRuntimeBehavior(
2258           Dest->getExprLoc(), Dest,
2259           PDiag(diag::warn_dyn_class_memaccess)
2260             << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2261             // "overwritten" if we're warning about the destination for any call
2262             // but memcmp; otherwise a verb appropriate to the call.
2263             << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2264             << Call->getCallee()->getSourceRange());
2265       else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
2266         DiagRuntimeBehavior(
2267           Dest->getExprLoc(), Dest,
2268           PDiag(diag::warn_arc_object_memaccess)
2269             << ArgIdx << FnName << PointeeTy
2270             << Call->getCallee()->getSourceRange());
2271       else
2272         continue;
2273
2274       DiagRuntimeBehavior(
2275         Dest->getExprLoc(), Dest,
2276         PDiag(diag::note_bad_memaccess_silence)
2277           << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2278       break;
2279     }
2280   }
2281 }
2282
2283 // A little helper routine: ignore addition and subtraction of integer literals.
2284 // This intentionally does not ignore all integer constant expressions because
2285 // we don't want to remove sizeof().
2286 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2287   Ex = Ex->IgnoreParenCasts();
2288
2289   for (;;) {
2290     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2291     if (!BO || !BO->isAdditiveOp())
2292       break;
2293
2294     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2295     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2296     
2297     if (isa<IntegerLiteral>(RHS))
2298       Ex = LHS;
2299     else if (isa<IntegerLiteral>(LHS))
2300       Ex = RHS;
2301     else
2302       break;
2303   }
2304
2305   return Ex;
2306 }
2307
2308 // Warn if the user has made the 'size' argument to strlcpy or strlcat
2309 // be the size of the source, instead of the destination.
2310 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2311                                     IdentifierInfo *FnName) {
2312
2313   // Don't crash if the user has the wrong number of arguments
2314   if (Call->getNumArgs() != 3)
2315     return;
2316
2317   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2318   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2319   const Expr *CompareWithSrc = NULL;
2320   
2321   // Look for 'strlcpy(dst, x, sizeof(x))'
2322   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2323     CompareWithSrc = Ex;
2324   else {
2325     // Look for 'strlcpy(dst, x, strlen(x))'
2326     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2327       if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2328           && SizeCall->getNumArgs() == 1)
2329         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2330     }
2331   }
2332
2333   if (!CompareWithSrc)
2334     return;
2335
2336   // Determine if the argument to sizeof/strlen is equal to the source
2337   // argument.  In principle there's all kinds of things you could do
2338   // here, for instance creating an == expression and evaluating it with
2339   // EvaluateAsBooleanCondition, but this uses a more direct technique:
2340   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2341   if (!SrcArgDRE)
2342     return;
2343   
2344   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2345   if (!CompareWithSrcDRE || 
2346       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2347     return;
2348   
2349   const Expr *OriginalSizeArg = Call->getArg(2);
2350   Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2351     << OriginalSizeArg->getSourceRange() << FnName;
2352   
2353   // Output a FIXIT hint if the destination is an array (rather than a
2354   // pointer to an array).  This could be enhanced to handle some
2355   // pointers if we know the actual size, like if DstArg is 'array+2'
2356   // we could say 'sizeof(array)-2'.
2357   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
2358   QualType DstArgTy = DstArg->getType();
2359   
2360   // Only handle constant-sized or VLAs, but not flexible members.
2361   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2362     // Only issue the FIXIT for arrays of size > 1.
2363     if (CAT->getSize().getSExtValue() <= 1)
2364       return;
2365   } else if (!DstArgTy->isVariableArrayType()) {
2366     return;
2367   }
2368
2369   llvm::SmallString<128> sizeString;
2370   llvm::raw_svector_ostream OS(sizeString);
2371   OS << "sizeof(";
2372   DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
2373   OS << ")";
2374   
2375   Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2376     << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2377                                     OS.str());
2378 }
2379
2380 //===--- CHECK: Return Address of Stack Variable --------------------------===//
2381
2382 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2383 static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
2384
2385 /// CheckReturnStackAddr - Check if a return statement returns the address
2386 ///   of a stack variable.
2387 void
2388 Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2389                            SourceLocation ReturnLoc) {
2390
2391   Expr *stackE = 0;
2392   SmallVector<DeclRefExpr *, 8> refVars;
2393
2394   // Perform checking for returned stack addresses, local blocks,
2395   // label addresses or references to temporaries.
2396   if (lhsType->isPointerType() ||
2397       (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
2398     stackE = EvalAddr(RetValExp, refVars);
2399   } else if (lhsType->isReferenceType()) {
2400     stackE = EvalVal(RetValExp, refVars);
2401   }
2402
2403   if (stackE == 0)
2404     return; // Nothing suspicious was found.
2405
2406   SourceLocation diagLoc;
2407   SourceRange diagRange;
2408   if (refVars.empty()) {
2409     diagLoc = stackE->getLocStart();
2410     diagRange = stackE->getSourceRange();
2411   } else {
2412     // We followed through a reference variable. 'stackE' contains the
2413     // problematic expression but we will warn at the return statement pointing
2414     // at the reference variable. We will later display the "trail" of
2415     // reference variables using notes.
2416     diagLoc = refVars[0]->getLocStart();
2417     diagRange = refVars[0]->getSourceRange();
2418   }
2419
2420   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2421     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2422                                              : diag::warn_ret_stack_addr)
2423      << DR->getDecl()->getDeclName() << diagRange;
2424   } else if (isa<BlockExpr>(stackE)) { // local block.
2425     Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2426   } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2427     Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2428   } else { // local temporary.
2429     Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2430                                              : diag::warn_ret_local_temp_addr)
2431      << diagRange;
2432   }
2433
2434   // Display the "trail" of reference variables that we followed until we
2435   // found the problematic expression using notes.
2436   for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2437     VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2438     // If this var binds to another reference var, show the range of the next
2439     // var, otherwise the var binds to the problematic expression, in which case
2440     // show the range of the expression.
2441     SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2442                                   : stackE->getSourceRange();
2443     Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2444       << VD->getDeclName() << range;
2445   }
2446 }
2447
2448 /// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2449 ///  check if the expression in a return statement evaluates to an address
2450 ///  to a location on the stack, a local block, an address of a label, or a
2451 ///  reference to local temporary. The recursion is used to traverse the
2452 ///  AST of the return expression, with recursion backtracking when we
2453 ///  encounter a subexpression that (1) clearly does not lead to one of the
2454 ///  above problematic expressions (2) is something we cannot determine leads to
2455 ///  a problematic expression based on such local checking.
2456 ///
2457 ///  Both EvalAddr and EvalVal follow through reference variables to evaluate
2458 ///  the expression that they point to. Such variables are added to the
2459 ///  'refVars' vector so that we know what the reference variable "trail" was.
2460 ///
2461 ///  EvalAddr processes expressions that are pointers that are used as
2462 ///  references (and not L-values).  EvalVal handles all other values.
2463 ///  At the base case of the recursion is a check for the above problematic
2464 ///  expressions.
2465 ///
2466 ///  This implementation handles:
2467 ///
2468 ///   * pointer-to-pointer casts
2469 ///   * implicit conversions from array references to pointers
2470 ///   * taking the address of fields
2471 ///   * arbitrary interplay between "&" and "*" operators
2472 ///   * pointer arithmetic from an address of a stack variable
2473 ///   * taking the address of an array element where the array is on the stack
2474 static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2475   if (E->isTypeDependent())
2476       return NULL;
2477
2478   // We should only be called for evaluating pointer expressions.
2479   assert((E->getType()->isAnyPointerType() ||
2480           E->getType()->isBlockPointerType() ||
2481           E->getType()->isObjCQualifiedIdType()) &&
2482          "EvalAddr only works on pointers");
2483
2484   E = E->IgnoreParens();
2485
2486   // Our "symbolic interpreter" is just a dispatch off the currently
2487   // viewed AST node.  We then recursively traverse the AST by calling
2488   // EvalAddr and EvalVal appropriately.
2489   switch (E->getStmtClass()) {
2490   case Stmt::DeclRefExprClass: {
2491     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2492
2493     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2494       // If this is a reference variable, follow through to the expression that
2495       // it points to.
2496       if (V->hasLocalStorage() &&
2497           V->getType()->isReferenceType() && V->hasInit()) {
2498         // Add the reference variable to the "trail".
2499         refVars.push_back(DR);
2500         return EvalAddr(V->getInit(), refVars);
2501       }
2502
2503     return NULL;
2504   }
2505
2506   case Stmt::UnaryOperatorClass: {
2507     // The only unary operator that make sense to handle here
2508     // is AddrOf.  All others don't make sense as pointers.
2509     UnaryOperator *U = cast<UnaryOperator>(E);
2510
2511     if (U->getOpcode() == UO_AddrOf)
2512       return EvalVal(U->getSubExpr(), refVars);
2513     else
2514       return NULL;
2515   }
2516
2517   case Stmt::BinaryOperatorClass: {
2518     // Handle pointer arithmetic.  All other binary operators are not valid
2519     // in this context.
2520     BinaryOperator *B = cast<BinaryOperator>(E);
2521     BinaryOperatorKind op = B->getOpcode();
2522
2523     if (op != BO_Add && op != BO_Sub)
2524       return NULL;
2525
2526     Expr *Base = B->getLHS();
2527
2528     // Determine which argument is the real pointer base.  It could be
2529     // the RHS argument instead of the LHS.
2530     if (!Base->getType()->isPointerType()) Base = B->getRHS();
2531
2532     assert (Base->getType()->isPointerType());
2533     return EvalAddr(Base, refVars);
2534   }
2535
2536   // For conditional operators we need to see if either the LHS or RHS are
2537   // valid DeclRefExpr*s.  If one of them is valid, we return it.
2538   case Stmt::ConditionalOperatorClass: {
2539     ConditionalOperator *C = cast<ConditionalOperator>(E);
2540
2541     // Handle the GNU extension for missing LHS.
2542     if (Expr *lhsExpr = C->getLHS()) {
2543     // In C++, we can have a throw-expression, which has 'void' type.
2544       if (!lhsExpr->getType()->isVoidType())
2545         if (Expr* LHS = EvalAddr(lhsExpr, refVars))
2546           return LHS;
2547     }
2548
2549     // In C++, we can have a throw-expression, which has 'void' type.
2550     if (C->getRHS()->getType()->isVoidType())
2551       return NULL;
2552
2553     return EvalAddr(C->getRHS(), refVars);
2554   }
2555   
2556   case Stmt::BlockExprClass:
2557     if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
2558       return E; // local block.
2559     return NULL;
2560
2561   case Stmt::AddrLabelExprClass:
2562     return E; // address of label.
2563
2564   // For casts, we need to handle conversions from arrays to
2565   // pointer values, and pointer-to-pointer conversions.
2566   case Stmt::ImplicitCastExprClass:
2567   case Stmt::CStyleCastExprClass:
2568   case Stmt::CXXFunctionalCastExprClass:
2569   case Stmt::ObjCBridgedCastExprClass: {
2570     Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2571     QualType T = SubExpr->getType();
2572
2573     if (SubExpr->getType()->isPointerType() ||
2574         SubExpr->getType()->isBlockPointerType() ||
2575         SubExpr->getType()->isObjCQualifiedIdType())
2576       return EvalAddr(SubExpr, refVars);
2577     else if (T->isArrayType())
2578       return EvalVal(SubExpr, refVars);
2579     else
2580       return 0;
2581   }
2582
2583   // C++ casts.  For dynamic casts, static casts, and const casts, we
2584   // are always converting from a pointer-to-pointer, so we just blow
2585   // through the cast.  In the case the dynamic cast doesn't fail (and
2586   // return NULL), we take the conservative route and report cases
2587   // where we return the address of a stack variable.  For Reinterpre
2588   // FIXME: The comment about is wrong; we're not always converting
2589   // from pointer to pointer. I'm guessing that this code should also
2590   // handle references to objects.
2591   case Stmt::CXXStaticCastExprClass:
2592   case Stmt::CXXDynamicCastExprClass:
2593   case Stmt::CXXConstCastExprClass:
2594   case Stmt::CXXReinterpretCastExprClass: {
2595       Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
2596       if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
2597         return EvalAddr(S, refVars);
2598       else
2599         return NULL;
2600   }
2601
2602   case Stmt::MaterializeTemporaryExprClass:
2603     if (Expr *Result = EvalAddr(
2604                          cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2605                                 refVars))
2606       return Result;
2607       
2608     return E;
2609       
2610   // Everything else: we simply don't reason about them.
2611   default:
2612     return NULL;
2613   }
2614 }
2615
2616
2617 ///  EvalVal - This function is complements EvalAddr in the mutual recursion.
2618 ///   See the comments for EvalAddr for more details.
2619 static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
2620 do {
2621   // We should only be called for evaluating non-pointer expressions, or
2622   // expressions with a pointer type that are not used as references but instead
2623   // are l-values (e.g., DeclRefExpr with a pointer type).
2624
2625   // Our "symbolic interpreter" is just a dispatch off the currently
2626   // viewed AST node.  We then recursively traverse the AST by calling
2627   // EvalAddr and EvalVal appropriately.
2628
2629   E = E->IgnoreParens();
2630   switch (E->getStmtClass()) {
2631   case Stmt::ImplicitCastExprClass: {
2632     ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
2633     if (IE->getValueKind() == VK_LValue) {
2634       E = IE->getSubExpr();
2635       continue;
2636     }
2637     return NULL;
2638   }
2639
2640   case Stmt::DeclRefExprClass: {
2641     // When we hit a DeclRefExpr we are looking at code that refers to a
2642     // variable's name. If it's not a reference variable we check if it has
2643     // local storage within the function, and if so, return the expression.
2644     DeclRefExpr *DR = cast<DeclRefExpr>(E);
2645
2646     if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2647       if (V->hasLocalStorage()) {
2648         if (!V->getType()->isReferenceType())
2649           return DR;
2650
2651         // Reference variable, follow through to the expression that
2652         // it points to.
2653         if (V->hasInit()) {
2654           // Add the reference variable to the "trail".
2655           refVars.push_back(DR);
2656           return EvalVal(V->getInit(), refVars);
2657         }
2658       }
2659
2660     return NULL;
2661   }
2662
2663   case Stmt::UnaryOperatorClass: {
2664     // The only unary operator that make sense to handle here
2665     // is Deref.  All others don't resolve to a "name."  This includes
2666     // handling all sorts of rvalues passed to a unary operator.
2667     UnaryOperator *U = cast<UnaryOperator>(E);
2668
2669     if (U->getOpcode() == UO_Deref)
2670       return EvalAddr(U->getSubExpr(), refVars);
2671
2672     return NULL;
2673   }
2674
2675   case Stmt::ArraySubscriptExprClass: {
2676     // Array subscripts are potential references to data on the stack.  We
2677     // retrieve the DeclRefExpr* for the array variable if it indeed
2678     // has local storage.
2679     return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
2680   }
2681
2682   case Stmt::ConditionalOperatorClass: {
2683     // For conditional operators we need to see if either the LHS or RHS are
2684     // non-NULL Expr's.  If one is non-NULL, we return it.
2685     ConditionalOperator *C = cast<ConditionalOperator>(E);
2686
2687     // Handle the GNU extension for missing LHS.
2688     if (Expr *lhsExpr = C->getLHS())
2689       if (Expr *LHS = EvalVal(lhsExpr, refVars))
2690         return LHS;
2691
2692     return EvalVal(C->getRHS(), refVars);
2693   }
2694
2695   // Accesses to members are potential references to data on the stack.
2696   case Stmt::MemberExprClass: {
2697     MemberExpr *M = cast<MemberExpr>(E);
2698
2699     // Check for indirect access.  We only want direct field accesses.
2700     if (M->isArrow())
2701       return NULL;
2702
2703     // Check whether the member type is itself a reference, in which case
2704     // we're not going to refer to the member, but to what the member refers to.
2705     if (M->getMemberDecl()->getType()->isReferenceType())
2706       return NULL;
2707
2708     return EvalVal(M->getBase(), refVars);
2709   }
2710
2711   case Stmt::MaterializeTemporaryExprClass:
2712     if (Expr *Result = EvalVal(
2713                           cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2714                                refVars))
2715       return Result;
2716       
2717     return E;
2718
2719   default:
2720     // Check that we don't return or take the address of a reference to a
2721     // temporary. This is only useful in C++.
2722     if (!E->isTypeDependent() && E->isRValue())
2723       return E;
2724
2725     // Everything else: we simply don't reason about them.
2726     return NULL;
2727   }
2728 } while (true);
2729 }
2730
2731 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2732
2733 /// Check for comparisons of floating point operands using != and ==.
2734 /// Issue a warning if these are no self-comparisons, as they are not likely
2735 /// to do what the programmer intended.
2736 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
2737   bool EmitWarning = true;
2738
2739   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2740   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
2741
2742   // Special case: check for x == x (which is OK).
2743   // Do not emit warnings for such cases.
2744   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2745     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2746       if (DRL->getDecl() == DRR->getDecl())
2747         EmitWarning = false;
2748
2749
2750   // Special case: check for comparisons against literals that can be exactly
2751   //  represented by APFloat.  In such cases, do not emit a warning.  This
2752   //  is a heuristic: often comparison against such literals are used to
2753   //  detect if a value in a variable has not changed.  This clearly can
2754   //  lead to false negatives.
2755   if (EmitWarning) {
2756     if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2757       if (FLL->isExact())
2758         EmitWarning = false;
2759     } else
2760       if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2761         if (FLR->isExact())
2762           EmitWarning = false;
2763     }
2764   }
2765
2766   // Check for comparisons with builtin types.
2767   if (EmitWarning)
2768     if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
2769       if (CL->isBuiltinCall(Context))
2770         EmitWarning = false;
2771
2772   if (EmitWarning)
2773     if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
2774       if (CR->isBuiltinCall(Context))
2775         EmitWarning = false;
2776
2777   // Emit the diagnostic.
2778   if (EmitWarning)
2779     Diag(Loc, diag::warn_floatingpoint_eq)
2780       << LHS->getSourceRange() << RHS->getSourceRange();
2781 }
2782
2783 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2784 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
2785
2786 namespace {
2787
2788 /// Structure recording the 'active' range of an integer-valued
2789 /// expression.
2790 struct IntRange {
2791   /// The number of bits active in the int.
2792   unsigned Width;
2793
2794   /// True if the int is known not to have negative values.
2795   bool NonNegative;
2796
2797   IntRange(unsigned Width, bool NonNegative)
2798     : Width(Width), NonNegative(NonNegative)
2799   {}
2800
2801   /// Returns the range of the bool type.
2802   static IntRange forBoolType() {
2803     return IntRange(1, true);
2804   }
2805
2806   /// Returns the range of an opaque value of the given integral type.
2807   static IntRange forValueOfType(ASTContext &C, QualType T) {
2808     return forValueOfCanonicalType(C,
2809                           T->getCanonicalTypeInternal().getTypePtr());
2810   }
2811
2812   /// Returns the range of an opaque value of a canonical integral type.
2813   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
2814     assert(T->isCanonicalUnqualified());
2815
2816     if (const VectorType *VT = dyn_cast<VectorType>(T))
2817       T = VT->getElementType().getTypePtr();
2818     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2819       T = CT->getElementType().getTypePtr();
2820
2821     // For enum types, use the known bit width of the enumerators.
2822     if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2823       EnumDecl *Enum = ET->getDecl();
2824       if (!Enum->isCompleteDefinition())
2825         return IntRange(C.getIntWidth(QualType(T, 0)), false);
2826
2827       unsigned NumPositive = Enum->getNumPositiveBits();
2828       unsigned NumNegative = Enum->getNumNegativeBits();
2829
2830       return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2831     }
2832
2833     const BuiltinType *BT = cast<BuiltinType>(T);
2834     assert(BT->isInteger());
2835
2836     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2837   }
2838
2839   /// Returns the "target" range of a canonical integral type, i.e.
2840   /// the range of values expressible in the type.
2841   ///
2842   /// This matches forValueOfCanonicalType except that enums have the
2843   /// full range of their type, not the range of their enumerators.
2844   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2845     assert(T->isCanonicalUnqualified());
2846
2847     if (const VectorType *VT = dyn_cast<VectorType>(T))
2848       T = VT->getElementType().getTypePtr();
2849     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2850       T = CT->getElementType().getTypePtr();
2851     if (const EnumType *ET = dyn_cast<EnumType>(T))
2852       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
2853
2854     const BuiltinType *BT = cast<BuiltinType>(T);
2855     assert(BT->isInteger());
2856
2857     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2858   }
2859
2860   /// Returns the supremum of two ranges: i.e. their conservative merge.
2861   static IntRange join(IntRange L, IntRange R) {
2862     return IntRange(std::max(L.Width, R.Width),
2863                     L.NonNegative && R.NonNegative);
2864   }
2865
2866   /// Returns the infinum of two ranges: i.e. their aggressive merge.
2867   static IntRange meet(IntRange L, IntRange R) {
2868     return IntRange(std::min(L.Width, R.Width),
2869                     L.NonNegative || R.NonNegative);
2870   }
2871 };
2872
2873 IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2874   if (value.isSigned() && value.isNegative())
2875     return IntRange(value.getMinSignedBits(), false);
2876
2877   if (value.getBitWidth() > MaxWidth)
2878     value = value.trunc(MaxWidth);
2879
2880   // isNonNegative() just checks the sign bit without considering
2881   // signedness.
2882   return IntRange(value.getActiveBits(), true);
2883 }
2884
2885 IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
2886                        unsigned MaxWidth) {
2887   if (result.isInt())
2888     return GetValueRange(C, result.getInt(), MaxWidth);
2889
2890   if (result.isVector()) {
2891     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2892     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2893       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2894       R = IntRange::join(R, El);
2895     }
2896     return R;
2897   }
2898
2899   if (result.isComplexInt()) {
2900     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2901     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2902     return IntRange::join(R, I);
2903   }
2904
2905   // This can happen with lossless casts to intptr_t of "based" lvalues.
2906   // Assume it might use arbitrary bits.
2907   // FIXME: The only reason we need to pass the type in here is to get
2908   // the sign right on this one case.  It would be nice if APValue
2909   // preserved this.
2910   assert(result.isLValue());
2911   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
2912 }
2913
2914 /// Pseudo-evaluate the given integer expression, estimating the
2915 /// range of values it might take.
2916 ///
2917 /// \param MaxWidth - the width to which the value will be truncated
2918 IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2919   E = E->IgnoreParens();
2920
2921   // Try a full evaluation first.
2922   Expr::EvalResult result;
2923   if (E->Evaluate(result, C))
2924     return GetValueRange(C, result.Val, E->getType(), MaxWidth);
2925
2926   // I think we only want to look through implicit casts here; if the
2927   // user has an explicit widening cast, we should treat the value as
2928   // being of the new, wider type.
2929   if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
2930     if (CE->getCastKind() == CK_NoOp)
2931       return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2932
2933     IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
2934
2935     bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
2936
2937     // Assume that non-integer casts can span the full range of the type.
2938     if (!isIntegerCast)
2939       return OutputTypeRange;
2940
2941     IntRange SubRange
2942       = GetExprRange(C, CE->getSubExpr(),
2943                      std::min(MaxWidth, OutputTypeRange.Width));
2944
2945     // Bail out if the subexpr's range is as wide as the cast type.
2946     if (SubRange.Width >= OutputTypeRange.Width)
2947       return OutputTypeRange;
2948
2949     // Otherwise, we take the smaller width, and we're non-negative if
2950     // either the output type or the subexpr is.
2951     return IntRange(SubRange.Width,
2952                     SubRange.NonNegative || OutputTypeRange.NonNegative);
2953   }
2954
2955   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2956     // If we can fold the condition, just take that operand.
2957     bool CondResult;
2958     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2959       return GetExprRange(C, CondResult ? CO->getTrueExpr()
2960                                         : CO->getFalseExpr(),
2961                           MaxWidth);
2962
2963     // Otherwise, conservatively merge.
2964     IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2965     IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2966     return IntRange::join(L, R);
2967   }
2968
2969   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2970     switch (BO->getOpcode()) {
2971
2972     // Boolean-valued operations are single-bit and positive.
2973     case BO_LAnd:
2974     case BO_LOr:
2975     case BO_LT:
2976     case BO_GT:
2977     case BO_LE:
2978     case BO_GE:
2979     case BO_EQ:
2980     case BO_NE:
2981       return IntRange::forBoolType();
2982
2983     // The type of the assignments is the type of the LHS, so the RHS
2984     // is not necessarily the same type.
2985     case BO_MulAssign:
2986     case BO_DivAssign:
2987     case BO_RemAssign:
2988     case BO_AddAssign:
2989     case BO_SubAssign:
2990     case BO_XorAssign:
2991     case BO_OrAssign:
2992       // TODO: bitfields?
2993       return IntRange::forValueOfType(C, E->getType());
2994
2995     // Simple assignments just pass through the RHS, which will have
2996     // been coerced to the LHS type.
2997     case BO_Assign:
2998       // TODO: bitfields?
2999       return GetExprRange(C, BO->getRHS(), MaxWidth);
3000
3001     // Operations with opaque sources are black-listed.
3002     case BO_PtrMemD:
3003     case BO_PtrMemI:
3004       return IntRange::forValueOfType(C, E->getType());
3005
3006     // Bitwise-and uses the *infinum* of the two source ranges.
3007     case BO_And:
3008     case BO_AndAssign:
3009       return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3010                             GetExprRange(C, BO->getRHS(), MaxWidth));
3011
3012     // Left shift gets black-listed based on a judgement call.
3013     case BO_Shl:
3014       // ...except that we want to treat '1 << (blah)' as logically
3015       // positive.  It's an important idiom.
3016       if (IntegerLiteral *I
3017             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3018         if (I->getValue() == 1) {
3019           IntRange R = IntRange::forValueOfType(C, E->getType());
3020           return IntRange(R.Width, /*NonNegative*/ true);
3021         }
3022       }
3023       // fallthrough
3024
3025     case BO_ShlAssign:
3026       return IntRange::forValueOfType(C, E->getType());
3027
3028     // Right shift by a constant can narrow its left argument.
3029     case BO_Shr:
3030     case BO_ShrAssign: {
3031       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3032
3033       // If the shift amount is a positive constant, drop the width by
3034       // that much.
3035       llvm::APSInt shift;
3036       if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3037           shift.isNonNegative()) {
3038         unsigned zext = shift.getZExtValue();
3039         if (zext >= L.Width)
3040           L.Width = (L.NonNegative ? 0 : 1);
3041         else
3042           L.Width -= zext;
3043       }
3044
3045       return L;
3046     }
3047
3048     // Comma acts as its right operand.
3049     case BO_Comma:
3050       return GetExprRange(C, BO->getRHS(), MaxWidth);
3051
3052     // Black-list pointer subtractions.
3053     case BO_Sub:
3054       if (BO->getLHS()->getType()->isPointerType())
3055         return IntRange::forValueOfType(C, E->getType());
3056       break;
3057
3058     // The width of a division result is mostly determined by the size
3059     // of the LHS.
3060     case BO_Div: {
3061       // Don't 'pre-truncate' the operands.
3062       unsigned opWidth = C.getIntWidth(E->getType());
3063       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3064
3065       // If the divisor is constant, use that.
3066       llvm::APSInt divisor;
3067       if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3068         unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3069         if (log2 >= L.Width)
3070           L.Width = (L.NonNegative ? 0 : 1);
3071         else
3072           L.Width = std::min(L.Width - log2, MaxWidth);
3073         return L;
3074       }
3075
3076       // Otherwise, just use the LHS's width.
3077       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3078       return IntRange(L.Width, L.NonNegative && R.NonNegative);
3079     }
3080
3081     // The result of a remainder can't be larger than the result of
3082     // either side.
3083     case BO_Rem: {
3084       // Don't 'pre-truncate' the operands.
3085       unsigned opWidth = C.getIntWidth(E->getType());
3086       IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3087       IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3088
3089       IntRange meet = IntRange::meet(L, R);
3090       meet.Width = std::min(meet.Width, MaxWidth);
3091       return meet;
3092     }
3093
3094     // The default behavior is okay for these.
3095     case BO_Mul:
3096     case BO_Add:
3097     case BO_Xor:
3098     case BO_Or:
3099       break;
3100     }
3101
3102     // The default case is to treat the operation as if it were closed
3103     // on the narrowest type that encompasses both operands.
3104     IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3105     IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3106     return IntRange::join(L, R);
3107   }
3108
3109   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3110     switch (UO->getOpcode()) {
3111     // Boolean-valued operations are white-listed.
3112     case UO_LNot:
3113       return IntRange::forBoolType();
3114
3115     // Operations with opaque sources are black-listed.
3116     case UO_Deref:
3117     case UO_AddrOf: // should be impossible
3118       return IntRange::forValueOfType(C, E->getType());
3119
3120     default:
3121       return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3122     }
3123   }
3124   
3125   if (dyn_cast<OffsetOfExpr>(E)) {
3126     IntRange::forValueOfType(C, E->getType());
3127   }
3128
3129   if (FieldDecl *BitField = E->getBitField())
3130     return IntRange(BitField->getBitWidthValue(C),
3131                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
3132
3133   return IntRange::forValueOfType(C, E->getType());
3134 }
3135
3136 IntRange GetExprRange(ASTContext &C, Expr *E) {
3137   return GetExprRange(C, E, C.getIntWidth(E->getType()));
3138 }
3139
3140 /// Checks whether the given value, which currently has the given
3141 /// source semantics, has the same value when coerced through the
3142 /// target semantics.
3143 bool IsSameFloatAfterCast(const llvm::APFloat &value,
3144                           const llvm::fltSemantics &Src,
3145                           const llvm::fltSemantics &Tgt) {
3146   llvm::APFloat truncated = value;
3147
3148   bool ignored;
3149   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3150   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3151
3152   return truncated.bitwiseIsEqual(value);
3153 }
3154
3155 /// Checks whether the given value, which currently has the given
3156 /// source semantics, has the same value when coerced through the
3157 /// target semantics.
3158 ///
3159 /// The value might be a vector of floats (or a complex number).
3160 bool IsSameFloatAfterCast(const APValue &value,
3161                           const llvm::fltSemantics &Src,
3162                           const llvm::fltSemantics &Tgt) {
3163   if (value.isFloat())
3164     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3165
3166   if (value.isVector()) {
3167     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3168       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3169         return false;
3170     return true;
3171   }
3172
3173   assert(value.isComplexFloat());
3174   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3175           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3176 }
3177
3178 void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
3179
3180 static bool IsZero(Sema &S, Expr *E) {
3181   // Suppress cases where we are comparing against an enum constant.
3182   if (const DeclRefExpr *DR =
3183       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3184     if (isa<EnumConstantDecl>(DR->getDecl()))
3185       return false;
3186
3187   // Suppress cases where the '0' value is expanded from a macro.
3188   if (E->getLocStart().isMacroID())
3189     return false;
3190
3191   llvm::APSInt Value;
3192   return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3193 }
3194
3195 static bool HasEnumType(Expr *E) {
3196   // Strip off implicit integral promotions.
3197   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3198     if (ICE->getCastKind() != CK_IntegralCast &&
3199         ICE->getCastKind() != CK_NoOp)
3200       break;
3201     E = ICE->getSubExpr();
3202   }
3203
3204   return E->getType()->isEnumeralType();
3205 }
3206
3207 void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
3208   BinaryOperatorKind op = E->getOpcode();
3209   if (E->isValueDependent())
3210     return;
3211
3212   if (op == BO_LT && IsZero(S, E->getRHS())) {
3213     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3214       << "< 0" << "false" << HasEnumType(E->getLHS())
3215       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3216   } else if (op == BO_GE && IsZero(S, E->getRHS())) {
3217     S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
3218       << ">= 0" << "true" << HasEnumType(E->getLHS())
3219       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3220   } else if (op == BO_GT && IsZero(S, E->getLHS())) {
3221     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3222       << "0 >" << "false" << HasEnumType(E->getRHS())
3223       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3224   } else if (op == BO_LE && IsZero(S, E->getLHS())) {
3225     S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
3226       << "0 <=" << "true" << HasEnumType(E->getRHS())
3227       << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3228   }
3229 }
3230
3231 /// Analyze the operands of the given comparison.  Implements the
3232 /// fallback case from AnalyzeComparison.
3233 void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
3234   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3235   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3236 }
3237
3238 /// \brief Implements -Wsign-compare.
3239 ///
3240 /// \param E the binary operator to check for warnings
3241 void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3242   // The type the comparison is being performed in.
3243   QualType T = E->getLHS()->getType();
3244   assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3245          && "comparison with mismatched types");
3246
3247   // We don't do anything special if this isn't an unsigned integral
3248   // comparison:  we're only interested in integral comparisons, and
3249   // signed comparisons only happen in cases we don't care to warn about.
3250   //
3251   // We also don't care about value-dependent expressions or expressions
3252   // whose result is a constant.
3253   if (!T->hasUnsignedIntegerRepresentation()
3254       || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
3255     return AnalyzeImpConvsInComparison(S, E);
3256
3257   Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3258   Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
3259
3260   // Check to see if one of the (unmodified) operands is of different
3261   // signedness.
3262   Expr *signedOperand, *unsignedOperand;
3263   if (LHS->getType()->hasSignedIntegerRepresentation()) {
3264     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
3265            "unsigned comparison between two signed integer expressions?");
3266     signedOperand = LHS;
3267     unsignedOperand = RHS;
3268   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3269     signedOperand = RHS;
3270     unsignedOperand = LHS;
3271   } else {
3272     CheckTrivialUnsignedComparison(S, E);
3273     return AnalyzeImpConvsInComparison(S, E);
3274   }
3275
3276   // Otherwise, calculate the effective range of the signed operand.
3277   IntRange signedRange = GetExprRange(S.Context, signedOperand);
3278
3279   // Go ahead and analyze implicit conversions in the operands.  Note
3280   // that we skip the implicit conversions on both sides.
3281   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3282   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
3283
3284   // If the signed range is non-negative, -Wsign-compare won't fire,
3285   // but we should still check for comparisons which are always true
3286   // or false.
3287   if (signedRange.NonNegative)
3288     return CheckTrivialUnsignedComparison(S, E);
3289
3290   // For (in)equality comparisons, if the unsigned operand is a
3291   // constant which cannot collide with a overflowed signed operand,
3292   // then reinterpreting the signed operand as unsigned will not
3293   // change the result of the comparison.
3294   if (E->isEqualityOp()) {
3295     unsigned comparisonWidth = S.Context.getIntWidth(T);
3296     IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
3297
3298     // We should never be unable to prove that the unsigned operand is
3299     // non-negative.
3300     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3301
3302     if (unsignedRange.Width < comparisonWidth)
3303       return;
3304   }
3305
3306   S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
3307     << LHS->getType() << RHS->getType()
3308     << LHS->getSourceRange() << RHS->getSourceRange();
3309 }
3310
3311 /// Analyzes an attempt to assign the given value to a bitfield.
3312 ///
3313 /// Returns true if there was something fishy about the attempt.
3314 bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3315                                SourceLocation InitLoc) {
3316   assert(Bitfield->isBitField());
3317   if (Bitfield->isInvalidDecl())
3318     return false;
3319
3320   // White-list bool bitfields.
3321   if (Bitfield->getType()->isBooleanType())
3322     return false;
3323
3324   // Ignore value- or type-dependent expressions.
3325   if (Bitfield->getBitWidth()->isValueDependent() ||
3326       Bitfield->getBitWidth()->isTypeDependent() ||
3327       Init->isValueDependent() ||
3328       Init->isTypeDependent())
3329     return false;
3330
3331   Expr *OriginalInit = Init->IgnoreParenImpCasts();
3332
3333   Expr::EvalResult InitValue;
3334   if (!OriginalInit->Evaluate(InitValue, S.Context) ||
3335       !InitValue.Val.isInt())
3336     return false;
3337
3338   const llvm::APSInt &Value = InitValue.Val.getInt();
3339   unsigned OriginalWidth = Value.getBitWidth();
3340   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
3341
3342   if (OriginalWidth <= FieldWidth)
3343     return false;
3344
3345   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
3346
3347   // It's fairly common to write values into signed bitfields
3348   // that, if sign-extended, would end up becoming a different
3349   // value.  We don't want to warn about that.
3350   if (Value.isSigned() && Value.isNegative())
3351     TruncatedValue = TruncatedValue.sext(OriginalWidth);
3352   else
3353     TruncatedValue = TruncatedValue.zext(OriginalWidth);
3354
3355   if (Value == TruncatedValue)
3356     return false;
3357
3358   std::string PrettyValue = Value.toString(10);
3359   std::string PrettyTrunc = TruncatedValue.toString(10);
3360
3361   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3362     << PrettyValue << PrettyTrunc << OriginalInit->getType()
3363     << Init->getSourceRange();
3364
3365   return true;
3366 }
3367
3368 /// Analyze the given simple or compound assignment for warning-worthy
3369 /// operations.
3370 void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3371   // Just recurse on the LHS.
3372   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3373
3374   // We want to recurse on the RHS as normal unless we're assigning to
3375   // a bitfield.
3376   if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
3377     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3378                                   E->getOperatorLoc())) {
3379       // Recurse, ignoring any implicit conversions on the RHS.
3380       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3381                                         E->getOperatorLoc());
3382     }
3383   }
3384
3385   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3386 }
3387
3388 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3389 void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 
3390                      SourceLocation CContext, unsigned diag) {
3391   S.Diag(E->getExprLoc(), diag)
3392     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3393 }
3394
3395 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
3396 void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3397                      unsigned diag) {
3398   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3399 }
3400
3401 /// Diagnose an implicit cast from a literal expression. Does not warn when the
3402 /// cast wouldn't lose information.
3403 void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3404                                     SourceLocation CContext) {
3405   // Try to convert the literal exactly to an integer. If we can, don't warn.
3406   bool isExact = false;
3407   const llvm::APFloat &Value = FL->getValue();
3408   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3409                             T->hasUnsignedIntegerRepresentation());
3410   if (Value.convertToInteger(IntegerValue,
3411                              llvm::APFloat::rmTowardZero, &isExact)
3412       == llvm::APFloat::opOK && isExact)
3413     return;
3414
3415   S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3416     << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
3417 }
3418
3419 std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3420   if (!Range.Width) return "0";
3421
3422   llvm::APSInt ValueInRange = Value;
3423   ValueInRange.setIsSigned(!Range.NonNegative);
3424   ValueInRange = ValueInRange.trunc(Range.Width);
3425   return ValueInRange.toString(10);
3426 }
3427
3428 static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3429   SourceManager &smgr = S.Context.getSourceManager();
3430   return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3431 }
3432
3433 void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
3434                              SourceLocation CC, bool *ICContext = 0) {
3435   if (E->isTypeDependent() || E->isValueDependent()) return;
3436
3437   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3438   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3439   if (Source == Target) return;
3440   if (Target->isDependentType()) return;
3441
3442   // If the conversion context location is invalid don't complain. We also
3443   // don't want to emit a warning if the issue occurs from the expansion of
3444   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3445   // delay this check as long as possible. Once we detect we are in that
3446   // scenario, we just return.
3447   if (CC.isInvalid())
3448     return;
3449
3450   // Diagnose implicit casts to bool.
3451   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3452     if (isa<StringLiteral>(E))
3453       // Warn on string literal to bool.  Checks for string literals in logical
3454       // expressions, for instances, assert(0 && "error here"), is prevented
3455       // by a check in AnalyzeImplicitConversions().
3456       return DiagnoseImpCast(S, E, T, CC,
3457                              diag::warn_impcast_string_literal_to_bool);
3458     return; // Other casts to bool are not checked.
3459   }
3460
3461   // Strip vector types.
3462   if (isa<VectorType>(Source)) {
3463     if (!isa<VectorType>(Target)) {
3464       if (isFromSystemMacro(S, CC))
3465         return;
3466       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
3467     }
3468     
3469     // If the vector cast is cast between two vectors of the same size, it is
3470     // a bitcast, not a conversion.
3471     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3472       return;
3473
3474     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3475     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3476   }
3477
3478   // Strip complex types.
3479   if (isa<ComplexType>(Source)) {
3480     if (!isa<ComplexType>(Target)) {
3481       if (isFromSystemMacro(S, CC))
3482         return;
3483
3484       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
3485     }
3486
3487     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3488     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3489   }
3490
3491   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3492   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3493
3494   // If the source is floating point...
3495   if (SourceBT && SourceBT->isFloatingPoint()) {
3496     // ...and the target is floating point...
3497     if (TargetBT && TargetBT->isFloatingPoint()) {
3498       // ...then warn if we're dropping FP rank.
3499
3500       // Builtin FP kinds are ordered by increasing FP rank.
3501       if (SourceBT->getKind() > TargetBT->getKind()) {
3502         // Don't warn about float constants that are precisely
3503         // representable in the target type.
3504         Expr::EvalResult result;
3505         if (E->Evaluate(result, S.Context)) {
3506           // Value might be a float, a float vector, or a float complex.
3507           if (IsSameFloatAfterCast(result.Val,
3508                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3509                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
3510             return;
3511         }
3512
3513         if (isFromSystemMacro(S, CC))
3514           return;
3515
3516         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
3517       }
3518       return;
3519     }
3520
3521     // If the target is integral, always warn.    
3522     if ((TargetBT && TargetBT->isInteger())) {
3523       if (isFromSystemMacro(S, CC))
3524         return;
3525       
3526       Expr *InnerE = E->IgnoreParenImpCasts();
3527       // We also want to warn on, e.g., "int i = -1.234"
3528       if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3529         if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3530           InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3531
3532       if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3533         DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
3534       } else {
3535         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3536       }
3537     }
3538
3539     return;
3540   }
3541
3542   if (!Source->isIntegerType() || !Target->isIntegerType())
3543     return;
3544
3545   if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3546            == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3547     S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3548         << E->getSourceRange() << clang::SourceRange(CC);
3549     return;
3550   }
3551
3552   IntRange SourceRange = GetExprRange(S.Context, E);
3553   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
3554
3555   if (SourceRange.Width > TargetRange.Width) {
3556     // If the source is a constant, use a default-on diagnostic.
3557     // TODO: this should happen for bitfield stores, too.
3558     llvm::APSInt Value(32);
3559     if (E->isIntegerConstantExpr(Value, S.Context)) {
3560       if (isFromSystemMacro(S, CC))
3561         return;
3562
3563       std::string PrettySourceValue = Value.toString(10);
3564       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3565
3566       S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3567         << PrettySourceValue << PrettyTargetValue
3568         << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3569       return;
3570     }
3571
3572     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
3573     if (isFromSystemMacro(S, CC))
3574       return;
3575     
3576     if (SourceRange.Width == 64 && TargetRange.Width == 32)
3577       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3578     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
3579   }
3580
3581   if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3582       (!TargetRange.NonNegative && SourceRange.NonNegative &&
3583        SourceRange.Width == TargetRange.Width)) {
3584         
3585     if (isFromSystemMacro(S, CC))
3586       return;
3587
3588     unsigned DiagID = diag::warn_impcast_integer_sign;
3589
3590     // Traditionally, gcc has warned about this under -Wsign-compare.
3591     // We also want to warn about it in -Wconversion.
3592     // So if -Wconversion is off, use a completely identical diagnostic
3593     // in the sign-compare group.
3594     // The conditional-checking code will 
3595     if (ICContext) {
3596       DiagID = diag::warn_impcast_integer_sign_conditional;
3597       *ICContext = true;
3598     }
3599
3600     return DiagnoseImpCast(S, E, T, CC, DiagID);
3601   }
3602
3603   // Diagnose conversions between different enumeration types.
3604   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3605   // type, to give us better diagnostics.
3606   QualType SourceType = E->getType();
3607   if (!S.getLangOptions().CPlusPlus) {
3608     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3609       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3610         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3611         SourceType = S.Context.getTypeDeclType(Enum);
3612         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3613       }
3614   }
3615   
3616   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3617     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3618       if ((SourceEnum->getDecl()->getIdentifier() || 
3619            SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3620           (TargetEnum->getDecl()->getIdentifier() ||
3621            TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
3622           SourceEnum != TargetEnum) {
3623         if (isFromSystemMacro(S, CC))
3624           return;
3625
3626         return DiagnoseImpCast(S, E, SourceType, T, CC, 
3627                                diag::warn_impcast_different_enum_types);
3628       }
3629   
3630   return;
3631 }
3632
3633 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3634
3635 void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
3636                              SourceLocation CC, bool &ICContext) {
3637   E = E->IgnoreParenImpCasts();
3638
3639   if (isa<ConditionalOperator>(E))
3640     return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3641
3642   AnalyzeImplicitConversions(S, E, CC);
3643   if (E->getType() != T)
3644     return CheckImplicitConversion(S, E, T, CC, &ICContext);
3645   return;
3646 }
3647
3648 void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
3649   SourceLocation CC = E->getQuestionLoc();
3650
3651   AnalyzeImplicitConversions(S, E->getCond(), CC);
3652
3653   bool Suspicious = false;
3654   CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3655   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
3656
3657   // If -Wconversion would have warned about either of the candidates
3658   // for a signedness conversion to the context type...
3659   if (!Suspicious) return;
3660
3661   // ...but it's currently ignored...
3662   if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3663                                  CC))
3664     return;
3665
3666   // ...then check whether it would have warned about either of the
3667   // candidates for a signedness conversion to the condition type.
3668   if (E->getType() == T) return;
3669  
3670   Suspicious = false;
3671   CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3672                           E->getType(), CC, &Suspicious);
3673   if (!Suspicious)
3674     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
3675                             E->getType(), CC, &Suspicious);
3676 }
3677
3678 /// AnalyzeImplicitConversions - Find and report any interesting
3679 /// implicit conversions in the given expression.  There are a couple
3680 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
3681 void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
3682   QualType T = OrigE->getType();
3683   Expr *E = OrigE->IgnoreParenImpCasts();
3684
3685   if (E->isTypeDependent() || E->isValueDependent())
3686     return;
3687
3688   // For conditional operators, we analyze the arguments as if they
3689   // were being fed directly into the output.
3690   if (isa<ConditionalOperator>(E)) {
3691     ConditionalOperator *CO = cast<ConditionalOperator>(E);
3692     CheckConditionalOperator(S, CO, T);
3693     return;
3694   }
3695
3696   // Go ahead and check any implicit conversions we might have skipped.
3697   // The non-canonical typecheck is just an optimization;
3698   // CheckImplicitConversion will filter out dead implicit conversions.
3699   if (E->getType() != T)
3700     CheckImplicitConversion(S, E, T, CC);
3701
3702   // Now continue drilling into this expression.
3703
3704   // Skip past explicit casts.
3705   if (isa<ExplicitCastExpr>(E)) {
3706     E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
3707     return AnalyzeImplicitConversions(S, E, CC);
3708   }
3709
3710   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3711     // Do a somewhat different check with comparison operators.
3712     if (BO->isComparisonOp())
3713       return AnalyzeComparison(S, BO);
3714
3715     // And with assignments and compound assignments.
3716     if (BO->isAssignmentOp())
3717       return AnalyzeAssignment(S, BO);
3718   }
3719
3720   // These break the otherwise-useful invariant below.  Fortunately,
3721   // we don't really need to recurse into them, because any internal
3722   // expressions should have been analyzed already when they were
3723   // built into statements.
3724   if (isa<StmtExpr>(E)) return;
3725
3726   // Don't descend into unevaluated contexts.
3727   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
3728
3729   // Now just recurse over the expression's children.
3730   CC = E->getExprLoc();
3731   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3732   bool IsLogicalOperator = BO && BO->isLogicalOp();
3733   for (Stmt::child_range I = E->children(); I; ++I) {
3734     Expr *ChildExpr = cast<Expr>(*I);
3735     if (IsLogicalOperator &&
3736         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3737       // Ignore checking string literals that are in logical operators.
3738       continue;
3739     AnalyzeImplicitConversions(S, ChildExpr, CC);
3740   }
3741 }
3742
3743 } // end anonymous namespace
3744
3745 /// Diagnoses "dangerous" implicit conversions within the given
3746 /// expression (which is a full expression).  Implements -Wconversion
3747 /// and -Wsign-compare.
3748 ///
3749 /// \param CC the "context" location of the implicit conversion, i.e.
3750 ///   the most location of the syntactic entity requiring the implicit
3751 ///   conversion
3752 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
3753   // Don't diagnose in unevaluated contexts.
3754   if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3755     return;
3756
3757   // Don't diagnose for value- or type-dependent expressions.
3758   if (E->isTypeDependent() || E->isValueDependent())
3759     return;
3760
3761   // Check for array bounds violations in cases where the check isn't triggered
3762   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3763   // ArraySubscriptExpr is on the RHS of a variable initialization.
3764   CheckArrayAccess(E);
3765
3766   // This is not the right CC for (e.g.) a variable initialization.
3767   AnalyzeImplicitConversions(*this, E, CC);
3768 }
3769
3770 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3771                                        FieldDecl *BitField,
3772                                        Expr *Init) {
3773   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3774 }
3775
3776 /// CheckParmsForFunctionDef - Check that the parameters of the given
3777 /// function are appropriate for the definition of a function. This
3778 /// takes care of any checks that cannot be performed on the
3779 /// declaration itself, e.g., that the types of each of the function
3780 /// parameters are complete.
3781 bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3782                                     bool CheckParameterNames) {
3783   bool HasInvalidParm = false;
3784   for (; P != PEnd; ++P) {
3785     ParmVarDecl *Param = *P;
3786     
3787     // C99 6.7.5.3p4: the parameters in a parameter type list in a
3788     // function declarator that is part of a function definition of
3789     // that function shall not have incomplete type.
3790     //
3791     // This is also C++ [dcl.fct]p6.
3792     if (!Param->isInvalidDecl() &&
3793         RequireCompleteType(Param->getLocation(), Param->getType(),
3794                                diag::err_typecheck_decl_incomplete_type)) {
3795       Param->setInvalidDecl();
3796       HasInvalidParm = true;
3797     }
3798
3799     // C99 6.9.1p5: If the declarator includes a parameter type list, the
3800     // declaration of each parameter shall include an identifier.
3801     if (CheckParameterNames &&
3802         Param->getIdentifier() == 0 &&
3803         !Param->isImplicit() &&
3804         !getLangOptions().CPlusPlus)
3805       Diag(Param->getLocation(), diag::err_parameter_name_omitted);
3806
3807     // C99 6.7.5.3p12:
3808     //   If the function declarator is not part of a definition of that
3809     //   function, parameters may have incomplete type and may use the [*]
3810     //   notation in their sequences of declarator specifiers to specify
3811     //   variable length array types.
3812     QualType PType = Param->getOriginalType();
3813     if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3814       if (AT->getSizeModifier() == ArrayType::Star) {
3815         // FIXME: This diagnosic should point the the '[*]' if source-location
3816         // information is added for it.
3817         Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3818       }
3819     }
3820   }
3821
3822   return HasInvalidParm;
3823 }
3824
3825 /// CheckCastAlign - Implements -Wcast-align, which warns when a
3826 /// pointer cast increases the alignment requirements.
3827 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3828   // This is actually a lot of work to potentially be doing on every
3829   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
3830   if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3831                                           TRange.getBegin())
3832         == DiagnosticsEngine::Ignored)
3833     return;
3834
3835   // Ignore dependent types.
3836   if (T->isDependentType() || Op->getType()->isDependentType())
3837     return;
3838
3839   // Require that the destination be a pointer type.
3840   const PointerType *DestPtr = T->getAs<PointerType>();
3841   if (!DestPtr) return;
3842
3843   // If the destination has alignment 1, we're done.
3844   QualType DestPointee = DestPtr->getPointeeType();
3845   if (DestPointee->isIncompleteType()) return;
3846   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3847   if (DestAlign.isOne()) return;
3848
3849   // Require that the source be a pointer type.
3850   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3851   if (!SrcPtr) return;
3852   QualType SrcPointee = SrcPtr->getPointeeType();
3853
3854   // Whitelist casts from cv void*.  We already implicitly
3855   // whitelisted casts to cv void*, since they have alignment 1.
3856   // Also whitelist casts involving incomplete types, which implicitly
3857   // includes 'void'.
3858   if (SrcPointee->isIncompleteType()) return;
3859
3860   CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3861   if (SrcAlign >= DestAlign) return;
3862
3863   Diag(TRange.getBegin(), diag::warn_cast_align)
3864     << Op->getType() << T
3865     << static_cast<unsigned>(SrcAlign.getQuantity())
3866     << static_cast<unsigned>(DestAlign.getQuantity())
3867     << TRange << Op->getSourceRange();
3868 }
3869
3870 static const Type* getElementType(const Expr *BaseExpr) {
3871   const Type* EltType = BaseExpr->getType().getTypePtr();
3872   if (EltType->isAnyPointerType())
3873     return EltType->getPointeeType().getTypePtr();
3874   else if (EltType->isArrayType())
3875     return EltType->getBaseElementTypeUnsafe();
3876   return EltType;
3877 }
3878
3879 /// \brief Check whether this array fits the idiom of a size-one tail padded
3880 /// array member of a struct.
3881 ///
3882 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
3883 /// commonly used to emulate flexible arrays in C89 code.
3884 static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3885                                     const NamedDecl *ND) {
3886   if (Size != 1 || !ND) return false;
3887
3888   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3889   if (!FD) return false;
3890
3891   // Don't consider sizes resulting from macro expansions or template argument
3892   // substitution to form C89 tail-padded arrays.
3893   ConstantArrayTypeLoc TL =
3894     cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3895   const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3896   if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3897     return false;
3898
3899   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3900   if (!RD || !RD->isStruct())
3901     return false;
3902
3903   // See if this is the last field decl in the record.
3904   const Decl *D = FD;
3905   while ((D = D->getNextDeclInContext()))
3906     if (isa<FieldDecl>(D))
3907       return false;
3908   return true;
3909 }
3910
3911 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3912                             bool isSubscript, bool AllowOnePastEnd) {
3913   const Type* EffectiveType = getElementType(BaseExpr);
3914   BaseExpr = BaseExpr->IgnoreParenCasts();
3915   IndexExpr = IndexExpr->IgnoreParenCasts();
3916
3917   const ConstantArrayType *ArrayTy =
3918     Context.getAsConstantArrayType(BaseExpr->getType());
3919   if (!ArrayTy)
3920     return;
3921
3922   if (IndexExpr->isValueDependent())
3923     return;
3924   llvm::APSInt index;
3925   if (!IndexExpr->isIntegerConstantExpr(index, Context))
3926     return;
3927
3928   const NamedDecl *ND = NULL;
3929   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3930     ND = dyn_cast<NamedDecl>(DRE->getDecl());
3931   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3932     ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3933
3934   if (index.isUnsigned() || !index.isNegative()) {
3935     llvm::APInt size = ArrayTy->getSize();
3936     if (!size.isStrictlyPositive())
3937       return;
3938
3939     const Type* BaseType = getElementType(BaseExpr);
3940     if (BaseType != EffectiveType) {
3941       // Make sure we're comparing apples to apples when comparing index to size
3942       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3943       uint64_t array_typesize = Context.getTypeSize(BaseType);
3944       // Handle ptrarith_typesize being zero, such as when casting to void*
3945       if (!ptrarith_typesize) ptrarith_typesize = 1;
3946       if (ptrarith_typesize != array_typesize) {
3947         // There's a cast to a different size type involved
3948         uint64_t ratio = array_typesize / ptrarith_typesize;
3949         // TODO: Be smarter about handling cases where array_typesize is not a
3950         // multiple of ptrarith_typesize
3951         if (ptrarith_typesize * ratio == array_typesize)
3952           size *= llvm::APInt(size.getBitWidth(), ratio);
3953       }
3954     }
3955
3956     if (size.getBitWidth() > index.getBitWidth())
3957       index = index.sext(size.getBitWidth());
3958     else if (size.getBitWidth() < index.getBitWidth())
3959       size = size.sext(index.getBitWidth());
3960
3961     // For array subscripting the index must be less than size, but for pointer
3962     // arithmetic also allow the index (offset) to be equal to size since
3963     // computing the next address after the end of the array is legal and
3964     // commonly done e.g. in C++ iterators and range-based for loops.
3965     if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
3966       return;
3967
3968     // Also don't warn for arrays of size 1 which are members of some
3969     // structure. These are often used to approximate flexible arrays in C89
3970     // code.
3971     if (IsTailPaddedMemberArray(*this, size, ND))
3972       return;
3973
3974     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
3975     if (isSubscript)
3976       DiagID = diag::warn_array_index_exceeds_bounds;
3977
3978     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3979                         PDiag(DiagID) << index.toString(10, true)
3980                           << size.toString(10, true)
3981                           << (unsigned)size.getLimitedValue(~0U)
3982                           << IndexExpr->getSourceRange());
3983   } else {
3984     unsigned DiagID = diag::warn_array_index_precedes_bounds;
3985     if (!isSubscript) {
3986       DiagID = diag::warn_ptr_arith_precedes_bounds;
3987       if (index.isNegative()) index = -index;
3988     }
3989
3990     DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
3991                         PDiag(DiagID) << index.toString(10, true)
3992                           << IndexExpr->getSourceRange());
3993   }
3994
3995   if (ND)
3996     DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3997                         PDiag(diag::note_array_index_out_of_bounds)
3998                           << ND->getDeclName());
3999 }
4000
4001 void Sema::CheckArrayAccess(const Expr *expr) {
4002   int AllowOnePastEnd = 0;
4003   while (expr) {
4004     expr = expr->IgnoreParenImpCasts();
4005     switch (expr->getStmtClass()) {
4006       case Stmt::ArraySubscriptExprClass: {
4007         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4008         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4009                          AllowOnePastEnd > 0);
4010         return;
4011       }
4012       case Stmt::UnaryOperatorClass: {
4013         // Only unwrap the * and & unary operators
4014         const UnaryOperator *UO = cast<UnaryOperator>(expr);
4015         expr = UO->getSubExpr();
4016         switch (UO->getOpcode()) {
4017           case UO_AddrOf:
4018             AllowOnePastEnd++;
4019             break;
4020           case UO_Deref:
4021             AllowOnePastEnd--;
4022             break;
4023           default:
4024             return;
4025         }
4026         break;
4027       }
4028       case Stmt::ConditionalOperatorClass: {
4029         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4030         if (const Expr *lhs = cond->getLHS())
4031           CheckArrayAccess(lhs);
4032         if (const Expr *rhs = cond->getRHS())
4033           CheckArrayAccess(rhs);
4034         return;
4035       }
4036       default:
4037         return;
4038     }
4039   }
4040 }
4041
4042 //===--- CHECK: Objective-C retain cycles ----------------------------------//
4043
4044 namespace {
4045   struct RetainCycleOwner {
4046     RetainCycleOwner() : Variable(0), Indirect(false) {}
4047     VarDecl *Variable;
4048     SourceRange Range;
4049     SourceLocation Loc;
4050     bool Indirect;
4051
4052     void setLocsFrom(Expr *e) {
4053       Loc = e->getExprLoc();
4054       Range = e->getSourceRange();
4055     }
4056   };
4057 }
4058
4059 /// Consider whether capturing the given variable can possibly lead to
4060 /// a retain cycle.
4061 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4062   // In ARC, it's captured strongly iff the variable has __strong
4063   // lifetime.  In MRR, it's captured strongly if the variable is
4064   // __block and has an appropriate type.
4065   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4066     return false;
4067
4068   owner.Variable = var;
4069   owner.setLocsFrom(ref);
4070   return true;
4071 }
4072
4073 static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4074   while (true) {
4075     e = e->IgnoreParens();
4076     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4077       switch (cast->getCastKind()) {
4078       case CK_BitCast:
4079       case CK_LValueBitCast:
4080       case CK_LValueToRValue:
4081       case CK_ARCReclaimReturnedObject:
4082         e = cast->getSubExpr();
4083         continue;
4084
4085       case CK_GetObjCProperty: {
4086         // Bail out if this isn't a strong explicit property.
4087         const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4088         if (pre->isImplicitProperty()) return false;
4089         ObjCPropertyDecl *property = pre->getExplicitProperty();
4090         if (!property->isRetaining() &&
4091             !(property->getPropertyIvarDecl() &&
4092               property->getPropertyIvarDecl()->getType()
4093                 .getObjCLifetime() == Qualifiers::OCL_Strong))
4094           return false;
4095
4096         owner.Indirect = true;
4097         e = const_cast<Expr*>(pre->getBase());
4098         continue;
4099       }
4100         
4101       default:
4102         return false;
4103       }
4104     }
4105
4106     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4107       ObjCIvarDecl *ivar = ref->getDecl();
4108       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4109         return false;
4110
4111       // Try to find a retain cycle in the base.
4112       if (!findRetainCycleOwner(ref->getBase(), owner))
4113         return false;
4114
4115       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4116       owner.Indirect = true;
4117       return true;
4118     }
4119
4120     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4121       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4122       if (!var) return false;
4123       return considerVariable(var, ref, owner);
4124     }
4125
4126     if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4127       owner.Variable = ref->getDecl();
4128       owner.setLocsFrom(ref);
4129       return true;
4130     }
4131
4132     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4133       if (member->isArrow()) return false;
4134
4135       // Don't count this as an indirect ownership.
4136       e = member->getBase();
4137       continue;
4138     }
4139
4140     // Array ivars?
4141
4142     return false;
4143   }
4144 }
4145
4146 namespace {
4147   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4148     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4149       : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4150         Variable(variable), Capturer(0) {}
4151
4152     VarDecl *Variable;
4153     Expr *Capturer;
4154
4155     void VisitDeclRefExpr(DeclRefExpr *ref) {
4156       if (ref->getDecl() == Variable && !Capturer)
4157         Capturer = ref;
4158     }
4159
4160     void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4161       if (ref->getDecl() == Variable && !Capturer)
4162         Capturer = ref;
4163     }
4164
4165     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4166       if (Capturer) return;
4167       Visit(ref->getBase());
4168       if (Capturer && ref->isFreeIvar())
4169         Capturer = ref;
4170     }
4171
4172     void VisitBlockExpr(BlockExpr *block) {
4173       // Look inside nested blocks 
4174       if (block->getBlockDecl()->capturesVariable(Variable))
4175         Visit(block->getBlockDecl()->getBody());
4176     }
4177   };
4178 }
4179
4180 /// Check whether the given argument is a block which captures a
4181 /// variable.
4182 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4183   assert(owner.Variable && owner.Loc.isValid());
4184
4185   e = e->IgnoreParenCasts();
4186   BlockExpr *block = dyn_cast<BlockExpr>(e);
4187   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4188     return 0;
4189
4190   FindCaptureVisitor visitor(S.Context, owner.Variable);
4191   visitor.Visit(block->getBlockDecl()->getBody());
4192   return visitor.Capturer;
4193 }
4194
4195 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4196                                 RetainCycleOwner &owner) {
4197   assert(capturer);
4198   assert(owner.Variable && owner.Loc.isValid());
4199
4200   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4201     << owner.Variable << capturer->getSourceRange();
4202   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4203     << owner.Indirect << owner.Range;
4204 }
4205
4206 /// Check for a keyword selector that starts with the word 'add' or
4207 /// 'set'.
4208 static bool isSetterLikeSelector(Selector sel) {
4209   if (sel.isUnarySelector()) return false;
4210
4211   StringRef str = sel.getNameForSlot(0);
4212   while (!str.empty() && str.front() == '_') str = str.substr(1);
4213   if (str.startswith("set") || str.startswith("add"))
4214     str = str.substr(3);
4215   else
4216     return false;
4217
4218   if (str.empty()) return true;
4219   return !islower(str.front());
4220 }
4221
4222 /// Check a message send to see if it's likely to cause a retain cycle.
4223 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4224   // Only check instance methods whose selector looks like a setter.
4225   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4226     return;
4227
4228   // Try to find a variable that the receiver is strongly owned by.
4229   RetainCycleOwner owner;
4230   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4231     if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4232       return;
4233   } else {
4234     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4235     owner.Variable = getCurMethodDecl()->getSelfDecl();
4236     owner.Loc = msg->getSuperLoc();
4237     owner.Range = msg->getSuperLoc();
4238   }
4239
4240   // Check whether the receiver is captured by any of the arguments.
4241   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4242     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4243       return diagnoseRetainCycle(*this, capturer, owner);
4244 }
4245
4246 /// Check a property assign to see if it's likely to cause a retain cycle.
4247 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4248   RetainCycleOwner owner;
4249   if (!findRetainCycleOwner(receiver, owner))
4250     return;
4251
4252   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4253     diagnoseRetainCycle(*this, capturer, owner);
4254 }
4255
4256 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
4257                               QualType LHS, Expr *RHS) {
4258   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4259   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
4260     return false;
4261   // strip off any implicit cast added to get to the one arc-specific
4262   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4263     if (cast->getCastKind() == CK_ARCConsumeObject) {
4264       Diag(Loc, diag::warn_arc_retained_assign)
4265         << (LT == Qualifiers::OCL_ExplicitNone) 
4266         << RHS->getSourceRange();
4267       return true;
4268     }
4269     RHS = cast->getSubExpr();
4270   }
4271   return false;
4272 }
4273
4274 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4275                               Expr *LHS, Expr *RHS) {
4276   QualType LHSType = LHS->getType();
4277   if (checkUnsafeAssigns(Loc, LHSType, RHS))
4278     return;
4279   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4280   // FIXME. Check for other life times.
4281   if (LT != Qualifiers::OCL_None)
4282     return;
4283   
4284   if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4285     if (PRE->isImplicitProperty())
4286       return;
4287     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4288     if (!PD)
4289       return;
4290     
4291     unsigned Attributes = PD->getPropertyAttributes();
4292     if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4293       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
4294         if (cast->getCastKind() == CK_ARCConsumeObject) {
4295           Diag(Loc, diag::warn_arc_retained_property_assign)
4296           << RHS->getSourceRange();
4297           return;
4298         }
4299         RHS = cast->getSubExpr();
4300       }
4301   }
4302 }