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