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