blob: cd07358b159a00b97e543fda26d3008e3c290a49 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
John McCall29ad95b2011-08-27 01:09:30 +000015#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000017#include "clang/Sema/SemaInternal.h"
Eli Friedmandf14b3a2011-10-11 02:20:01 +000018#include "clang/Sema/Initialization.h"
John McCallaab3e412010-08-25 08:40:02 +000019#include "clang/Sema/ScopeInfo.h"
Ted Kremenek02087932010-07-16 02:11:22 +000020#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000021#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000022#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000023#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000025#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000026#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000027#include "clang/AST/EvaluatedExprVisitor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000028#include "clang/AST/DeclObjC.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/StmtObjC.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000031#include "clang/Lex/Preprocessor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000032#include "llvm/ADT/BitVector.h"
33#include "llvm/ADT/STLExtras.h"
Tom Careb7042702010-06-09 04:11:11 +000034#include "llvm/Support/raw_ostream.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000035#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000036#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian56603ef2010-09-07 19:38:13 +000037#include "clang/Basic/ConvertUTF.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000038#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000039using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000040using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000041
Chris Lattnera26fb342009-02-18 17:49:48 +000042SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
43 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000044 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
45 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000046}
Chris Lattnere925d612010-11-17 07:37:15 +000047
Chris Lattnera26fb342009-02-18 17:49:48 +000048
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000049/// CheckablePrintfAttr - does a function call have a "printf" attribute
50/// and arguments that merit checking?
51bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
52 if (Format->getType() == "printf") return true;
53 if (Format->getType() == "printf0") {
54 // printf0 allows null "format" string; if so don't check format/args
55 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl6eedcc12009-11-17 18:02:24 +000056 // Does the index refer to the implicit object argument?
57 if (isa<CXXMemberCallExpr>(TheCall)) {
58 if (format_idx == 0)
59 return false;
60 --format_idx;
61 }
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000062 if (format_idx < TheCall->getNumArgs()) {
63 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekd1668192010-02-27 01:41:03 +000064 if (!Format->isNullPointerConstant(Context,
65 Expr::NPC_ValueDependentIsNull))
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000066 return true;
67 }
68 }
69 return false;
70}
Chris Lattnera26fb342009-02-18 17:49:48 +000071
John McCallbebede42011-02-26 05:39:39 +000072/// Checks that a call expression's argument count is the desired number.
73/// This is useful when doing custom type-checking. Returns true on error.
74static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
75 unsigned argCount = call->getNumArgs();
76 if (argCount == desiredArgCount) return false;
77
78 if (argCount < desiredArgCount)
79 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
80 << 0 /*function call*/ << desiredArgCount << argCount
81 << call->getSourceRange();
82
83 // Highlight all the excess arguments.
84 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
85 call->getArg(argCount - 1)->getLocEnd());
86
87 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
88 << 0 /*function call*/ << desiredArgCount << argCount
89 << call->getArg(1)->getSourceRange();
90}
91
Julien Lerouge5a6b6982011-09-09 22:41:49 +000092/// CheckBuiltinAnnotationString - Checks that string argument to the builtin
93/// annotation is a non wide string literal.
94static bool CheckBuiltinAnnotationString(Sema &S, Expr *Arg) {
95 Arg = Arg->IgnoreParenCasts();
96 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
97 if (!Literal || !Literal->isAscii()) {
98 S.Diag(Arg->getLocStart(), diag::err_builtin_annotation_not_string_constant)
99 << Arg->getSourceRange();
100 return true;
101 }
102 return false;
103}
104
John McCalldadc5752010-08-24 06:29:42 +0000105ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000106Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +0000107 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +0000108
Chris Lattner3be167f2010-10-01 23:23:24 +0000109 // Find out if any arguments are required to be integer constant expressions.
110 unsigned ICEArguments = 0;
111 ASTContext::GetBuiltinTypeError Error;
112 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
113 if (Error != ASTContext::GE_None)
114 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
115
116 // If any arguments are required to be ICE's, check and diagnose.
117 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
118 // Skip arguments not required to be ICE's.
119 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
120
121 llvm::APSInt Result;
122 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
123 return true;
124 ICEArguments &= ~(1 << ArgNo);
125 }
126
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000127 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000128 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000129 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000130 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000131 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000132 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000133 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000134 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000135 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000136 if (SemaBuiltinVAStart(TheCall))
137 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000138 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000139 case Builtin::BI__builtin_isgreater:
140 case Builtin::BI__builtin_isgreaterequal:
141 case Builtin::BI__builtin_isless:
142 case Builtin::BI__builtin_islessequal:
143 case Builtin::BI__builtin_islessgreater:
144 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 if (SemaBuiltinUnorderedCompare(TheCall))
146 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000147 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000148 case Builtin::BI__builtin_fpclassify:
149 if (SemaBuiltinFPClassification(TheCall, 6))
150 return ExprError();
151 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000152 case Builtin::BI__builtin_isfinite:
153 case Builtin::BI__builtin_isinf:
154 case Builtin::BI__builtin_isinf_sign:
155 case Builtin::BI__builtin_isnan:
156 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000157 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000158 return ExprError();
159 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000160 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000161 return SemaBuiltinShuffleVector(TheCall);
162 // TheCall will be freed by the smart pointer here, but that's fine, since
163 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000164 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000165 if (SemaBuiltinPrefetch(TheCall))
166 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000167 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000168 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000169 if (SemaBuiltinObjectSize(TheCall))
170 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000171 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000172 case Builtin::BI__builtin_longjmp:
173 if (SemaBuiltinLongjmp(TheCall))
174 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000175 break;
John McCallbebede42011-02-26 05:39:39 +0000176
177 case Builtin::BI__builtin_classify_type:
178 if (checkArgCount(*this, TheCall, 1)) return true;
179 TheCall->setType(Context.IntTy);
180 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000181 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000182 if (checkArgCount(*this, TheCall, 1)) return true;
183 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000184 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000185 case Builtin::BI__sync_fetch_and_add:
186 case Builtin::BI__sync_fetch_and_sub:
187 case Builtin::BI__sync_fetch_and_or:
188 case Builtin::BI__sync_fetch_and_and:
189 case Builtin::BI__sync_fetch_and_xor:
190 case Builtin::BI__sync_add_and_fetch:
191 case Builtin::BI__sync_sub_and_fetch:
192 case Builtin::BI__sync_and_and_fetch:
193 case Builtin::BI__sync_or_and_fetch:
194 case Builtin::BI__sync_xor_and_fetch:
195 case Builtin::BI__sync_val_compare_and_swap:
196 case Builtin::BI__sync_bool_compare_and_swap:
197 case Builtin::BI__sync_lock_test_and_set:
198 case Builtin::BI__sync_lock_release:
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000199 case Builtin::BI__sync_swap:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000200 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000201 case Builtin::BI__atomic_load:
202 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Load);
203 case Builtin::BI__atomic_store:
204 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Store);
205 case Builtin::BI__atomic_exchange:
206 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xchg);
207 case Builtin::BI__atomic_compare_exchange_strong:
208 return SemaAtomicOpsOverloaded(move(TheCallResult),
209 AtomicExpr::CmpXchgStrong);
210 case Builtin::BI__atomic_compare_exchange_weak:
211 return SemaAtomicOpsOverloaded(move(TheCallResult),
212 AtomicExpr::CmpXchgWeak);
213 case Builtin::BI__atomic_fetch_add:
214 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Add);
215 case Builtin::BI__atomic_fetch_sub:
216 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Sub);
217 case Builtin::BI__atomic_fetch_and:
218 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::And);
219 case Builtin::BI__atomic_fetch_or:
220 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Or);
221 case Builtin::BI__atomic_fetch_xor:
222 return SemaAtomicOpsOverloaded(move(TheCallResult), AtomicExpr::Xor);
Julien Lerouge5a6b6982011-09-09 22:41:49 +0000223 case Builtin::BI__builtin_annotation:
224 if (CheckBuiltinAnnotationString(*this, TheCall->getArg(1)))
225 return ExprError();
226 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000227 }
228
229 // Since the target specific builtins for each arch overlap, only check those
230 // of the arch we are compiling for.
231 if (BuiltinID >= Builtin::FirstTSBuiltin) {
Douglas Gregore8bbc122011-09-02 00:18:52 +0000232 switch (Context.getTargetInfo().getTriple().getArch()) {
Nate Begeman4904e322010-06-08 02:47:44 +0000233 case llvm::Triple::arm:
234 case llvm::Triple::thumb:
235 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
236 return ExprError();
237 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000238 default:
239 break;
240 }
241 }
242
243 return move(TheCallResult);
244}
245
Nate Begeman91e1fea2010-06-14 05:21:25 +0000246// Get the valid immediate range for the specified NEON type code.
247static unsigned RFT(unsigned t, bool shift = false) {
Bob Wilson98bc98c2011-11-08 01:16:11 +0000248 NeonTypeFlags Type(t);
249 int IsQuad = Type.isQuad();
250 switch (Type.getEltType()) {
251 case NeonTypeFlags::Int8:
252 case NeonTypeFlags::Poly8:
253 return shift ? 7 : (8 << IsQuad) - 1;
254 case NeonTypeFlags::Int16:
255 case NeonTypeFlags::Poly16:
256 return shift ? 15 : (4 << IsQuad) - 1;
257 case NeonTypeFlags::Int32:
258 return shift ? 31 : (2 << IsQuad) - 1;
259 case NeonTypeFlags::Int64:
260 return shift ? 63 : (1 << IsQuad) - 1;
261 case NeonTypeFlags::Float16:
262 assert(!shift && "cannot shift float types!");
263 return (4 << IsQuad) - 1;
264 case NeonTypeFlags::Float32:
265 assert(!shift && "cannot shift float types!");
266 return (2 << IsQuad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000267 }
268 return 0;
269}
270
Bob Wilsone4d77232011-11-08 05:04:11 +0000271/// getNeonEltType - Return the QualType corresponding to the elements of
272/// the vector type specified by the NeonTypeFlags. This is used to check
273/// the pointer arguments for Neon load/store intrinsics.
274static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context) {
275 switch (Flags.getEltType()) {
276 case NeonTypeFlags::Int8:
277 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
278 case NeonTypeFlags::Int16:
279 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
280 case NeonTypeFlags::Int32:
281 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
282 case NeonTypeFlags::Int64:
283 return Flags.isUnsigned() ? Context.UnsignedLongLongTy : Context.LongLongTy;
284 case NeonTypeFlags::Poly8:
285 return Context.SignedCharTy;
286 case NeonTypeFlags::Poly16:
287 return Context.ShortTy;
288 case NeonTypeFlags::Float16:
289 return Context.UnsignedShortTy;
290 case NeonTypeFlags::Float32:
291 return Context.FloatTy;
292 }
293 return QualType();
294}
295
Nate Begeman4904e322010-06-08 02:47:44 +0000296bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000297 llvm::APSInt Result;
298
Nate Begemand773fe62010-06-13 04:47:52 +0000299 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000300 unsigned TV = 0;
Bob Wilsone4d77232011-11-08 05:04:11 +0000301 bool HasPtr = false;
302 bool HasConstPtr = false;
Nate Begeman55483092010-06-09 01:10:23 +0000303 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000304#define GET_NEON_OVERLOAD_CHECK
305#include "clang/Basic/arm_neon.inc"
306#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000307 }
308
Nate Begemand773fe62010-06-13 04:47:52 +0000309 // For NEON intrinsics which are overloaded on vector element type, validate
310 // the immediate which specifies which variant to emit.
Bob Wilsone4d77232011-11-08 05:04:11 +0000311 unsigned ImmArg = TheCall->getNumArgs()-1;
Nate Begemand773fe62010-06-13 04:47:52 +0000312 if (mask) {
Bob Wilsone4d77232011-11-08 05:04:11 +0000313 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
Nate Begemand773fe62010-06-13 04:47:52 +0000314 return true;
315
Bob Wilson98bc98c2011-11-08 01:16:11 +0000316 TV = Result.getLimitedValue(64);
317 if ((TV > 63) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
Bob Wilsone4d77232011-11-08 05:04:11 +0000319 << TheCall->getArg(ImmArg)->getSourceRange();
320 }
321
322 if (HasPtr || HasConstPtr) {
323 // Check that pointer arguments have the specified type.
324 for (unsigned ArgNo = 0; ArgNo < ImmArg; ++ArgNo) {
325 Expr *Arg = TheCall->getArg(ArgNo);
326 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
327 Arg = ICE->getSubExpr();
328 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
329 QualType RHSTy = RHS.get()->getType();
330 if (!RHSTy->isPointerType())
331 continue;
332 QualType EltTy = getNeonEltType(NeonTypeFlags(TV), Context);
333 if (HasConstPtr)
334 EltTy = EltTy.withConst();
335 QualType LHSTy = Context.getPointerType(EltTy);
336 AssignConvertType ConvTy;
337 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
338 if (RHS.isInvalid())
339 return true;
340 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
341 RHS.get(), AA_Assigning))
342 return true;
343 }
Nate Begemand773fe62010-06-13 04:47:52 +0000344 }
Nate Begeman55483092010-06-09 01:10:23 +0000345
Nate Begemand773fe62010-06-13 04:47:52 +0000346 // For NEON intrinsics which take an immediate value as part of the
347 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000348 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000349 switch (BuiltinID) {
350 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000351 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
352 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000353 case ARM::BI__builtin_arm_vcvtr_f:
354 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000355#define GET_NEON_IMMEDIATE_CHECK
356#include "clang/Basic/arm_neon.inc"
357#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000358 };
359
Nate Begeman91e1fea2010-06-14 05:21:25 +0000360 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000361 if (SemaBuiltinConstantArg(TheCall, i, Result))
362 return true;
363
Nate Begeman91e1fea2010-06-14 05:21:25 +0000364 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000365 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000366 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000367 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000368 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000369
Nate Begemanf568b072010-08-03 21:32:34 +0000370 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000371 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000372}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000373
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000374/// CheckFunctionCall - Check a direct function call for various correctness
375/// and safety properties not strictly enforced by the C type system.
376bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
377 // Get the IdentifierInfo* for the called function.
378 IdentifierInfo *FnInfo = FDecl->getIdentifier();
379
380 // None of the checks below are needed for functions that don't have
381 // simple names (e.g., C++ conversion functions).
382 if (!FnInfo)
383 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000384
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000385 // FIXME: This mechanism should be abstracted to be less fragile and
386 // more efficient. For example, just map function ids to custom
387 // handlers.
388
Ted Kremenekb8176da2010-09-09 04:33:05 +0000389 // Printf and scanf checking.
390 for (specific_attr_iterator<FormatAttr>
391 i = FDecl->specific_attr_begin<FormatAttr>(),
392 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
393
394 const FormatAttr *Format = *i;
Ted Kremenek02087932010-07-16 02:11:22 +0000395 const bool b = Format->getType() == "scanf";
396 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000397 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000398 CheckPrintfScanfArguments(TheCall, HasVAListArg,
399 Format->getFormatIdx() - 1,
400 HasVAListArg ? 0 : Format->getFirstArg() - 1,
401 !b);
Douglas Gregore711f702009-02-14 18:57:46 +0000402 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000403 }
Mike Stump11289f42009-09-09 15:08:12 +0000404
Ted Kremenekb8176da2010-09-09 04:33:05 +0000405 for (specific_attr_iterator<NonNullAttr>
406 i = FDecl->specific_attr_begin<NonNullAttr>(),
407 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +0000408 CheckNonNullArguments(*i, TheCall->getArgs(),
409 TheCall->getCallee()->getLocStart());
Ted Kremenekb8176da2010-09-09 04:33:05 +0000410 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000411
Ted Kremenek6865f772011-08-18 20:55:45 +0000412 // Builtin handling
Douglas Gregor18739c32011-06-16 17:56:04 +0000413 int CMF = -1;
414 switch (FDecl->getBuiltinID()) {
415 case Builtin::BI__builtin_memset:
416 case Builtin::BI__builtin___memset_chk:
417 case Builtin::BImemset:
418 CMF = CMF_Memset;
419 break;
420
421 case Builtin::BI__builtin_memcpy:
422 case Builtin::BI__builtin___memcpy_chk:
423 case Builtin::BImemcpy:
424 CMF = CMF_Memcpy;
425 break;
426
427 case Builtin::BI__builtin_memmove:
428 case Builtin::BI__builtin___memmove_chk:
429 case Builtin::BImemmove:
430 CMF = CMF_Memmove;
431 break;
Ted Kremenek6865f772011-08-18 20:55:45 +0000432
433 case Builtin::BIstrlcpy:
434 case Builtin::BIstrlcat:
435 CheckStrlcpycatArguments(TheCall, FnInfo);
436 break;
Douglas Gregor18739c32011-06-16 17:56:04 +0000437
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000438 case Builtin::BI__builtin_memcmp:
439 CMF = CMF_Memcmp;
440 break;
441
Nico Weber39bfed82011-10-13 22:30:23 +0000442 case Builtin::BI__builtin_strncpy:
443 case Builtin::BI__builtin___strncpy_chk:
444 case Builtin::BIstrncpy:
445 CMF = CMF_Strncpy;
446 break;
447
448 case Builtin::BI__builtin_strncmp:
449 CMF = CMF_Strncmp;
450 break;
451
452 case Builtin::BI__builtin_strncasecmp:
453 CMF = CMF_Strncasecmp;
454 break;
455
456 case Builtin::BI__builtin_strncat:
457 case Builtin::BIstrncat:
458 CMF = CMF_Strncat;
459 break;
460
461 case Builtin::BI__builtin_strndup:
462 case Builtin::BIstrndup:
463 CMF = CMF_Strndup;
464 break;
465
Douglas Gregor18739c32011-06-16 17:56:04 +0000466 default:
467 if (FDecl->getLinkage() == ExternalLinkage &&
468 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
469 if (FnInfo->isStr("memset"))
470 CMF = CMF_Memset;
471 else if (FnInfo->isStr("memcpy"))
472 CMF = CMF_Memcpy;
473 else if (FnInfo->isStr("memmove"))
474 CMF = CMF_Memmove;
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000475 else if (FnInfo->isStr("memcmp"))
476 CMF = CMF_Memcmp;
Nico Weber39bfed82011-10-13 22:30:23 +0000477 else if (FnInfo->isStr("strncpy"))
478 CMF = CMF_Strncpy;
479 else if (FnInfo->isStr("strncmp"))
480 CMF = CMF_Strncmp;
481 else if (FnInfo->isStr("strncasecmp"))
482 CMF = CMF_Strncasecmp;
483 else if (FnInfo->isStr("strncat"))
484 CMF = CMF_Strncat;
485 else if (FnInfo->isStr("strndup"))
486 CMF = CMF_Strndup;
Douglas Gregor18739c32011-06-16 17:56:04 +0000487 }
488 break;
Douglas Gregor3bb2a812011-05-03 20:37:33 +0000489 }
Douglas Gregor18739c32011-06-16 17:56:04 +0000490
Ted Kremenek6865f772011-08-18 20:55:45 +0000491 // Memset/memcpy/memmove handling
Douglas Gregor18739c32011-06-16 17:56:04 +0000492 if (CMF != -1)
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000493 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000494
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000495 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000496}
497
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000498bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000499 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000500 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000501 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000502 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000503
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000504 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
505 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000506 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000507
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000508 QualType Ty = V->getType();
509 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000510 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000511
Ted Kremenek02087932010-07-16 02:11:22 +0000512 const bool b = Format->getType() == "scanf";
513 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000514 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000515
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000516 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000517 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
518 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000519
520 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000521}
522
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000523ExprResult
524Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
525 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
526 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000527
528 // All these operations take one of the following four forms:
529 // T __atomic_load(_Atomic(T)*, int) (loads)
530 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
531 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
532 // (cmpxchg)
533 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
534 // where T is an appropriate type, and the int paremeterss are for orderings.
535 unsigned NumVals = 1;
536 unsigned NumOrders = 1;
537 if (Op == AtomicExpr::Load) {
538 NumVals = 0;
539 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
540 NumVals = 2;
541 NumOrders = 2;
542 }
543
544 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
545 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
546 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
547 << TheCall->getCallee()->getSourceRange();
548 return ExprError();
549 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
550 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
551 diag::err_typecheck_call_too_many_args)
552 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
553 << TheCall->getCallee()->getSourceRange();
554 return ExprError();
555 }
556
557 // Inspect the first argument of the atomic operation. This should always be
558 // a pointer to an _Atomic type.
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000559 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000560 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
561 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
562 if (!pointerType) {
563 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
564 << Ptr->getType() << Ptr->getSourceRange();
565 return ExprError();
566 }
567
568 QualType AtomTy = pointerType->getPointeeType();
569 if (!AtomTy->isAtomicType()) {
570 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
571 << Ptr->getType() << Ptr->getSourceRange();
572 return ExprError();
573 }
574 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
575
576 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
577 !ValType->isIntegerType() && !ValType->isPointerType()) {
578 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
579 << Ptr->getType() << Ptr->getSourceRange();
580 return ExprError();
581 }
582
583 if (!ValType->isIntegerType() &&
584 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
585 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
586 << Ptr->getType() << Ptr->getSourceRange();
587 return ExprError();
588 }
589
590 switch (ValType.getObjCLifetime()) {
591 case Qualifiers::OCL_None:
592 case Qualifiers::OCL_ExplicitNone:
593 // okay
594 break;
595
596 case Qualifiers::OCL_Weak:
597 case Qualifiers::OCL_Strong:
598 case Qualifiers::OCL_Autoreleasing:
599 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
600 << ValType << Ptr->getSourceRange();
601 return ExprError();
602 }
603
604 QualType ResultType = ValType;
605 if (Op == AtomicExpr::Store)
606 ResultType = Context.VoidTy;
607 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
608 ResultType = Context.BoolTy;
609
610 // The first argument --- the pointer --- has a fixed type; we
611 // deduce the types of the rest of the arguments accordingly. Walk
612 // the remaining arguments, converting them to the deduced value type.
613 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
614 ExprResult Arg = TheCall->getArg(i);
615 QualType Ty;
616 if (i < NumVals+1) {
617 // The second argument to a cmpxchg is a pointer to the data which will
618 // be exchanged. The second argument to a pointer add/subtract is the
619 // amount to add/subtract, which must be a ptrdiff_t. The third
620 // argument to a cmpxchg and the second argument in all other cases
621 // is the type of the value.
622 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
623 Op == AtomicExpr::CmpXchgStrong))
624 Ty = Context.getPointerType(ValType.getUnqualifiedType());
625 else if (!ValType->isIntegerType() &&
626 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
627 Ty = Context.getPointerDiffType();
628 else
629 Ty = ValType;
630 } else {
631 // The order(s) are always converted to int.
632 Ty = Context.IntTy;
633 }
634 InitializedEntity Entity =
635 InitializedEntity::InitializeParameter(Context, Ty, false);
636 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
637 if (Arg.isInvalid())
638 return true;
639 TheCall->setArg(i, Arg.get());
640 }
641
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000642 SmallVector<Expr*, 5> SubExprs;
643 SubExprs.push_back(Ptr);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000644 if (Op == AtomicExpr::Load) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000645 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000646 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000647 SubExprs.push_back(TheCall->getArg(2)); // Order
648 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000649 } else {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000650 SubExprs.push_back(TheCall->getArg(3)); // Order
651 SubExprs.push_back(TheCall->getArg(1)); // Val1
652 SubExprs.push_back(TheCall->getArg(2)); // Val2
653 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000654 }
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000655
656 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
657 SubExprs.data(), SubExprs.size(),
658 ResultType, Op,
659 TheCall->getRParenLoc()));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000660}
661
662
John McCall29ad95b2011-08-27 01:09:30 +0000663/// checkBuiltinArgument - Given a call to a builtin function, perform
664/// normal type-checking on the given argument, updating the call in
665/// place. This is useful when a builtin function requires custom
666/// type-checking for some of its arguments but not necessarily all of
667/// them.
668///
669/// Returns true on error.
670static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
671 FunctionDecl *Fn = E->getDirectCallee();
672 assert(Fn && "builtin call without direct callee!");
673
674 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
675 InitializedEntity Entity =
676 InitializedEntity::InitializeParameter(S.Context, Param);
677
678 ExprResult Arg = E->getArg(0);
679 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
680 if (Arg.isInvalid())
681 return true;
682
683 E->setArg(ArgIndex, Arg.take());
684 return false;
685}
686
Chris Lattnerdc046542009-05-08 06:58:22 +0000687/// SemaBuiltinAtomicOverloaded - We have a call to a function like
688/// __sync_fetch_and_add, which is an overloaded function based on the pointer
689/// type of its first argument. The main ActOnCallExpr routines have already
690/// promoted the types of arguments because all of these calls are prototyped as
691/// void(...).
692///
693/// This function goes through and does final semantic checking for these
694/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000695ExprResult
696Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000697 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000698 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
699 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
700
701 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000702 if (TheCall->getNumArgs() < 1) {
703 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
704 << 0 << 1 << TheCall->getNumArgs()
705 << TheCall->getCallee()->getSourceRange();
706 return ExprError();
707 }
Mike Stump11289f42009-09-09 15:08:12 +0000708
Chris Lattnerdc046542009-05-08 06:58:22 +0000709 // Inspect the first argument of the atomic builtin. This should always be
710 // a pointer type, whose element is an integral scalar or pointer type.
711 // Because it is a pointer type, we don't have to worry about any implicit
712 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000713 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000714 Expr *FirstArg = TheCall->getArg(0);
John McCall31168b02011-06-15 23:02:42 +0000715 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
716 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000717 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
718 << FirstArg->getType() << FirstArg->getSourceRange();
719 return ExprError();
720 }
Mike Stump11289f42009-09-09 15:08:12 +0000721
John McCall31168b02011-06-15 23:02:42 +0000722 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000723 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000724 !ValType->isBlockPointerType()) {
725 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
726 << FirstArg->getType() << FirstArg->getSourceRange();
727 return ExprError();
728 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000729
John McCall31168b02011-06-15 23:02:42 +0000730 switch (ValType.getObjCLifetime()) {
731 case Qualifiers::OCL_None:
732 case Qualifiers::OCL_ExplicitNone:
733 // okay
734 break;
735
736 case Qualifiers::OCL_Weak:
737 case Qualifiers::OCL_Strong:
738 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +0000739 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +0000740 << ValType << FirstArg->getSourceRange();
741 return ExprError();
742 }
743
John McCallb50451a2011-10-05 07:41:44 +0000744 // Strip any qualifiers off ValType.
745 ValType = ValType.getUnqualifiedType();
746
Chandler Carruth3973af72010-07-18 20:54:12 +0000747 // The majority of builtins return a value, but a few have special return
748 // types, so allow them to override appropriately below.
749 QualType ResultType = ValType;
750
Chris Lattnerdc046542009-05-08 06:58:22 +0000751 // We need to figure out which concrete builtin this maps onto. For example,
752 // __sync_fetch_and_add with a 2 byte object turns into
753 // __sync_fetch_and_add_2.
754#define BUILTIN_ROW(x) \
755 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
756 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
Chris Lattnerdc046542009-05-08 06:58:22 +0000758 static const unsigned BuiltinIndices[][5] = {
759 BUILTIN_ROW(__sync_fetch_and_add),
760 BUILTIN_ROW(__sync_fetch_and_sub),
761 BUILTIN_ROW(__sync_fetch_and_or),
762 BUILTIN_ROW(__sync_fetch_and_and),
763 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000764
Chris Lattnerdc046542009-05-08 06:58:22 +0000765 BUILTIN_ROW(__sync_add_and_fetch),
766 BUILTIN_ROW(__sync_sub_and_fetch),
767 BUILTIN_ROW(__sync_and_and_fetch),
768 BUILTIN_ROW(__sync_or_and_fetch),
769 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000770
Chris Lattnerdc046542009-05-08 06:58:22 +0000771 BUILTIN_ROW(__sync_val_compare_and_swap),
772 BUILTIN_ROW(__sync_bool_compare_and_swap),
773 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000774 BUILTIN_ROW(__sync_lock_release),
775 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +0000776 };
Mike Stump11289f42009-09-09 15:08:12 +0000777#undef BUILTIN_ROW
778
Chris Lattnerdc046542009-05-08 06:58:22 +0000779 // Determine the index of the size.
780 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000781 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000782 case 1: SizeIndex = 0; break;
783 case 2: SizeIndex = 1; break;
784 case 4: SizeIndex = 2; break;
785 case 8: SizeIndex = 3; break;
786 case 16: SizeIndex = 4; break;
787 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000788 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
789 << FirstArg->getType() << FirstArg->getSourceRange();
790 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000791 }
Mike Stump11289f42009-09-09 15:08:12 +0000792
Chris Lattnerdc046542009-05-08 06:58:22 +0000793 // Each of these builtins has one pointer argument, followed by some number of
794 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
795 // that we ignore. Find out which row of BuiltinIndices to read from as well
796 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000797 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000798 unsigned BuiltinIndex, NumFixed = 1;
799 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +0000800 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattnerdc046542009-05-08 06:58:22 +0000801 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
802 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
803 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
804 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
805 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump11289f42009-09-09 15:08:12 +0000806
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000807 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
808 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
809 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
810 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
811 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump11289f42009-09-09 15:08:12 +0000812
Chris Lattnerdc046542009-05-08 06:58:22 +0000813 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000814 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000815 NumFixed = 2;
816 break;
817 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000818 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000819 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000820 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000821 break;
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000822 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000823 case Builtin::BI__sync_lock_release:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000824 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000825 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000826 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000827 break;
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000828 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000829 }
Mike Stump11289f42009-09-09 15:08:12 +0000830
Chris Lattnerdc046542009-05-08 06:58:22 +0000831 // Now that we know how many fixed arguments we expect, first check that we
832 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000833 if (TheCall->getNumArgs() < 1+NumFixed) {
834 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
835 << 0 << 1+NumFixed << TheCall->getNumArgs()
836 << TheCall->getCallee()->getSourceRange();
837 return ExprError();
838 }
Mike Stump11289f42009-09-09 15:08:12 +0000839
Chris Lattner5b9241b2009-05-08 15:36:58 +0000840 // Get the decl for the concrete builtin from this, we can tell what the
841 // concrete integer type we should convert to is.
842 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
843 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
844 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000845 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000846 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
847 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000848
John McCallcf142162010-08-07 06:22:56 +0000849 // The first argument --- the pointer --- has a fixed type; we
850 // deduce the types of the rest of the arguments accordingly. Walk
851 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000852 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +0000853 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000854
Chris Lattnerdc046542009-05-08 06:58:22 +0000855 // If the argument is an implicit cast, then there was a promotion due to
856 // "...", just remove it now.
John Wiegley01296292011-04-08 18:41:53 +0000857 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000858 Arg = ICE->getSubExpr();
859 ICE->setSubExpr(0);
John Wiegley01296292011-04-08 18:41:53 +0000860 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +0000861 }
Mike Stump11289f42009-09-09 15:08:12 +0000862
Chris Lattnerdc046542009-05-08 06:58:22 +0000863 // GCC does an implicit conversion to the pointer or integer ValType. This
864 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +0000865 // Initialize the argument.
866 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
867 ValType, /*consume*/ false);
868 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +0000869 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000870 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000871
Chris Lattnerdc046542009-05-08 06:58:22 +0000872 // Okay, we have something that *can* be converted to the right type. Check
873 // to see if there is a potentially weird extension going on here. This can
874 // happen when you do an atomic operation on something like an char* and
875 // pass in 42. The 42 gets converted to char. This is even more strange
876 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000877 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +0000878 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +0000879 }
Mike Stump11289f42009-09-09 15:08:12 +0000880
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000881 ASTContext& Context = this->getASTContext();
882
883 // Create a new DeclRefExpr to refer to the new decl.
884 DeclRefExpr* NewDRE = DeclRefExpr::Create(
885 Context,
886 DRE->getQualifierLoc(),
887 NewBuiltinDecl,
888 DRE->getLocation(),
889 NewBuiltinDecl->getType(),
890 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +0000891
Chris Lattnerdc046542009-05-08 06:58:22 +0000892 // Set the callee in the CallExpr.
893 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000894 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley01296292011-04-08 18:41:53 +0000895 if (PromotedCall.isInvalid())
896 return ExprError();
897 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +0000898
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000899 // Change the result type of the call to match the original value type. This
900 // is arbitrary, but the codegen for these builtins ins design to handle it
901 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000902 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000903
904 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +0000905}
906
Chris Lattner6436fb62009-02-18 06:01:06 +0000907/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000908/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000909/// Note: It might also make sense to do the UTF-16 conversion here (would
910/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000911bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000912 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000913 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
914
Douglas Gregorfb65e592011-07-27 05:40:30 +0000915 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000916 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
917 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000918 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000919 }
Mike Stump11289f42009-09-09 15:08:12 +0000920
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000921 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000922 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000923 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000924 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000925 const UTF8 *FromPtr = (UTF8 *)String.data();
926 UTF16 *ToPtr = &ToBuf[0];
927
928 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
929 &ToPtr, ToPtr + NumBytes,
930 strictConversion);
931 // Check for conversion failure.
932 if (Result != conversionOK)
933 Diag(Arg->getLocStart(),
934 diag::warn_cfstring_truncated) << Arg->getSourceRange();
935 }
Anders Carlssona3a9c432007-08-17 15:44:17 +0000936 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000937}
938
Chris Lattnere202e6a2007-12-20 00:05:45 +0000939/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
940/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000941bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
942 Expr *Fn = TheCall->getCallee();
943 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000944 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000945 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000946 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
947 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000948 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000949 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000950 return true;
951 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000952
953 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +0000954 return Diag(TheCall->getLocEnd(),
955 diag::err_typecheck_call_too_few_args_at_least)
956 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000957 }
958
John McCall29ad95b2011-08-27 01:09:30 +0000959 // Type-check the first argument normally.
960 if (checkBuiltinArgument(*this, TheCall, 0))
961 return true;
962
Chris Lattnere202e6a2007-12-20 00:05:45 +0000963 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000964 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +0000965 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000966 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +0000967 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +0000968 else if (FunctionDecl *FD = getCurFunctionDecl())
969 isVariadic = FD->isVariadic();
970 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000971 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000972
Chris Lattnere202e6a2007-12-20 00:05:45 +0000973 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000974 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
975 return true;
976 }
Mike Stump11289f42009-09-09 15:08:12 +0000977
Chris Lattner43be2e62007-12-19 23:59:04 +0000978 // Verify that the second argument to the builtin is the last argument of the
979 // current function or method.
980 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000981 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000982
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000983 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
984 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000985 // FIXME: This isn't correct for methods (results in bogus warning).
986 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000987 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000988 if (CurBlock)
989 LastArg = *(CurBlock->TheDecl->param_end()-1);
990 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000991 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000992 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000993 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000994 SecondArgIsLastNamedArgument = PV == LastArg;
995 }
996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
Chris Lattner43be2e62007-12-19 23:59:04 +0000998 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000999 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +00001000 diag::warn_second_parameter_of_va_start_not_last_named_argument);
1001 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +00001002}
Chris Lattner43be2e62007-12-19 23:59:04 +00001003
Chris Lattner2da14fb2007-12-20 00:26:33 +00001004/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
1005/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +00001006bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
1007 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +00001008 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001009 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +00001010 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +00001011 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001012 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001013 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +00001014 << SourceRange(TheCall->getArg(2)->getLocStart(),
1015 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001016
John Wiegley01296292011-04-08 18:41:53 +00001017 ExprResult OrigArg0 = TheCall->getArg(0);
1018 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001019
Chris Lattner2da14fb2007-12-20 00:26:33 +00001020 // Do standard promotions between the two arguments, returning their common
1021 // type.
Chris Lattner08464942007-12-28 05:29:59 +00001022 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +00001023 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
1024 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +00001025
1026 // Make sure any conversions are pushed back into the call; this is
1027 // type safe since unordered compare builtins are declared as "_Bool
1028 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +00001029 TheCall->setArg(0, OrigArg0.get());
1030 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +00001031
John Wiegley01296292011-04-08 18:41:53 +00001032 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +00001033 return false;
1034
Chris Lattner2da14fb2007-12-20 00:26:33 +00001035 // If the common type isn't a real floating type, then the arguments were
1036 // invalid for this operation.
1037 if (!Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +00001038 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001039 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +00001040 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
1041 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +00001042
Chris Lattner2da14fb2007-12-20 00:26:33 +00001043 return false;
1044}
1045
Benjamin Kramer634fc102010-02-15 22:42:31 +00001046/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1047/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001048/// to check everything. We expect the last argument to be a floating point
1049/// value.
1050bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1051 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001052 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001053 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001054 if (TheCall->getNumArgs() > NumArgs)
1055 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001056 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001057 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001058 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001059 (*(TheCall->arg_end()-1))->getLocEnd());
1060
Benjamin Kramer64aae502010-02-16 10:07:31 +00001061 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001062
Eli Friedman7e4faac2009-08-31 20:06:00 +00001063 if (OrigArg->isTypeDependent())
1064 return false;
1065
Chris Lattner68784ef2010-05-06 05:50:07 +00001066 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001067 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001068 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001069 diag::err_typecheck_call_invalid_unary_fp)
1070 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001071
Chris Lattner68784ef2010-05-06 05:50:07 +00001072 // If this is an implicit conversion from float -> double, remove it.
1073 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1074 Expr *CastArg = Cast->getSubExpr();
1075 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1076 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1077 "promotion from float to double is the only expected cast here");
1078 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001079 TheCall->setArg(NumArgs-1, CastArg);
1080 OrigArg = CastArg;
1081 }
1082 }
1083
Eli Friedman7e4faac2009-08-31 20:06:00 +00001084 return false;
1085}
1086
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001087/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1088// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001089ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001090 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001091 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001092 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +00001093 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +00001094 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001095
Nate Begemana0110022010-06-08 00:16:34 +00001096 // Determine which of the following types of shufflevector we're checking:
1097 // 1) unary, vector mask: (lhs, mask)
1098 // 2) binary, vector mask: (lhs, rhs, mask)
1099 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1100 QualType resType = TheCall->getArg(0)->getType();
1101 unsigned numElements = 0;
1102
Douglas Gregorc25f7662009-05-19 22:10:17 +00001103 if (!TheCall->getArg(0)->isTypeDependent() &&
1104 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001105 QualType LHSType = TheCall->getArg(0)->getType();
1106 QualType RHSType = TheCall->getArg(1)->getType();
1107
1108 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001109 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001110 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001111 TheCall->getArg(1)->getLocEnd());
1112 return ExprError();
1113 }
Nate Begemana0110022010-06-08 00:16:34 +00001114
1115 numElements = LHSType->getAs<VectorType>()->getNumElements();
1116 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001117
Nate Begemana0110022010-06-08 00:16:34 +00001118 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1119 // with mask. If so, verify that RHS is an integer vector type with the
1120 // same number of elts as lhs.
1121 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00001122 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001123 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1124 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1125 << SourceRange(TheCall->getArg(1)->getLocStart(),
1126 TheCall->getArg(1)->getLocEnd());
1127 numResElements = numElements;
1128 }
1129 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001130 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001131 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001132 TheCall->getArg(1)->getLocEnd());
1133 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +00001134 } else if (numElements != numResElements) {
1135 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001136 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001137 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001138 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001139 }
1140
1141 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001142 if (TheCall->getArg(i)->isTypeDependent() ||
1143 TheCall->getArg(i)->isValueDependent())
1144 continue;
1145
Nate Begemana0110022010-06-08 00:16:34 +00001146 llvm::APSInt Result(32);
1147 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1148 return ExprError(Diag(TheCall->getLocStart(),
1149 diag::err_shufflevector_nonconstant_argument)
1150 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001151
Chris Lattner7ab824e2008-08-10 02:05:13 +00001152 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001153 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001154 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001155 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001156 }
1157
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001158 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001159
Chris Lattner7ab824e2008-08-10 02:05:13 +00001160 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001161 exprs.push_back(TheCall->getArg(i));
1162 TheCall->setArg(i, 0);
1163 }
1164
Nate Begemanf485fb52009-08-12 02:10:25 +00001165 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +00001166 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001167 TheCall->getCallee()->getLocStart(),
1168 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001169}
Chris Lattner43be2e62007-12-19 23:59:04 +00001170
Daniel Dunbarb7257262008-07-21 22:59:13 +00001171/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1172// This is declared to take (const void*, ...) and can take two
1173// optional constant int args.
1174bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001175 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001176
Chris Lattner3b054132008-11-19 05:08:23 +00001177 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001178 return Diag(TheCall->getLocEnd(),
1179 diag::err_typecheck_call_too_many_args_at_most)
1180 << 0 /*function call*/ << 3 << NumArgs
1181 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001182
1183 // Argument 0 is checked for us and the remaining arguments must be
1184 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001185 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001186 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001187
Eli Friedman5efba262009-12-04 00:30:06 +00001188 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001189 if (SemaBuiltinConstantArg(TheCall, i, Result))
1190 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001191
Daniel Dunbarb7257262008-07-21 22:59:13 +00001192 // FIXME: gcc issues a warning and rewrites these to 0. These
1193 // seems especially odd for the third argument since the default
1194 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001195 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001196 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001197 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001198 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001199 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001200 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001201 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001202 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001203 }
1204 }
1205
Chris Lattner3b054132008-11-19 05:08:23 +00001206 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001207}
1208
Eric Christopher8d0c6212010-04-17 02:26:23 +00001209/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1210/// TheCall is a constant expression.
1211bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1212 llvm::APSInt &Result) {
1213 Expr *Arg = TheCall->getArg(ArgNum);
1214 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1215 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1216
1217 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1218
1219 if (!Arg->isIntegerConstantExpr(Result, Context))
1220 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001221 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001222
Chris Lattnerd545ad12009-09-23 06:06:36 +00001223 return false;
1224}
1225
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001226/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1227/// int type). This simply type checks that type is one of the defined
1228/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001229// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001230bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001231 llvm::APSInt Result;
1232
1233 // Check constant-ness first.
1234 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1235 return true;
1236
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001237 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001238 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001239 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1240 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001241 }
1242
1243 return false;
1244}
1245
Eli Friedmanc97d0142009-05-03 06:04:26 +00001246/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001247/// This checks that val is a constant 1.
1248bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1249 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001250 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001251
Eric Christopher8d0c6212010-04-17 02:26:23 +00001252 // TODO: This is less than ideal. Overload this to take a value.
1253 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1254 return true;
1255
1256 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001257 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1258 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1259
1260 return false;
1261}
1262
Ted Kremeneka8890832011-02-24 23:03:04 +00001263// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001264bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1265 bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001266 unsigned format_idx, unsigned firstDataArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001267 bool isPrintf, bool inFunctionCall) {
Ted Kremenek808829352010-09-09 03:51:39 +00001268 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001269 if (E->isTypeDependent() || E->isValueDependent())
1270 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001271
Peter Collingbourne91147592011-04-15 00:35:48 +00001272 E = E->IgnoreParens();
1273
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001274 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00001275 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001276 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +00001277 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek02087932010-07-16 02:11:22 +00001278 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001279 format_idx, firstDataArg, isPrintf,
1280 inFunctionCall)
John McCallc07a0c72011-02-17 10:25:35 +00001281 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001282 format_idx, firstDataArg, isPrintf,
1283 inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001284 }
1285
Ted Kremenek1520dae2010-09-09 03:51:42 +00001286 case Stmt::IntegerLiteralClass:
1287 // Technically -Wformat-nonliteral does not warn about this case.
1288 // The behavior of printf and friends in this case is implementation
1289 // dependent. Ideally if the format string cannot be null then
1290 // it should have a 'nonnull' attribute in the function prototype.
1291 return true;
1292
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001293 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00001294 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1295 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001296 }
1297
John McCallc07a0c72011-02-17 10:25:35 +00001298 case Stmt::OpaqueValueExprClass:
1299 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1300 E = src;
1301 goto tryAgain;
1302 }
1303 return false;
1304
Ted Kremeneka8890832011-02-24 23:03:04 +00001305 case Stmt::PredefinedExprClass:
1306 // While __func__, etc., are technically not string literals, they
1307 // cannot contain format specifiers and thus are not a security
1308 // liability.
1309 return true;
1310
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001311 case Stmt::DeclRefExprClass: {
1312 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001313
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001314 // As an exception, do not flag errors for variables binding to
1315 // const string literals.
1316 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1317 bool isConstant = false;
1318 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001319
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001320 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1321 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00001322 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001323 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001324 PT->getPointeeType().isConstant(Context);
1325 }
Mike Stump11289f42009-09-09 15:08:12 +00001326
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001327 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001328 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001329 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek02087932010-07-16 02:11:22 +00001330 HasVAListArg, format_idx, firstDataArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001331 isPrintf, /*inFunctionCall*/false);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001332 }
Mike Stump11289f42009-09-09 15:08:12 +00001333
Anders Carlssonb012ca92009-06-28 19:55:58 +00001334 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1335 // special check to see if the format string is a function parameter
1336 // of the function calling the printf function. If the function
1337 // has an attribute indicating it is a printf-like function, then we
1338 // should suppress warnings concerning non-literals being used in a call
1339 // to a vprintf function. For example:
1340 //
1341 // void
1342 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1343 // va_list ap;
1344 // va_start(ap, fmt);
1345 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1346 // ...
1347 //
1348 //
1349 // FIXME: We don't have full attribute support yet, so just check to see
1350 // if the argument is a DeclRefExpr that references a parameter. We'll
1351 // add proper support for checking the attribute later.
1352 if (HasVAListArg)
1353 if (isa<ParmVarDecl>(VD))
1354 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001355 }
Mike Stump11289f42009-09-09 15:08:12 +00001356
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001357 return false;
1358 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001359
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001360 case Stmt::CallExprClass: {
1361 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001362 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001363 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1364 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1365 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001366 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001367 unsigned ArgIndex = FA->getFormatIdx();
1368 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00001369
1370 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001371 format_idx, firstDataArg, isPrintf,
1372 inFunctionCall);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001373 }
1374 }
1375 }
1376 }
Mike Stump11289f42009-09-09 15:08:12 +00001377
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001378 return false;
1379 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001380 case Stmt::ObjCStringLiteralClass:
1381 case Stmt::StringLiteralClass: {
1382 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001383
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001384 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001385 StrE = ObjCFExpr->getString();
1386 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001387 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001388
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001389 if (StrE) {
Ted Kremenek02087932010-07-16 02:11:22 +00001390 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001391 firstDataArg, isPrintf, inFunctionCall);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001392 return true;
1393 }
Mike Stump11289f42009-09-09 15:08:12 +00001394
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001395 return false;
1396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001398 default:
1399 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001400 }
1401}
1402
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001403void
Mike Stump11289f42009-09-09 15:08:12 +00001404Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00001405 const Expr * const *ExprArgs,
1406 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001407 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1408 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001409 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00001410 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001411 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001412 Expr::NPC_ValueDependentIsNotNull))
Nick Lewyckyd4693212011-03-25 01:44:32 +00001413 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001414 }
1415}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001416
Ted Kremenek02087932010-07-16 02:11:22 +00001417/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1418/// functions) for correct use of format strings.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001419void
Ted Kremenek02087932010-07-16 02:11:22 +00001420Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1421 unsigned format_idx, unsigned firstDataArg,
1422 bool isPrintf) {
1423
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001424 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +00001425
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001426 // The way the format attribute works in GCC, the implicit this argument
1427 // of member functions is counted. However, it doesn't appear in our own
1428 // lists, so decrement format_idx in that case.
1429 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth1c8383d2010-11-16 08:49:43 +00001430 const CXXMethodDecl *method_decl =
1431 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1432 if (method_decl && method_decl->isInstance()) {
1433 // Catch a format attribute mistakenly referring to the object argument.
1434 if (format_idx == 0)
1435 return;
1436 --format_idx;
1437 if(firstDataArg != 0)
1438 --firstDataArg;
1439 }
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001440 }
1441
Ted Kremenek02087932010-07-16 02:11:22 +00001442 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +00001443 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001444 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerf490e152008-11-19 05:27:50 +00001445 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001446 return;
1447 }
Mike Stump11289f42009-09-09 15:08:12 +00001448
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001449 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001450
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001451 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001452 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001453 // Dynamically generated format strings are difficult to
1454 // automatically vet at compile time. Requiring that format strings
1455 // are string literals: (1) permits the checking of format strings by
1456 // the compiler and thereby (2) can practically remove the source of
1457 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001458
Mike Stump11289f42009-09-09 15:08:12 +00001459 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001460 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001461 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001462 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001463 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek02087932010-07-16 02:11:22 +00001464 firstDataArg, isPrintf))
Chris Lattnere009a882009-04-29 04:49:34 +00001465 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001466
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001467 // If there are no arguments specified, warn with -Wformat-security, otherwise
1468 // warn only with -Wformat-nonliteral.
1469 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001470 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001471 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001472 << OrigFormatExpr->getSourceRange();
1473 else
Mike Stump11289f42009-09-09 15:08:12 +00001474 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001475 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001476 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001477}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001478
Ted Kremenekab278de2010-01-28 23:39:18 +00001479namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001480class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1481protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001482 Sema &S;
1483 const StringLiteral *FExpr;
1484 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001485 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001486 const unsigned NumDataArgs;
1487 const bool IsObjCLiteral;
1488 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001489 const bool HasVAListArg;
1490 const CallExpr *TheCall;
1491 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001492 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001493 bool usesPositionalArgs;
1494 bool atFirstArg;
Richard Trieu03cf7b72011-10-28 00:41:25 +00001495 bool inFunctionCall;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001496public:
Ted Kremenek02087932010-07-16 02:11:22 +00001497 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001498 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001499 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001500 const char *beg, bool hasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001501 const CallExpr *theCall, unsigned formatIdx,
1502 bool inFunctionCall)
Ted Kremenekab278de2010-01-28 23:39:18 +00001503 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001504 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001505 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001506 IsObjCLiteral(isObjCLiteral), Beg(beg),
1507 HasVAListArg(hasVAListArg),
Ted Kremenekd1668192010-02-27 01:41:03 +00001508 TheCall(theCall), FormatIdx(formatIdx),
Richard Trieu03cf7b72011-10-28 00:41:25 +00001509 usesPositionalArgs(false), atFirstArg(true),
1510 inFunctionCall(inFunctionCall) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001511 CoveredArgs.resize(numDataArgs);
1512 CoveredArgs.reset();
1513 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001514
Ted Kremenek019d2242010-01-29 01:50:07 +00001515 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001516
Ted Kremenek02087932010-07-16 02:11:22 +00001517 void HandleIncompleteSpecifier(const char *startSpecifier,
1518 unsigned specifierLen);
1519
Ted Kremenekd1668192010-02-27 01:41:03 +00001520 virtual void HandleInvalidPosition(const char *startSpecifier,
1521 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001522 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001523
1524 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1525
Ted Kremenekab278de2010-01-28 23:39:18 +00001526 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001527
Richard Trieu03cf7b72011-10-28 00:41:25 +00001528 template <typename Range>
1529 static void EmitFormatDiagnostic(Sema &S, bool inFunctionCall,
1530 const Expr *ArgumentExpr,
1531 PartialDiagnostic PDiag,
1532 SourceLocation StringLoc,
1533 bool IsStringLocation, Range StringRange,
1534 FixItHint Fixit = FixItHint());
1535
Ted Kremenek02087932010-07-16 02:11:22 +00001536protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001537 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1538 const char *startSpec,
1539 unsigned specifierLen,
1540 const char *csStart, unsigned csLen);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001541
1542 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
1543 const char *startSpec,
1544 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001545
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001546 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001547 CharSourceRange getSpecifierRange(const char *startSpecifier,
1548 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001549 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001550
Ted Kremenek5739de72010-01-29 01:06:55 +00001551 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001552
1553 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1554 const analyze_format_string::ConversionSpecifier &CS,
1555 const char *startSpecifier, unsigned specifierLen,
1556 unsigned argIndex);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001557
1558 template <typename Range>
1559 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
1560 bool IsStringLocation, Range StringRange,
1561 FixItHint Fixit = FixItHint());
1562
1563 void CheckPositionalAndNonpositionalArgs(
1564 const analyze_format_string::FormatSpecifier *FS);
Ted Kremenekab278de2010-01-28 23:39:18 +00001565};
1566}
1567
Ted Kremenek02087932010-07-16 02:11:22 +00001568SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001569 return OrigFormatExpr->getSourceRange();
1570}
1571
Ted Kremenek02087932010-07-16 02:11:22 +00001572CharSourceRange CheckFormatHandler::
1573getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001574 SourceLocation Start = getLocationOfByte(startSpecifier);
1575 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1576
1577 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001578 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00001579
1580 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001581}
1582
Ted Kremenek02087932010-07-16 02:11:22 +00001583SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001584 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001585}
1586
Ted Kremenek02087932010-07-16 02:11:22 +00001587void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1588 unsigned specifierLen){
Richard Trieu03cf7b72011-10-28 00:41:25 +00001589 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
1590 getLocationOfByte(startSpecifier),
1591 /*IsStringLocation*/true,
1592 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001593}
1594
Ted Kremenekd1668192010-02-27 01:41:03 +00001595void
Ted Kremenek02087932010-07-16 02:11:22 +00001596CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1597 analyze_format_string::PositionContext p) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001598 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
1599 << (unsigned) p,
1600 getLocationOfByte(startPos), /*IsStringLocation*/true,
1601 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001602}
1603
Ted Kremenek02087932010-07-16 02:11:22 +00001604void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001605 unsigned posLen) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001606 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
1607 getLocationOfByte(startPos),
1608 /*IsStringLocation*/true,
1609 getSpecifierRange(startPos, posLen));
Ted Kremenekd1668192010-02-27 01:41:03 +00001610}
1611
Ted Kremenek02087932010-07-16 02:11:22 +00001612void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001613 if (!IsObjCLiteral) {
1614 // The presence of a null character is likely an error.
Richard Trieu03cf7b72011-10-28 00:41:25 +00001615 EmitFormatDiagnostic(
1616 S.PDiag(diag::warn_printf_format_string_contains_null_char),
1617 getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
1618 getFormatStringRange());
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001619 }
Ted Kremenek02087932010-07-16 02:11:22 +00001620}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001621
Ted Kremenek02087932010-07-16 02:11:22 +00001622const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1623 return TheCall->getArg(FirstDataArg + i);
1624}
1625
1626void CheckFormatHandler::DoneProcessing() {
1627 // Does the number of data arguments exceed the number of
1628 // format conversions in the format string?
1629 if (!HasVAListArg) {
1630 // Find any arguments that weren't covered.
1631 CoveredArgs.flip();
1632 signed notCoveredArg = CoveredArgs.find_first();
1633 if (notCoveredArg >= 0) {
1634 assert((unsigned)notCoveredArg < NumDataArgs);
Richard Trieu03cf7b72011-10-28 00:41:25 +00001635 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_data_arg_not_used),
1636 getDataArg((unsigned) notCoveredArg)->getLocStart(),
1637 /*IsStringLocation*/false, getFormatStringRange());
Ted Kremenek02087932010-07-16 02:11:22 +00001638 }
1639 }
1640}
1641
Ted Kremenekce815422010-07-19 21:25:57 +00001642bool
1643CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1644 SourceLocation Loc,
1645 const char *startSpec,
1646 unsigned specifierLen,
1647 const char *csStart,
1648 unsigned csLen) {
1649
1650 bool keepGoing = true;
1651 if (argIndex < NumDataArgs) {
1652 // Consider the argument coverered, even though the specifier doesn't
1653 // make sense.
1654 CoveredArgs.set(argIndex);
1655 }
1656 else {
1657 // If argIndex exceeds the number of data arguments we
1658 // don't issue a warning because that is just a cascade of warnings (and
1659 // they may have intended '%%' anyway). We don't want to continue processing
1660 // the format string after this point, however, as we will like just get
1661 // gibberish when trying to match arguments.
1662 keepGoing = false;
1663 }
1664
Richard Trieu03cf7b72011-10-28 00:41:25 +00001665 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_conversion)
1666 << StringRef(csStart, csLen),
1667 Loc, /*IsStringLocation*/true,
1668 getSpecifierRange(startSpec, specifierLen));
Ted Kremenekce815422010-07-19 21:25:57 +00001669
1670 return keepGoing;
1671}
1672
Richard Trieu03cf7b72011-10-28 00:41:25 +00001673void
1674CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
1675 const char *startSpec,
1676 unsigned specifierLen) {
1677 EmitFormatDiagnostic(
1678 S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
1679 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
1680}
1681
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001682bool
1683CheckFormatHandler::CheckNumArgs(
1684 const analyze_format_string::FormatSpecifier &FS,
1685 const analyze_format_string::ConversionSpecifier &CS,
1686 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1687
1688 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001689 PartialDiagnostic PDiag = FS.usesPositionalArg()
1690 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
1691 << (argIndex+1) << NumDataArgs)
1692 : S.PDiag(diag::warn_printf_insufficient_data_args);
1693 EmitFormatDiagnostic(
1694 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
1695 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001696 return false;
1697 }
1698 return true;
1699}
1700
Richard Trieu03cf7b72011-10-28 00:41:25 +00001701template<typename Range>
1702void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
1703 SourceLocation Loc,
1704 bool IsStringLocation,
1705 Range StringRange,
1706 FixItHint FixIt) {
1707 EmitFormatDiagnostic(S, inFunctionCall, TheCall->getArg(FormatIdx), PDiag,
1708 Loc, IsStringLocation, StringRange, FixIt);
1709}
1710
1711/// \brief If the format string is not within the funcion call, emit a note
1712/// so that the function call and string are in diagnostic messages.
1713///
1714/// \param inFunctionCall if true, the format string is within the function
1715/// call and only one diagnostic message will be produced. Otherwise, an
1716/// extra note will be emitted pointing to location of the format string.
1717///
1718/// \param ArgumentExpr the expression that is passed as the format string
1719/// argument in the function call. Used for getting locations when two
1720/// diagnostics are emitted.
1721///
1722/// \param PDiag the callee should already have provided any strings for the
1723/// diagnostic message. This function only adds locations and fixits
1724/// to diagnostics.
1725///
1726/// \param Loc primary location for diagnostic. If two diagnostics are
1727/// required, one will be at Loc and a new SourceLocation will be created for
1728/// the other one.
1729///
1730/// \param IsStringLocation if true, Loc points to the format string should be
1731/// used for the note. Otherwise, Loc points to the argument list and will
1732/// be used with PDiag.
1733///
1734/// \param StringRange some or all of the string to highlight. This is
1735/// templated so it can accept either a CharSourceRange or a SourceRange.
1736///
1737/// \param Fixit optional fix it hint for the format string.
1738template<typename Range>
1739void CheckFormatHandler::EmitFormatDiagnostic(Sema &S, bool InFunctionCall,
1740 const Expr *ArgumentExpr,
1741 PartialDiagnostic PDiag,
1742 SourceLocation Loc,
1743 bool IsStringLocation,
1744 Range StringRange,
1745 FixItHint FixIt) {
1746 if (InFunctionCall)
1747 S.Diag(Loc, PDiag) << StringRange << FixIt;
1748 else {
1749 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
1750 << ArgumentExpr->getSourceRange();
1751 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
1752 diag::note_format_string_defined)
1753 << StringRange << FixIt;
1754 }
1755}
1756
Ted Kremenek02087932010-07-16 02:11:22 +00001757//===--- CHECK: Printf format string checking ------------------------------===//
1758
1759namespace {
1760class CheckPrintfHandler : public CheckFormatHandler {
1761public:
1762 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1763 const Expr *origFormatExpr, unsigned firstDataArg,
1764 unsigned numDataArgs, bool isObjCLiteral,
1765 const char *beg, bool hasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001766 const CallExpr *theCall, unsigned formatIdx,
1767 bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00001768 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1769 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00001770 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00001771
1772
1773 bool HandleInvalidPrintfConversionSpecifier(
1774 const analyze_printf::PrintfSpecifier &FS,
1775 const char *startSpecifier,
1776 unsigned specifierLen);
1777
1778 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1779 const char *startSpecifier,
1780 unsigned specifierLen);
1781
1782 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1783 const char *startSpecifier, unsigned specifierLen);
1784 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1785 const analyze_printf::OptionalAmount &Amt,
1786 unsigned type,
1787 const char *startSpecifier, unsigned specifierLen);
1788 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1789 const analyze_printf::OptionalFlag &flag,
1790 const char *startSpecifier, unsigned specifierLen);
1791 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1792 const analyze_printf::OptionalFlag &ignoredFlag,
1793 const analyze_printf::OptionalFlag &flag,
1794 const char *startSpecifier, unsigned specifierLen);
1795};
1796}
1797
1798bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1799 const analyze_printf::PrintfSpecifier &FS,
1800 const char *startSpecifier,
1801 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001802 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001803 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001804
Ted Kremenekce815422010-07-19 21:25:57 +00001805 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1806 getLocationOfByte(CS.getStart()),
1807 startSpecifier, specifierLen,
1808 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001809}
1810
Ted Kremenek02087932010-07-16 02:11:22 +00001811bool CheckPrintfHandler::HandleAmount(
1812 const analyze_format_string::OptionalAmount &Amt,
1813 unsigned k, const char *startSpecifier,
1814 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001815
1816 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001817 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001818 unsigned argIndex = Amt.getArgIndex();
1819 if (argIndex >= NumDataArgs) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001820 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
1821 << k,
1822 getLocationOfByte(Amt.getStart()),
1823 /*IsStringLocation*/true,
1824 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001825 // Don't do any more checking. We will just emit
1826 // spurious errors.
1827 return false;
1828 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001829
Ted Kremenek5739de72010-01-29 01:06:55 +00001830 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001831 // Although not in conformance with C99, we also allow the argument to be
1832 // an 'unsigned int' as that is a reasonably safe case. GCC also
1833 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001834 CoveredArgs.set(argIndex);
1835 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001836 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001837
1838 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1839 assert(ATR.isValid());
1840
1841 if (!ATR.matchesType(S.Context, T)) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
1843 << k << ATR.getRepresentativeType(S.Context)
1844 << T << Arg->getSourceRange(),
1845 getLocationOfByte(Amt.getStart()),
1846 /*IsStringLocation*/true,
1847 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenek5739de72010-01-29 01:06:55 +00001848 // Don't do any more checking. We will just emit
1849 // spurious errors.
1850 return false;
1851 }
1852 }
1853 }
1854 return true;
1855}
Ted Kremenek5739de72010-01-29 01:06:55 +00001856
Tom Careb49ec692010-06-17 19:00:27 +00001857void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001858 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001859 const analyze_printf::OptionalAmount &Amt,
1860 unsigned type,
1861 const char *startSpecifier,
1862 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001863 const analyze_printf::PrintfConversionSpecifier &CS =
1864 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001865
Richard Trieu03cf7b72011-10-28 00:41:25 +00001866 FixItHint fixit =
1867 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
1868 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
1869 Amt.getConstantLength()))
1870 : FixItHint();
1871
1872 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
1873 << type << CS.toString(),
1874 getLocationOfByte(Amt.getStart()),
1875 /*IsStringLocation*/true,
1876 getSpecifierRange(startSpecifier, specifierLen),
1877 fixit);
Tom Careb49ec692010-06-17 19:00:27 +00001878}
1879
Ted Kremenek02087932010-07-16 02:11:22 +00001880void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001881 const analyze_printf::OptionalFlag &flag,
1882 const char *startSpecifier,
1883 unsigned specifierLen) {
1884 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001885 const analyze_printf::PrintfConversionSpecifier &CS =
1886 FS.getConversionSpecifier();
Richard Trieu03cf7b72011-10-28 00:41:25 +00001887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
1888 << flag.toString() << CS.toString(),
1889 getLocationOfByte(flag.getPosition()),
1890 /*IsStringLocation*/true,
1891 getSpecifierRange(startSpecifier, specifierLen),
1892 FixItHint::CreateRemoval(
1893 getSpecifierRange(flag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00001894}
1895
1896void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00001897 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001898 const analyze_printf::OptionalFlag &ignoredFlag,
1899 const analyze_printf::OptionalFlag &flag,
1900 const char *startSpecifier,
1901 unsigned specifierLen) {
1902 // Warn about ignored flag with a fixit removal.
Richard Trieu03cf7b72011-10-28 00:41:25 +00001903 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
1904 << ignoredFlag.toString() << flag.toString(),
1905 getLocationOfByte(ignoredFlag.getPosition()),
1906 /*IsStringLocation*/true,
1907 getSpecifierRange(startSpecifier, specifierLen),
1908 FixItHint::CreateRemoval(
1909 getSpecifierRange(ignoredFlag.getPosition(), 1)));
Tom Careb49ec692010-06-17 19:00:27 +00001910}
1911
Ted Kremenekab278de2010-01-28 23:39:18 +00001912bool
Ted Kremenek02087932010-07-16 02:11:22 +00001913CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00001914 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001915 const char *startSpecifier,
1916 unsigned specifierLen) {
1917
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001918 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00001919 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001920 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00001921
Ted Kremenek6cd69422010-07-19 22:01:06 +00001922 if (FS.consumesDataArgument()) {
1923 if (atFirstArg) {
1924 atFirstArg = false;
1925 usesPositionalArgs = FS.usesPositionalArg();
1926 }
1927 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00001928 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
1929 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00001930 return false;
1931 }
Ted Kremenek5739de72010-01-29 01:06:55 +00001932 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001933
Ted Kremenekd1668192010-02-27 01:41:03 +00001934 // First check if the field width, precision, and conversion specifier
1935 // have matching data arguments.
1936 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1937 startSpecifier, specifierLen)) {
1938 return false;
1939 }
1940
1941 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1942 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001943 return false;
1944 }
1945
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001946 if (!CS.consumesDataArgument()) {
1947 // FIXME: Technically specifying a precision or field width here
1948 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001949 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001950 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001951
Ted Kremenek4a49d982010-02-26 19:18:41 +00001952 // Consume the argument.
1953 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00001954 if (argIndex < NumDataArgs) {
1955 // The check to see if the argIndex is valid will come later.
1956 // We set the bit here because we may exit early from this
1957 // function if we encounter some other error.
1958 CoveredArgs.set(argIndex);
1959 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00001960
1961 // Check for using an Objective-C specific conversion specifier
1962 // in a non-ObjC literal.
1963 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001964 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1965 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00001966 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001967
Tom Careb49ec692010-06-17 19:00:27 +00001968 // Check for invalid use of field width
1969 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00001970 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00001971 startSpecifier, specifierLen);
1972 }
1973
1974 // Check for invalid use of precision
1975 if (!FS.hasValidPrecision()) {
1976 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1977 startSpecifier, specifierLen);
1978 }
1979
1980 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00001981 if (!FS.hasValidThousandsGroupingPrefix())
1982 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001983 if (!FS.hasValidLeadingZeros())
1984 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1985 if (!FS.hasValidPlusPrefix())
1986 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00001987 if (!FS.hasValidSpacePrefix())
1988 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001989 if (!FS.hasValidAlternativeForm())
1990 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1991 if (!FS.hasValidLeftJustified())
1992 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1993
1994 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00001995 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1996 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1997 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001998 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1999 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
2000 startSpecifier, specifierLen);
2001
2002 // Check the length modifier is valid with the given conversion specifier.
2003 const LengthModifier &LM = FS.getLengthModifier();
2004 if (!FS.hasValidLengthModifier())
Richard Trieu03cf7b72011-10-28 00:41:25 +00002005 EmitFormatDiagnostic(S.PDiag(diag::warn_format_nonsensical_length)
2006 << LM.toString() << CS.toString(),
2007 getLocationOfByte(LM.getStart()),
2008 /*IsStringLocation*/true,
2009 getSpecifierRange(startSpecifier, specifierLen),
2010 FixItHint::CreateRemoval(
2011 getSpecifierRange(LM.getStart(),
2012 LM.getLength())));
Tom Careb49ec692010-06-17 19:00:27 +00002013
2014 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00002015 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00002016 // Issue a warning about this being a possible security issue.
Richard Trieu03cf7b72011-10-28 00:41:25 +00002017 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_write_back),
2018 getLocationOfByte(CS.getStart()),
2019 /*IsStringLocation*/true,
2020 getSpecifierRange(startSpecifier, specifierLen));
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00002021 // Continue checking the other format specifiers.
2022 return true;
2023 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00002024
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002025 // The remaining checks depend on the data arguments.
2026 if (HasVAListArg)
2027 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002028
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002029 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00002030 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002031
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002032 // Now type check the data expression that matches the
2033 // format specifier.
2034 const Expr *Ex = getDataArg(argIndex);
2035 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
2036 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
2037 // Check if we didn't match because of an implicit cast from a 'char'
2038 // or 'short' to an 'int'. This is done because printf is a varargs
2039 // function.
2040 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00002041 if (ICE->getType() == S.Context.IntTy) {
2042 // All further checking is done on the subexpression.
2043 Ex = ICE->getSubExpr();
2044 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002045 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00002046 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002047
2048 // We may be able to offer a FixItHint if it is a supported type.
2049 PrintfSpecifier fixedFS = FS;
Hans Wennborgf99d04f2011-10-18 08:10:06 +00002050 bool success = fixedFS.fixType(Ex->getType(), S.getLangOptions());
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002051
2052 if (success) {
2053 // Get the fix string from the fixed format specifier
2054 llvm::SmallString<128> buf;
2055 llvm::raw_svector_ostream os(buf);
2056 fixedFS.toString(os);
2057
Ted Kremenek5f0c0662010-08-24 22:24:51 +00002058 // FIXME: getRepresentativeType() perhaps should return a string
2059 // instead of a QualType to better handle when the representative
2060 // type is 'wint_t' (which is defined in the system headers).
Richard Trieu03cf7b72011-10-28 00:41:25 +00002061 EmitFormatDiagnostic(
2062 S.PDiag(diag::warn_printf_conversion_argument_type_mismatch)
2063 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2064 << Ex->getSourceRange(),
2065 getLocationOfByte(CS.getStart()),
2066 /*IsStringLocation*/true,
2067 getSpecifierRange(startSpecifier, specifierLen),
2068 FixItHint::CreateReplacement(
2069 getSpecifierRange(startSpecifier, specifierLen),
2070 os.str()));
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00002071 }
2072 else {
2073 S.Diag(getLocationOfByte(CS.getStart()),
2074 diag::warn_printf_conversion_argument_type_mismatch)
2075 << ATR.getRepresentativeType(S.Context) << Ex->getType()
2076 << getSpecifierRange(startSpecifier, specifierLen)
2077 << Ex->getSourceRange();
2078 }
2079 }
2080
Ted Kremenekab278de2010-01-28 23:39:18 +00002081 return true;
2082}
2083
Ted Kremenek02087932010-07-16 02:11:22 +00002084//===--- CHECK: Scanf format string checking ------------------------------===//
2085
2086namespace {
2087class CheckScanfHandler : public CheckFormatHandler {
2088public:
2089 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2090 const Expr *origFormatExpr, unsigned firstDataArg,
2091 unsigned numDataArgs, bool isObjCLiteral,
2092 const char *beg, bool hasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002093 const CallExpr *theCall, unsigned formatIdx,
2094 bool inFunctionCall)
Ted Kremenek02087932010-07-16 02:11:22 +00002095 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2096 numDataArgs, isObjCLiteral, beg, hasVAListArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002097 theCall, formatIdx, inFunctionCall) {}
Ted Kremenek02087932010-07-16 02:11:22 +00002098
2099 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2100 const char *startSpecifier,
2101 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002102
2103 bool HandleInvalidScanfConversionSpecifier(
2104 const analyze_scanf::ScanfSpecifier &FS,
2105 const char *startSpecifier,
2106 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002107
2108 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00002109};
Ted Kremenek019d2242010-01-29 01:50:07 +00002110}
Ted Kremenekab278de2010-01-28 23:39:18 +00002111
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002112void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2113 const char *end) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002114 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
2115 getLocationOfByte(end), /*IsStringLocation*/true,
2116 getSpecifierRange(start, end - start));
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002117}
2118
Ted Kremenekce815422010-07-19 21:25:57 +00002119bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2120 const analyze_scanf::ScanfSpecifier &FS,
2121 const char *startSpecifier,
2122 unsigned specifierLen) {
2123
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002124 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002125 FS.getConversionSpecifier();
2126
2127 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2128 getLocationOfByte(CS.getStart()),
2129 startSpecifier, specifierLen,
2130 CS.getStart(), CS.getLength());
2131}
2132
Ted Kremenek02087932010-07-16 02:11:22 +00002133bool CheckScanfHandler::HandleScanfSpecifier(
2134 const analyze_scanf::ScanfSpecifier &FS,
2135 const char *startSpecifier,
2136 unsigned specifierLen) {
2137
2138 using namespace analyze_scanf;
2139 using namespace analyze_format_string;
2140
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002141 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002142
Ted Kremenek6cd69422010-07-19 22:01:06 +00002143 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2144 // be used to decide if we are using positional arguments consistently.
2145 if (FS.consumesDataArgument()) {
2146 if (atFirstArg) {
2147 atFirstArg = false;
2148 usesPositionalArgs = FS.usesPositionalArg();
2149 }
2150 else if (usesPositionalArgs != FS.usesPositionalArg()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002151 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
2152 startSpecifier, specifierLen);
Ted Kremenek6cd69422010-07-19 22:01:06 +00002153 return false;
2154 }
Ted Kremenek02087932010-07-16 02:11:22 +00002155 }
2156
2157 // Check if the field with is non-zero.
2158 const OptionalAmount &Amt = FS.getFieldWidth();
2159 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2160 if (Amt.getConstantAmount() == 0) {
2161 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2162 Amt.getConstantLength());
Richard Trieu03cf7b72011-10-28 00:41:25 +00002163 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
2164 getLocationOfByte(Amt.getStart()),
2165 /*IsStringLocation*/true, R,
2166 FixItHint::CreateRemoval(R));
Ted Kremenek02087932010-07-16 02:11:22 +00002167 }
2168 }
2169
2170 if (!FS.consumesDataArgument()) {
2171 // FIXME: Technically specifying a precision or field width here
2172 // makes no sense. Worth issuing a warning at some point.
2173 return true;
2174 }
2175
2176 // Consume the argument.
2177 unsigned argIndex = FS.getArgIndex();
2178 if (argIndex < NumDataArgs) {
2179 // The check to see if the argIndex is valid will come later.
2180 // We set the bit here because we may exit early from this
2181 // function if we encounter some other error.
2182 CoveredArgs.set(argIndex);
2183 }
2184
Ted Kremenek4407ea42010-07-20 20:04:47 +00002185 // Check the length modifier is valid with the given conversion specifier.
2186 const LengthModifier &LM = FS.getLengthModifier();
2187 if (!FS.hasValidLengthModifier()) {
2188 S.Diag(getLocationOfByte(LM.getStart()),
2189 diag::warn_format_nonsensical_length)
2190 << LM.toString() << CS.toString()
2191 << getSpecifierRange(startSpecifier, specifierLen)
2192 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2193 LM.getLength()));
2194 }
2195
Ted Kremenek02087932010-07-16 02:11:22 +00002196 // The remaining checks depend on the data arguments.
2197 if (HasVAListArg)
2198 return true;
2199
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002200 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00002201 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00002202
2203 // FIXME: Check that the argument type matches the format specifier.
2204
2205 return true;
2206}
2207
2208void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00002209 const Expr *OrigFormatExpr,
2210 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00002211 unsigned format_idx, unsigned firstDataArg,
Richard Trieu03cf7b72011-10-28 00:41:25 +00002212 bool isPrintf, bool inFunctionCall) {
Ted Kremenek02087932010-07-16 02:11:22 +00002213
Ted Kremenekab278de2010-01-28 23:39:18 +00002214 // CHECK: is the format string a wide literal?
Douglas Gregorfb65e592011-07-27 05:40:30 +00002215 if (!FExpr->isAscii()) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002216 CheckFormatHandler::EmitFormatDiagnostic(
2217 *this, inFunctionCall, TheCall->getArg(format_idx),
2218 PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
2219 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002220 return;
2221 }
Ted Kremenek02087932010-07-16 02:11:22 +00002222
Ted Kremenekab278de2010-01-28 23:39:18 +00002223 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002224 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002225 const char *Str = StrRef.data();
2226 unsigned StrLen = StrRef.size();
Ted Kremenek6e302b22011-09-29 05:52:16 +00002227 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00002228
Ted Kremenekab278de2010-01-28 23:39:18 +00002229 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00002230 if (StrLen == 0 && numDataArgs > 0) {
Richard Trieu03cf7b72011-10-28 00:41:25 +00002231 CheckFormatHandler::EmitFormatDiagnostic(
2232 *this, inFunctionCall, TheCall->getArg(format_idx),
2233 PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
2234 /*IsStringLocation*/true, OrigFormatExpr->getSourceRange());
Ted Kremenekab278de2010-01-28 23:39:18 +00002235 return;
2236 }
Ted Kremenek02087932010-07-16 02:11:22 +00002237
2238 if (isPrintf) {
2239 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002240 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002241 Str, HasVAListArg, TheCall, format_idx,
2242 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002243
2244 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2245 H.DoneProcessing();
2246 }
2247 else {
2248 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002249 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
Richard Trieu03cf7b72011-10-28 00:41:25 +00002250 Str, HasVAListArg, TheCall, format_idx,
2251 inFunctionCall);
Ted Kremenek02087932010-07-16 02:11:22 +00002252
2253 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2254 H.DoneProcessing();
2255 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00002256}
2257
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002258//===--- CHECK: Standard memory functions ---------------------------------===//
2259
Douglas Gregora74926b2011-05-03 20:05:22 +00002260/// \brief Determine whether the given type is a dynamic class type (e.g.,
2261/// whether it has a vtable).
2262static bool isDynamicClassType(QualType T) {
2263 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2264 if (CXXRecordDecl *Definition = Record->getDefinition())
2265 if (Definition->isDynamicClass())
2266 return true;
2267
2268 return false;
2269}
2270
Chandler Carruth889ed862011-06-21 23:04:20 +00002271/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002272/// otherwise returns NULL.
2273static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00002274 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002275 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2276 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2277 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002278
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002279 return 0;
2280}
2281
Chandler Carruth889ed862011-06-21 23:04:20 +00002282/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002283static QualType getSizeOfArgType(const Expr* E) {
2284 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2285 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2286 if (SizeOf->getKind() == clang::UETT_SizeOf)
2287 return SizeOf->getTypeOfArgument();
2288
2289 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00002290}
2291
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002292/// \brief Check for dangerous or invalid arguments to memset().
2293///
Chandler Carruthac687262011-06-03 06:23:57 +00002294/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002295/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2296/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002297///
2298/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002299void Sema::CheckMemaccessArguments(const CallExpr *Call,
2300 CheckedMemoryFunction CMF,
2301 IdentifierInfo *FnName) {
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002302 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00002303 // we have enough arguments, and if not, abort further checking.
Nico Weber39bfed82011-10-13 22:30:23 +00002304 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2305 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002306 return;
2307
Nico Weber39bfed82011-10-13 22:30:23 +00002308 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2309 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2310 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002311
2312 // We have special checking when the length is a sizeof expression.
2313 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2314 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2315 llvm::FoldingSetNodeID SizeOfArgID;
2316
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002317 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2318 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002319 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002320
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002321 QualType DestTy = Dest->getType();
2322 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2323 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002324
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002325 // Never warn about void type pointers. This can be used to suppress
2326 // false positives.
2327 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002328 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002329
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002330 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2331 // actually comparing the expressions for equality. Because computing the
2332 // expression IDs can be expensive, we only do this if the diagnostic is
2333 // enabled.
2334 if (SizeOfArg &&
2335 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2336 SizeOfArg->getExprLoc())) {
2337 // We only compute IDs for expressions if the warning is enabled, and
2338 // cache the sizeof arg's ID.
2339 if (SizeOfArgID == llvm::FoldingSetNodeID())
2340 SizeOfArg->Profile(SizeOfArgID, Context, true);
2341 llvm::FoldingSetNodeID DestID;
2342 Dest->Profile(DestID, Context, true);
2343 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00002344 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2345 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002346 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2347 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2348 if (UnaryOp->getOpcode() == UO_AddrOf)
2349 ActionIdx = 1; // If its an address-of operator, just remove it.
2350 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2351 ActionIdx = 2; // If the pointee's size is sizeof(char),
2352 // suggest an explicit length.
Nico Weber39bfed82011-10-13 22:30:23 +00002353 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002354 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2355 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Weber39bfed82011-10-13 22:30:23 +00002356 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002357 << Dest->getSourceRange()
2358 << SizeOfArg->getSourceRange());
2359 break;
2360 }
2361 }
2362
2363 // Also check for cases where the sizeof argument is the exact same
2364 // type as the memory argument, and where it points to a user-defined
2365 // record type.
2366 if (SizeOfArgTy != QualType()) {
2367 if (PointeeTy->isRecordType() &&
2368 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2369 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2370 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2371 << FnName << SizeOfArgTy << ArgIdx
2372 << PointeeTy << Dest->getSourceRange()
2373 << LenExpr->getSourceRange());
2374 break;
2375 }
Nico Weberc5e73862011-06-14 16:14:58 +00002376 }
2377
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002378 // Always complain about dynamic classes.
John McCall31168b02011-06-15 23:02:42 +00002379 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002380 DiagRuntimeBehavior(
2381 Dest->getExprLoc(), Dest,
2382 PDiag(diag::warn_dyn_class_memaccess)
2383 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2384 // "overwritten" if we're warning about the destination for any call
2385 // but memcmp; otherwise a verb appropriate to the call.
2386 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2387 << Call->getCallee()->getSourceRange());
Douglas Gregor18739c32011-06-16 17:56:04 +00002388 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002389 DiagRuntimeBehavior(
2390 Dest->getExprLoc(), Dest,
2391 PDiag(diag::warn_arc_object_memaccess)
2392 << ArgIdx << FnName << PointeeTy
2393 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00002394 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002395 continue;
John McCall31168b02011-06-15 23:02:42 +00002396
2397 DiagRuntimeBehavior(
2398 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00002399 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002400 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2401 break;
2402 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002403 }
2404}
2405
Ted Kremenek6865f772011-08-18 20:55:45 +00002406// A little helper routine: ignore addition and subtraction of integer literals.
2407// This intentionally does not ignore all integer constant expressions because
2408// we don't want to remove sizeof().
2409static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2410 Ex = Ex->IgnoreParenCasts();
2411
2412 for (;;) {
2413 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2414 if (!BO || !BO->isAdditiveOp())
2415 break;
2416
2417 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2418 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2419
2420 if (isa<IntegerLiteral>(RHS))
2421 Ex = LHS;
2422 else if (isa<IntegerLiteral>(LHS))
2423 Ex = RHS;
2424 else
2425 break;
2426 }
2427
2428 return Ex;
2429}
2430
2431// Warn if the user has made the 'size' argument to strlcpy or strlcat
2432// be the size of the source, instead of the destination.
2433void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2434 IdentifierInfo *FnName) {
2435
2436 // Don't crash if the user has the wrong number of arguments
2437 if (Call->getNumArgs() != 3)
2438 return;
2439
2440 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2441 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2442 const Expr *CompareWithSrc = NULL;
2443
2444 // Look for 'strlcpy(dst, x, sizeof(x))'
2445 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2446 CompareWithSrc = Ex;
2447 else {
2448 // Look for 'strlcpy(dst, x, strlen(x))'
2449 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2450 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2451 && SizeCall->getNumArgs() == 1)
2452 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2453 }
2454 }
2455
2456 if (!CompareWithSrc)
2457 return;
2458
2459 // Determine if the argument to sizeof/strlen is equal to the source
2460 // argument. In principle there's all kinds of things you could do
2461 // here, for instance creating an == expression and evaluating it with
2462 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2463 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2464 if (!SrcArgDRE)
2465 return;
2466
2467 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2468 if (!CompareWithSrcDRE ||
2469 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2470 return;
2471
2472 const Expr *OriginalSizeArg = Call->getArg(2);
2473 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2474 << OriginalSizeArg->getSourceRange() << FnName;
2475
2476 // Output a FIXIT hint if the destination is an array (rather than a
2477 // pointer to an array). This could be enhanced to handle some
2478 // pointers if we know the actual size, like if DstArg is 'array+2'
2479 // we could say 'sizeof(array)-2'.
2480 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek18db5d42011-08-18 22:48:41 +00002481 QualType DstArgTy = DstArg->getType();
Ted Kremenek6865f772011-08-18 20:55:45 +00002482
Ted Kremenek18db5d42011-08-18 22:48:41 +00002483 // Only handle constant-sized or VLAs, but not flexible members.
2484 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2485 // Only issue the FIXIT for arrays of size > 1.
2486 if (CAT->getSize().getSExtValue() <= 1)
2487 return;
2488 } else if (!DstArgTy->isVariableArrayType()) {
2489 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00002490 }
Ted Kremenek18db5d42011-08-18 22:48:41 +00002491
2492 llvm::SmallString<128> sizeString;
2493 llvm::raw_svector_ostream OS(sizeString);
2494 OS << "sizeof(";
Douglas Gregor75acd922011-09-27 23:30:47 +00002495 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00002496 OS << ")";
2497
2498 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2499 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2500 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00002501}
2502
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002503//===--- CHECK: Return Address of Stack Variable --------------------------===//
2504
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002505static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2506static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002507
2508/// CheckReturnStackAddr - Check if a return statement returns the address
2509/// of a stack variable.
2510void
2511Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2512 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00002513
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002514 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002515 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002516
2517 // Perform checking for returned stack addresses, local blocks,
2518 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00002519 if (lhsType->isPointerType() ||
2520 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002521 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00002522 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002523 stackE = EvalVal(RetValExp, refVars);
2524 }
2525
2526 if (stackE == 0)
2527 return; // Nothing suspicious was found.
2528
2529 SourceLocation diagLoc;
2530 SourceRange diagRange;
2531 if (refVars.empty()) {
2532 diagLoc = stackE->getLocStart();
2533 diagRange = stackE->getSourceRange();
2534 } else {
2535 // We followed through a reference variable. 'stackE' contains the
2536 // problematic expression but we will warn at the return statement pointing
2537 // at the reference variable. We will later display the "trail" of
2538 // reference variables using notes.
2539 diagLoc = refVars[0]->getLocStart();
2540 diagRange = refVars[0]->getSourceRange();
2541 }
2542
2543 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2544 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2545 : diag::warn_ret_stack_addr)
2546 << DR->getDecl()->getDeclName() << diagRange;
2547 } else if (isa<BlockExpr>(stackE)) { // local block.
2548 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2549 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2550 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2551 } else { // local temporary.
2552 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2553 : diag::warn_ret_local_temp_addr)
2554 << diagRange;
2555 }
2556
2557 // Display the "trail" of reference variables that we followed until we
2558 // found the problematic expression using notes.
2559 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2560 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2561 // If this var binds to another reference var, show the range of the next
2562 // var, otherwise the var binds to the problematic expression, in which case
2563 // show the range of the expression.
2564 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2565 : stackE->getSourceRange();
2566 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2567 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002568 }
2569}
2570
2571/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2572/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002573/// to a location on the stack, a local block, an address of a label, or a
2574/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002575/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002576/// encounter a subexpression that (1) clearly does not lead to one of the
2577/// above problematic expressions (2) is something we cannot determine leads to
2578/// a problematic expression based on such local checking.
2579///
2580/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2581/// the expression that they point to. Such variables are added to the
2582/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002583///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002584/// EvalAddr processes expressions that are pointers that are used as
2585/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002586/// At the base case of the recursion is a check for the above problematic
2587/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002588///
2589/// This implementation handles:
2590///
2591/// * pointer-to-pointer casts
2592/// * implicit conversions from array references to pointers
2593/// * taking the address of fields
2594/// * arbitrary interplay between "&" and "*" operators
2595/// * pointer arithmetic from an address of a stack variable
2596/// * taking the address of an array element where the array is on the stack
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002597static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002598 if (E->isTypeDependent())
2599 return NULL;
2600
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002601 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00002602 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002603 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002604 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00002605 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00002606
Peter Collingbourne91147592011-04-15 00:35:48 +00002607 E = E->IgnoreParens();
2608
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002609 // Our "symbolic interpreter" is just a dispatch off the currently
2610 // viewed AST node. We then recursively traverse the AST by calling
2611 // EvalAddr and EvalVal appropriately.
2612 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002613 case Stmt::DeclRefExprClass: {
2614 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2615
2616 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2617 // If this is a reference variable, follow through to the expression that
2618 // it points to.
2619 if (V->hasLocalStorage() &&
2620 V->getType()->isReferenceType() && V->hasInit()) {
2621 // Add the reference variable to the "trail".
2622 refVars.push_back(DR);
2623 return EvalAddr(V->getInit(), refVars);
2624 }
2625
2626 return NULL;
2627 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002628
Chris Lattner934edb22007-12-28 05:31:15 +00002629 case Stmt::UnaryOperatorClass: {
2630 // The only unary operator that make sense to handle here
2631 // is AddrOf. All others don't make sense as pointers.
2632 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002633
John McCalle3027922010-08-25 11:45:40 +00002634 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002635 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002636 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002637 return NULL;
2638 }
Mike Stump11289f42009-09-09 15:08:12 +00002639
Chris Lattner934edb22007-12-28 05:31:15 +00002640 case Stmt::BinaryOperatorClass: {
2641 // Handle pointer arithmetic. All other binary operators are not valid
2642 // in this context.
2643 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00002644 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00002645
John McCalle3027922010-08-25 11:45:40 +00002646 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00002647 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002648
Chris Lattner934edb22007-12-28 05:31:15 +00002649 Expr *Base = B->getLHS();
2650
2651 // Determine which argument is the real pointer base. It could be
2652 // the RHS argument instead of the LHS.
2653 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00002654
Chris Lattner934edb22007-12-28 05:31:15 +00002655 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002656 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002657 }
Steve Naroff2752a172008-09-10 19:17:48 +00002658
Chris Lattner934edb22007-12-28 05:31:15 +00002659 // For conditional operators we need to see if either the LHS or RHS are
2660 // valid DeclRefExpr*s. If one of them is valid, we return it.
2661 case Stmt::ConditionalOperatorClass: {
2662 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002663
Chris Lattner934edb22007-12-28 05:31:15 +00002664 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002665 if (Expr *lhsExpr = C->getLHS()) {
2666 // In C++, we can have a throw-expression, which has 'void' type.
2667 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002668 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002669 return LHS;
2670 }
Chris Lattner934edb22007-12-28 05:31:15 +00002671
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002672 // In C++, we can have a throw-expression, which has 'void' type.
2673 if (C->getRHS()->getType()->isVoidType())
2674 return NULL;
2675
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002676 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002677 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002678
2679 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00002680 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002681 return E; // local block.
2682 return NULL;
2683
2684 case Stmt::AddrLabelExprClass:
2685 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00002686
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002687 // For casts, we need to handle conversions from arrays to
2688 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00002689 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00002690 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00002691 case Stmt::CXXFunctionalCastExprClass:
2692 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00002693 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002694 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002695
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002696 if (SubExpr->getType()->isPointerType() ||
2697 SubExpr->getType()->isBlockPointerType() ||
2698 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002699 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002700 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002701 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002702 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002703 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00002704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705
Chris Lattner934edb22007-12-28 05:31:15 +00002706 // C++ casts. For dynamic casts, static casts, and const casts, we
2707 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00002708 // through the cast. In the case the dynamic cast doesn't fail (and
2709 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00002710 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00002711 // FIXME: The comment about is wrong; we're not always converting
2712 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00002713 // handle references to objects.
2714 case Stmt::CXXStaticCastExprClass:
2715 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00002716 case Stmt::CXXConstCastExprClass:
2717 case Stmt::CXXReinterpretCastExprClass: {
2718 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002719 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002720 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002721 else
2722 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00002723 }
Mike Stump11289f42009-09-09 15:08:12 +00002724
Douglas Gregorfe314812011-06-21 17:03:29 +00002725 case Stmt::MaterializeTemporaryExprClass:
2726 if (Expr *Result = EvalAddr(
2727 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2728 refVars))
2729 return Result;
2730
2731 return E;
2732
Chris Lattner934edb22007-12-28 05:31:15 +00002733 // Everything else: we simply don't reason about them.
2734 default:
2735 return NULL;
2736 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002737}
Mike Stump11289f42009-09-09 15:08:12 +00002738
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002739
2740/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2741/// See the comments for EvalAddr for more details.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002742static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002743do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002744 // We should only be called for evaluating non-pointer expressions, or
2745 // expressions with a pointer type that are not used as references but instead
2746 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00002747
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002748 // Our "symbolic interpreter" is just a dispatch off the currently
2749 // viewed AST node. We then recursively traverse the AST by calling
2750 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00002751
2752 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002753 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002754 case Stmt::ImplicitCastExprClass: {
2755 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002756 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002757 E = IE->getSubExpr();
2758 continue;
2759 }
2760 return NULL;
2761 }
2762
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002763 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002764 // When we hit a DeclRefExpr we are looking at code that refers to a
2765 // variable's name. If it's not a reference variable we check if it has
2766 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002767 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002768
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002769 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002770 if (V->hasLocalStorage()) {
2771 if (!V->getType()->isReferenceType())
2772 return DR;
2773
2774 // Reference variable, follow through to the expression that
2775 // it points to.
2776 if (V->hasInit()) {
2777 // Add the reference variable to the "trail".
2778 refVars.push_back(DR);
2779 return EvalVal(V->getInit(), refVars);
2780 }
2781 }
Mike Stump11289f42009-09-09 15:08:12 +00002782
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002783 return NULL;
2784 }
Mike Stump11289f42009-09-09 15:08:12 +00002785
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002786 case Stmt::UnaryOperatorClass: {
2787 // The only unary operator that make sense to handle here
2788 // is Deref. All others don't resolve to a "name." This includes
2789 // handling all sorts of rvalues passed to a unary operator.
2790 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002791
John McCalle3027922010-08-25 11:45:40 +00002792 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002793 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002794
2795 return NULL;
2796 }
Mike Stump11289f42009-09-09 15:08:12 +00002797
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002798 case Stmt::ArraySubscriptExprClass: {
2799 // Array subscripts are potential references to data on the stack. We
2800 // retrieve the DeclRefExpr* for the array variable if it indeed
2801 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002802 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002803 }
Mike Stump11289f42009-09-09 15:08:12 +00002804
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002805 case Stmt::ConditionalOperatorClass: {
2806 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002807 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002808 ConditionalOperator *C = cast<ConditionalOperator>(E);
2809
Anders Carlsson801c5c72007-11-30 19:04:31 +00002810 // Handle the GNU extension for missing LHS.
2811 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002812 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002813 return LHS;
2814
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002815 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002816 }
Mike Stump11289f42009-09-09 15:08:12 +00002817
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002818 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002819 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002820 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002821
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002822 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002823 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002824 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002825
2826 // Check whether the member type is itself a reference, in which case
2827 // we're not going to refer to the member, but to what the member refers to.
2828 if (M->getMemberDecl()->getType()->isReferenceType())
2829 return NULL;
2830
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002831 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002832 }
Mike Stump11289f42009-09-09 15:08:12 +00002833
Douglas Gregorfe314812011-06-21 17:03:29 +00002834 case Stmt::MaterializeTemporaryExprClass:
2835 if (Expr *Result = EvalVal(
2836 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2837 refVars))
2838 return Result;
2839
2840 return E;
2841
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002842 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002843 // Check that we don't return or take the address of a reference to a
2844 // temporary. This is only useful in C++.
2845 if (!E->isTypeDependent() && E->isRValue())
2846 return E;
2847
2848 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002849 return NULL;
2850 }
Ted Kremenekb7861562010-08-04 20:01:07 +00002851} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002852}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002853
2854//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2855
2856/// Check for comparisons of floating point operands using != and ==.
2857/// Issue a warning if these are no self-comparisons, as they are not likely
2858/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00002859void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002860 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00002861
Richard Trieu82402a02011-09-15 21:56:47 +00002862 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2863 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002864
2865 // Special case: check for x == x (which is OK).
2866 // Do not emit warnings for such cases.
2867 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2868 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2869 if (DRL->getDecl() == DRR->getDecl())
2870 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002871
2872
Ted Kremenekeda40e22007-11-29 00:59:04 +00002873 // Special case: check for comparisons against literals that can be exactly
2874 // represented by APFloat. In such cases, do not emit a warning. This
2875 // is a heuristic: often comparison against such literals are used to
2876 // detect if a value in a variable has not changed. This clearly can
2877 // lead to false negatives.
2878 if (EmitWarning) {
2879 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2880 if (FLL->isExact())
2881 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00002882 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00002883 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2884 if (FLR->isExact())
2885 EmitWarning = false;
2886 }
2887 }
Mike Stump11289f42009-09-09 15:08:12 +00002888
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002889 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002890 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002891 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002892 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002893 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002894
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002895 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002896 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002897 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002898 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002899
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002900 // Emit the diagnostic.
2901 if (EmitWarning)
Richard Trieu82402a02011-09-15 21:56:47 +00002902 Diag(Loc, diag::warn_floatingpoint_eq)
2903 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002904}
John McCallca01b222010-01-04 23:21:16 +00002905
John McCall70aa5392010-01-06 05:24:50 +00002906//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2907//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00002908
John McCall70aa5392010-01-06 05:24:50 +00002909namespace {
John McCallca01b222010-01-04 23:21:16 +00002910
John McCall70aa5392010-01-06 05:24:50 +00002911/// Structure recording the 'active' range of an integer-valued
2912/// expression.
2913struct IntRange {
2914 /// The number of bits active in the int.
2915 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00002916
John McCall70aa5392010-01-06 05:24:50 +00002917 /// True if the int is known not to have negative values.
2918 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00002919
John McCall70aa5392010-01-06 05:24:50 +00002920 IntRange(unsigned Width, bool NonNegative)
2921 : Width(Width), NonNegative(NonNegative)
2922 {}
John McCallca01b222010-01-04 23:21:16 +00002923
John McCall817d4af2010-11-10 23:38:19 +00002924 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00002925 static IntRange forBoolType() {
2926 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00002927 }
2928
John McCall817d4af2010-11-10 23:38:19 +00002929 /// Returns the range of an opaque value of the given integral type.
2930 static IntRange forValueOfType(ASTContext &C, QualType T) {
2931 return forValueOfCanonicalType(C,
2932 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00002933 }
2934
John McCall817d4af2010-11-10 23:38:19 +00002935 /// Returns the range of an opaque value of a canonical integral type.
2936 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00002937 assert(T->isCanonicalUnqualified());
2938
2939 if (const VectorType *VT = dyn_cast<VectorType>(T))
2940 T = VT->getElementType().getTypePtr();
2941 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2942 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00002943
John McCall18a2c2c2010-11-09 22:22:12 +00002944 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00002945 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2946 EnumDecl *Enum = ET->getDecl();
John McCallf937c022011-10-07 06:10:15 +00002947 if (!Enum->isCompleteDefinition())
John McCall18a2c2c2010-11-09 22:22:12 +00002948 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2949
John McCallcc7e5bf2010-05-06 08:58:33 +00002950 unsigned NumPositive = Enum->getNumPositiveBits();
2951 unsigned NumNegative = Enum->getNumNegativeBits();
2952
2953 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2954 }
John McCall70aa5392010-01-06 05:24:50 +00002955
2956 const BuiltinType *BT = cast<BuiltinType>(T);
2957 assert(BT->isInteger());
2958
2959 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2960 }
2961
John McCall817d4af2010-11-10 23:38:19 +00002962 /// Returns the "target" range of a canonical integral type, i.e.
2963 /// the range of values expressible in the type.
2964 ///
2965 /// This matches forValueOfCanonicalType except that enums have the
2966 /// full range of their type, not the range of their enumerators.
2967 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2968 assert(T->isCanonicalUnqualified());
2969
2970 if (const VectorType *VT = dyn_cast<VectorType>(T))
2971 T = VT->getElementType().getTypePtr();
2972 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2973 T = CT->getElementType().getTypePtr();
2974 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00002975 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00002976
2977 const BuiltinType *BT = cast<BuiltinType>(T);
2978 assert(BT->isInteger());
2979
2980 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2981 }
2982
2983 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00002984 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00002985 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00002986 L.NonNegative && R.NonNegative);
2987 }
2988
John McCall817d4af2010-11-10 23:38:19 +00002989 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00002990 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00002991 return IntRange(std::min(L.Width, R.Width),
2992 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00002993 }
2994};
2995
2996IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2997 if (value.isSigned() && value.isNegative())
2998 return IntRange(value.getMinSignedBits(), false);
2999
3000 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00003001 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003002
3003 // isNonNegative() just checks the sign bit without considering
3004 // signedness.
3005 return IntRange(value.getActiveBits(), true);
3006}
3007
John McCall74430522010-01-06 22:57:21 +00003008IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00003009 unsigned MaxWidth) {
3010 if (result.isInt())
3011 return GetValueRange(C, result.getInt(), MaxWidth);
3012
3013 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00003014 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
3015 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
3016 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
3017 R = IntRange::join(R, El);
3018 }
John McCall70aa5392010-01-06 05:24:50 +00003019 return R;
3020 }
3021
3022 if (result.isComplexInt()) {
3023 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
3024 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
3025 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00003026 }
3027
3028 // This can happen with lossless casts to intptr_t of "based" lvalues.
3029 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00003030 // FIXME: The only reason we need to pass the type in here is to get
3031 // the sign right on this one case. It would be nice if APValue
3032 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00003033 assert(result.isLValue());
Douglas Gregor61b6e492011-05-21 16:28:01 +00003034 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00003035}
John McCall70aa5392010-01-06 05:24:50 +00003036
3037/// Pseudo-evaluate the given integer expression, estimating the
3038/// range of values it might take.
3039///
3040/// \param MaxWidth - the width to which the value will be truncated
3041IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
3042 E = E->IgnoreParens();
3043
3044 // Try a full evaluation first.
3045 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003046 if (E->EvaluateAsRValue(result, C))
John McCall74430522010-01-06 22:57:21 +00003047 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00003048
3049 // I think we only want to look through implicit casts here; if the
3050 // user has an explicit widening cast, we should treat the value as
3051 // being of the new, wider type.
3052 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00003053 if (CE->getCastKind() == CK_NoOp)
John McCall70aa5392010-01-06 05:24:50 +00003054 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
3055
John McCall817d4af2010-11-10 23:38:19 +00003056 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00003057
John McCalle3027922010-08-25 11:45:40 +00003058 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00003059
John McCall70aa5392010-01-06 05:24:50 +00003060 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00003061 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00003062 return OutputTypeRange;
3063
3064 IntRange SubRange
3065 = GetExprRange(C, CE->getSubExpr(),
3066 std::min(MaxWidth, OutputTypeRange.Width));
3067
3068 // Bail out if the subexpr's range is as wide as the cast type.
3069 if (SubRange.Width >= OutputTypeRange.Width)
3070 return OutputTypeRange;
3071
3072 // Otherwise, we take the smaller width, and we're non-negative if
3073 // either the output type or the subexpr is.
3074 return IntRange(SubRange.Width,
3075 SubRange.NonNegative || OutputTypeRange.NonNegative);
3076 }
3077
3078 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3079 // If we can fold the condition, just take that operand.
3080 bool CondResult;
3081 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
3082 return GetExprRange(C, CondResult ? CO->getTrueExpr()
3083 : CO->getFalseExpr(),
3084 MaxWidth);
3085
3086 // Otherwise, conservatively merge.
3087 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
3088 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3089 return IntRange::join(L, R);
3090 }
3091
3092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3093 switch (BO->getOpcode()) {
3094
3095 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00003096 case BO_LAnd:
3097 case BO_LOr:
3098 case BO_LT:
3099 case BO_GT:
3100 case BO_LE:
3101 case BO_GE:
3102 case BO_EQ:
3103 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00003104 return IntRange::forBoolType();
3105
John McCallc3688382011-07-13 06:35:24 +00003106 // The type of the assignments is the type of the LHS, so the RHS
3107 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00003108 case BO_MulAssign:
3109 case BO_DivAssign:
3110 case BO_RemAssign:
3111 case BO_AddAssign:
3112 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00003113 case BO_XorAssign:
3114 case BO_OrAssign:
3115 // TODO: bitfields?
John McCall817d4af2010-11-10 23:38:19 +00003116 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00003117
John McCallc3688382011-07-13 06:35:24 +00003118 // Simple assignments just pass through the RHS, which will have
3119 // been coerced to the LHS type.
3120 case BO_Assign:
3121 // TODO: bitfields?
3122 return GetExprRange(C, BO->getRHS(), MaxWidth);
3123
John McCall70aa5392010-01-06 05:24:50 +00003124 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003125 case BO_PtrMemD:
3126 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00003127 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003128
John McCall2ce81ad2010-01-06 22:07:33 +00003129 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00003130 case BO_And:
3131 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00003132 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3133 GetExprRange(C, BO->getRHS(), MaxWidth));
3134
John McCall70aa5392010-01-06 05:24:50 +00003135 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00003136 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00003137 // ...except that we want to treat '1 << (blah)' as logically
3138 // positive. It's an important idiom.
3139 if (IntegerLiteral *I
3140 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3141 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00003142 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00003143 return IntRange(R.Width, /*NonNegative*/ true);
3144 }
3145 }
3146 // fallthrough
3147
John McCalle3027922010-08-25 11:45:40 +00003148 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00003149 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003150
John McCall2ce81ad2010-01-06 22:07:33 +00003151 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00003152 case BO_Shr:
3153 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00003154 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3155
3156 // If the shift amount is a positive constant, drop the width by
3157 // that much.
3158 llvm::APSInt shift;
3159 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3160 shift.isNonNegative()) {
3161 unsigned zext = shift.getZExtValue();
3162 if (zext >= L.Width)
3163 L.Width = (L.NonNegative ? 0 : 1);
3164 else
3165 L.Width -= zext;
3166 }
3167
3168 return L;
3169 }
3170
3171 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00003172 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00003173 return GetExprRange(C, BO->getRHS(), MaxWidth);
3174
John McCall2ce81ad2010-01-06 22:07:33 +00003175 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00003176 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00003177 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00003178 return IntRange::forValueOfType(C, E->getType());
John McCall51431812011-07-14 22:39:48 +00003179 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003180
John McCall51431812011-07-14 22:39:48 +00003181 // The width of a division result is mostly determined by the size
3182 // of the LHS.
3183 case BO_Div: {
3184 // Don't 'pre-truncate' the operands.
3185 unsigned opWidth = C.getIntWidth(E->getType());
3186 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3187
3188 // If the divisor is constant, use that.
3189 llvm::APSInt divisor;
3190 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3191 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3192 if (log2 >= L.Width)
3193 L.Width = (L.NonNegative ? 0 : 1);
3194 else
3195 L.Width = std::min(L.Width - log2, MaxWidth);
3196 return L;
3197 }
3198
3199 // Otherwise, just use the LHS's width.
3200 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3201 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3202 }
3203
3204 // The result of a remainder can't be larger than the result of
3205 // either side.
3206 case BO_Rem: {
3207 // Don't 'pre-truncate' the operands.
3208 unsigned opWidth = C.getIntWidth(E->getType());
3209 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3210 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3211
3212 IntRange meet = IntRange::meet(L, R);
3213 meet.Width = std::min(meet.Width, MaxWidth);
3214 return meet;
3215 }
3216
3217 // The default behavior is okay for these.
3218 case BO_Mul:
3219 case BO_Add:
3220 case BO_Xor:
3221 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00003222 break;
3223 }
3224
John McCall51431812011-07-14 22:39:48 +00003225 // The default case is to treat the operation as if it were closed
3226 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00003227 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3228 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3229 return IntRange::join(L, R);
3230 }
3231
3232 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3233 switch (UO->getOpcode()) {
3234 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00003235 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00003236 return IntRange::forBoolType();
3237
3238 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003239 case UO_Deref:
3240 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00003241 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003242
3243 default:
3244 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3245 }
3246 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003247
3248 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00003249 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00003250 }
John McCall70aa5392010-01-06 05:24:50 +00003251
Richard Smithcaf33902011-10-10 18:28:20 +00003252 if (FieldDecl *BitField = E->getBitField())
3253 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00003254 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00003255
John McCall817d4af2010-11-10 23:38:19 +00003256 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003257}
John McCall263a48b2010-01-04 23:31:57 +00003258
John McCallcc7e5bf2010-05-06 08:58:33 +00003259IntRange GetExprRange(ASTContext &C, Expr *E) {
3260 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3261}
3262
John McCall263a48b2010-01-04 23:31:57 +00003263/// Checks whether the given value, which currently has the given
3264/// source semantics, has the same value when coerced through the
3265/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00003266bool IsSameFloatAfterCast(const llvm::APFloat &value,
3267 const llvm::fltSemantics &Src,
3268 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003269 llvm::APFloat truncated = value;
3270
3271 bool ignored;
3272 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3273 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3274
3275 return truncated.bitwiseIsEqual(value);
3276}
3277
3278/// Checks whether the given value, which currently has the given
3279/// source semantics, has the same value when coerced through the
3280/// target semantics.
3281///
3282/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00003283bool IsSameFloatAfterCast(const APValue &value,
3284 const llvm::fltSemantics &Src,
3285 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003286 if (value.isFloat())
3287 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3288
3289 if (value.isVector()) {
3290 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3291 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3292 return false;
3293 return true;
3294 }
3295
3296 assert(value.isComplexFloat());
3297 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3298 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3299}
3300
John McCallacf0ee52010-10-08 02:01:28 +00003301void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003302
Ted Kremenek6274be42010-09-23 21:43:44 +00003303static bool IsZero(Sema &S, Expr *E) {
3304 // Suppress cases where we are comparing against an enum constant.
3305 if (const DeclRefExpr *DR =
3306 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3307 if (isa<EnumConstantDecl>(DR->getDecl()))
3308 return false;
3309
3310 // Suppress cases where the '0' value is expanded from a macro.
3311 if (E->getLocStart().isMacroID())
3312 return false;
3313
John McCallcc7e5bf2010-05-06 08:58:33 +00003314 llvm::APSInt Value;
3315 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3316}
3317
John McCall2551c1b2010-10-06 00:25:24 +00003318static bool HasEnumType(Expr *E) {
3319 // Strip off implicit integral promotions.
3320 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003321 if (ICE->getCastKind() != CK_IntegralCast &&
3322 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00003323 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003324 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00003325 }
3326
3327 return E->getType()->isEnumeralType();
3328}
3329
John McCallcc7e5bf2010-05-06 08:58:33 +00003330void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003331 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00003332 if (E->isValueDependent())
3333 return;
3334
John McCalle3027922010-08-25 11:45:40 +00003335 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003336 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003337 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003338 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003339 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003340 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003341 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003342 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003343 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003344 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003345 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003346 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003347 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003348 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003349 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003350 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3351 }
3352}
3353
3354/// Analyze the operands of the given comparison. Implements the
3355/// fallback case from AnalyzeComparison.
3356void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00003357 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3358 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00003359}
John McCall263a48b2010-01-04 23:31:57 +00003360
John McCallca01b222010-01-04 23:21:16 +00003361/// \brief Implements -Wsign-compare.
3362///
Richard Trieu82402a02011-09-15 21:56:47 +00003363/// \param E the binary operator to check for warnings
John McCallcc7e5bf2010-05-06 08:58:33 +00003364void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3365 // The type the comparison is being performed in.
3366 QualType T = E->getLHS()->getType();
3367 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3368 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00003369
John McCallcc7e5bf2010-05-06 08:58:33 +00003370 // We don't do anything special if this isn't an unsigned integral
3371 // comparison: we're only interested in integral comparisons, and
3372 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00003373 //
3374 // We also don't care about value-dependent expressions or expressions
3375 // whose result is a constant.
3376 if (!T->hasUnsignedIntegerRepresentation()
3377 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00003378 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00003379
Richard Trieu82402a02011-09-15 21:56:47 +00003380 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3381 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00003382
John McCallcc7e5bf2010-05-06 08:58:33 +00003383 // Check to see if one of the (unmodified) operands is of different
3384 // signedness.
3385 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00003386 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3387 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00003388 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00003389 signedOperand = LHS;
3390 unsignedOperand = RHS;
3391 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3392 signedOperand = RHS;
3393 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00003394 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00003395 CheckTrivialUnsignedComparison(S, E);
3396 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003397 }
3398
John McCallcc7e5bf2010-05-06 08:58:33 +00003399 // Otherwise, calculate the effective range of the signed operand.
3400 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00003401
John McCallcc7e5bf2010-05-06 08:58:33 +00003402 // Go ahead and analyze implicit conversions in the operands. Note
3403 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00003404 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3405 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00003406
John McCallcc7e5bf2010-05-06 08:58:33 +00003407 // If the signed range is non-negative, -Wsign-compare won't fire,
3408 // but we should still check for comparisons which are always true
3409 // or false.
3410 if (signedRange.NonNegative)
3411 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003412
3413 // For (in)equality comparisons, if the unsigned operand is a
3414 // constant which cannot collide with a overflowed signed operand,
3415 // then reinterpreting the signed operand as unsigned will not
3416 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00003417 if (E->isEqualityOp()) {
3418 unsigned comparisonWidth = S.Context.getIntWidth(T);
3419 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00003420
John McCallcc7e5bf2010-05-06 08:58:33 +00003421 // We should never be unable to prove that the unsigned operand is
3422 // non-negative.
3423 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3424
3425 if (unsignedRange.Width < comparisonWidth)
3426 return;
3427 }
3428
3429 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieu82402a02011-09-15 21:56:47 +00003430 << LHS->getType() << RHS->getType()
3431 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00003432}
3433
John McCall1f425642010-11-11 03:21:53 +00003434/// Analyzes an attempt to assign the given value to a bitfield.
3435///
3436/// Returns true if there was something fishy about the attempt.
3437bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3438 SourceLocation InitLoc) {
3439 assert(Bitfield->isBitField());
3440 if (Bitfield->isInvalidDecl())
3441 return false;
3442
John McCalldeebbcf2010-11-11 05:33:51 +00003443 // White-list bool bitfields.
3444 if (Bitfield->getType()->isBooleanType())
3445 return false;
3446
Douglas Gregor789adec2011-02-04 13:09:01 +00003447 // Ignore value- or type-dependent expressions.
3448 if (Bitfield->getBitWidth()->isValueDependent() ||
3449 Bitfield->getBitWidth()->isTypeDependent() ||
3450 Init->isValueDependent() ||
3451 Init->isTypeDependent())
3452 return false;
3453
John McCall1f425642010-11-11 03:21:53 +00003454 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3455
John McCall1f425642010-11-11 03:21:53 +00003456 Expr::EvalResult InitValue;
Richard Smith7b553f12011-10-29 00:50:52 +00003457 if (!OriginalInit->EvaluateAsRValue(InitValue, S.Context) ||
John McCall1f425642010-11-11 03:21:53 +00003458 !InitValue.Val.isInt())
3459 return false;
3460
3461 const llvm::APSInt &Value = InitValue.Val.getInt();
3462 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00003463 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00003464
3465 if (OriginalWidth <= FieldWidth)
3466 return false;
3467
Jay Foad6d4db0c2010-12-07 08:25:34 +00003468 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall1f425642010-11-11 03:21:53 +00003469
3470 // It's fairly common to write values into signed bitfields
3471 // that, if sign-extended, would end up becoming a different
3472 // value. We don't want to warn about that.
3473 if (Value.isSigned() && Value.isNegative())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003474 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003475 else
Jay Foad6d4db0c2010-12-07 08:25:34 +00003476 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003477
3478 if (Value == TruncatedValue)
3479 return false;
3480
3481 std::string PrettyValue = Value.toString(10);
3482 std::string PrettyTrunc = TruncatedValue.toString(10);
3483
3484 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3485 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3486 << Init->getSourceRange();
3487
3488 return true;
3489}
3490
John McCalld2a53122010-11-09 23:24:47 +00003491/// Analyze the given simple or compound assignment for warning-worthy
3492/// operations.
3493void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3494 // Just recurse on the LHS.
3495 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3496
3497 // We want to recurse on the RHS as normal unless we're assigning to
3498 // a bitfield.
3499 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00003500 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3501 E->getOperatorLoc())) {
3502 // Recurse, ignoring any implicit conversions on the RHS.
3503 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3504 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00003505 }
3506 }
3507
3508 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3509}
3510
John McCall263a48b2010-01-04 23:31:57 +00003511/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003512void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3513 SourceLocation CContext, unsigned diag) {
3514 S.Diag(E->getExprLoc(), diag)
3515 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3516}
3517
Chandler Carruth7f3654f2011-04-05 06:47:57 +00003518/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3519void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3520 unsigned diag) {
3521 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3522}
3523
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003524/// Diagnose an implicit cast from a literal expression. Does not warn when the
3525/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00003526void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3527 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003528 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00003529 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003530 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00003531 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3532 T->hasUnsignedIntegerRepresentation());
3533 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00003534 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003535 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00003536 return;
3537
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003538 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3539 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00003540}
3541
John McCall18a2c2c2010-11-09 22:22:12 +00003542std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3543 if (!Range.Width) return "0";
3544
3545 llvm::APSInt ValueInRange = Value;
3546 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00003547 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00003548 return ValueInRange.toString(10);
3549}
3550
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003551static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3552 SourceManager &smgr = S.Context.getSourceManager();
3553 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3554}
Chandler Carruth016ef402011-04-10 08:36:24 +00003555
John McCallcc7e5bf2010-05-06 08:58:33 +00003556void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003557 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003558 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00003559
John McCallcc7e5bf2010-05-06 08:58:33 +00003560 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3561 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3562 if (Source == Target) return;
3563 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00003564
Chandler Carruthc22845a2011-07-26 05:40:03 +00003565 // If the conversion context location is invalid don't complain. We also
3566 // don't want to emit a warning if the issue occurs from the expansion of
3567 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3568 // delay this check as long as possible. Once we detect we are in that
3569 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003570 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00003571 return;
3572
Richard Trieu021baa32011-09-23 20:10:00 +00003573 // Diagnose implicit casts to bool.
3574 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3575 if (isa<StringLiteral>(E))
3576 // Warn on string literal to bool. Checks for string literals in logical
3577 // expressions, for instances, assert(0 && "error here"), is prevented
3578 // by a check in AnalyzeImplicitConversions().
3579 return DiagnoseImpCast(S, E, T, CC,
3580 diag::warn_impcast_string_literal_to_bool);
David Blaikie7833b7d2011-09-29 04:06:47 +00003581 return; // Other casts to bool are not checked.
Richard Trieu021baa32011-09-23 20:10:00 +00003582 }
John McCall263a48b2010-01-04 23:31:57 +00003583
3584 // Strip vector types.
3585 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003586 if (!isa<VectorType>(Target)) {
3587 if (isFromSystemMacro(S, CC))
3588 return;
John McCallacf0ee52010-10-08 02:01:28 +00003589 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003590 }
Chris Lattneree7286f2011-06-14 04:51:15 +00003591
3592 // If the vector cast is cast between two vectors of the same size, it is
3593 // a bitcast, not a conversion.
3594 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3595 return;
John McCall263a48b2010-01-04 23:31:57 +00003596
3597 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3598 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3599 }
3600
3601 // Strip complex types.
3602 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003603 if (!isa<ComplexType>(Target)) {
3604 if (isFromSystemMacro(S, CC))
3605 return;
3606
John McCallacf0ee52010-10-08 02:01:28 +00003607 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003608 }
John McCall263a48b2010-01-04 23:31:57 +00003609
3610 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3611 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3612 }
3613
3614 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3615 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3616
3617 // If the source is floating point...
3618 if (SourceBT && SourceBT->isFloatingPoint()) {
3619 // ...and the target is floating point...
3620 if (TargetBT && TargetBT->isFloatingPoint()) {
3621 // ...then warn if we're dropping FP rank.
3622
3623 // Builtin FP kinds are ordered by increasing FP rank.
3624 if (SourceBT->getKind() > TargetBT->getKind()) {
3625 // Don't warn about float constants that are precisely
3626 // representable in the target type.
3627 Expr::EvalResult result;
Richard Smith7b553f12011-10-29 00:50:52 +00003628 if (E->EvaluateAsRValue(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00003629 // Value might be a float, a float vector, or a float complex.
3630 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00003631 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3632 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00003633 return;
3634 }
3635
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003636 if (isFromSystemMacro(S, CC))
3637 return;
3638
John McCallacf0ee52010-10-08 02:01:28 +00003639 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00003640 }
3641 return;
3642 }
3643
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003644 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00003645 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003646 if (isFromSystemMacro(S, CC))
3647 return;
3648
Chandler Carruth22c7a792011-02-17 11:05:49 +00003649 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00003650 // We also want to warn on, e.g., "int i = -1.234"
3651 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3652 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3653 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3654
Chandler Carruth016ef402011-04-10 08:36:24 +00003655 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3656 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00003657 } else {
3658 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3659 }
3660 }
John McCall263a48b2010-01-04 23:31:57 +00003661
3662 return;
3663 }
3664
John McCall70aa5392010-01-06 05:24:50 +00003665 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00003666 return;
3667
Richard Trieubeaf3452011-05-29 19:59:02 +00003668 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3669 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3670 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3671 << E->getSourceRange() << clang::SourceRange(CC);
3672 return;
3673 }
3674
John McCallcc7e5bf2010-05-06 08:58:33 +00003675 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00003676 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00003677
3678 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00003679 // If the source is a constant, use a default-on diagnostic.
3680 // TODO: this should happen for bitfield stores, too.
3681 llvm::APSInt Value(32);
3682 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003683 if (isFromSystemMacro(S, CC))
3684 return;
3685
John McCall18a2c2c2010-11-09 22:22:12 +00003686 std::string PrettySourceValue = Value.toString(10);
3687 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3688
Ted Kremenek33ba9952011-10-22 02:37:33 +00003689 S.DiagRuntimeBehavior(E->getExprLoc(), E,
3690 S.PDiag(diag::warn_impcast_integer_precision_constant)
3691 << PrettySourceValue << PrettyTargetValue
3692 << E->getType() << T << E->getSourceRange()
3693 << clang::SourceRange(CC));
John McCall18a2c2c2010-11-09 22:22:12 +00003694 return;
3695 }
3696
Chris Lattneree7286f2011-06-14 04:51:15 +00003697 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003698 if (isFromSystemMacro(S, CC))
3699 return;
3700
John McCall70aa5392010-01-06 05:24:50 +00003701 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00003702 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3703 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00003704 }
3705
3706 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3707 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3708 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003709
3710 if (isFromSystemMacro(S, CC))
3711 return;
3712
John McCallcc7e5bf2010-05-06 08:58:33 +00003713 unsigned DiagID = diag::warn_impcast_integer_sign;
3714
3715 // Traditionally, gcc has warned about this under -Wsign-compare.
3716 // We also want to warn about it in -Wconversion.
3717 // So if -Wconversion is off, use a completely identical diagnostic
3718 // in the sign-compare group.
3719 // The conditional-checking code will
3720 if (ICContext) {
3721 DiagID = diag::warn_impcast_integer_sign_conditional;
3722 *ICContext = true;
3723 }
3724
John McCallacf0ee52010-10-08 02:01:28 +00003725 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00003726 }
3727
Douglas Gregora78f1932011-02-22 02:45:07 +00003728 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003729 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3730 // type, to give us better diagnostics.
3731 QualType SourceType = E->getType();
3732 if (!S.getLangOptions().CPlusPlus) {
3733 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3734 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3735 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3736 SourceType = S.Context.getTypeDeclType(Enum);
3737 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3738 }
3739 }
3740
Douglas Gregora78f1932011-02-22 02:45:07 +00003741 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3742 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3743 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003744 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregora78f1932011-02-22 02:45:07 +00003745 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003746 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003747 SourceEnum != TargetEnum) {
3748 if (isFromSystemMacro(S, CC))
3749 return;
3750
Douglas Gregor364f7db2011-03-12 00:14:31 +00003751 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00003752 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003753 }
Douglas Gregora78f1932011-02-22 02:45:07 +00003754
John McCall263a48b2010-01-04 23:31:57 +00003755 return;
3756}
3757
John McCallcc7e5bf2010-05-06 08:58:33 +00003758void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3759
3760void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003761 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003762 E = E->IgnoreParenImpCasts();
3763
3764 if (isa<ConditionalOperator>(E))
3765 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3766
John McCallacf0ee52010-10-08 02:01:28 +00003767 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003768 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003769 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00003770 return;
3771}
3772
3773void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00003774 SourceLocation CC = E->getQuestionLoc();
3775
3776 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003777
3778 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00003779 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3780 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003781
3782 // If -Wconversion would have warned about either of the candidates
3783 // for a signedness conversion to the context type...
3784 if (!Suspicious) return;
3785
3786 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003787 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3788 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00003789 return;
3790
John McCallcc7e5bf2010-05-06 08:58:33 +00003791 // ...then check whether it would have warned about either of the
3792 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00003793 if (E->getType() == T) return;
3794
3795 Suspicious = false;
3796 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3797 E->getType(), CC, &Suspicious);
3798 if (!Suspicious)
3799 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00003800 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003801}
3802
3803/// AnalyzeImplicitConversions - Find and report any interesting
3804/// implicit conversions in the given expression. There are a couple
3805/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003806void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003807 QualType T = OrigE->getType();
3808 Expr *E = OrigE->IgnoreParenImpCasts();
3809
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00003810 if (E->isTypeDependent() || E->isValueDependent())
3811 return;
3812
John McCallcc7e5bf2010-05-06 08:58:33 +00003813 // For conditional operators, we analyze the arguments as if they
3814 // were being fed directly into the output.
3815 if (isa<ConditionalOperator>(E)) {
3816 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3817 CheckConditionalOperator(S, CO, T);
3818 return;
3819 }
3820
3821 // Go ahead and check any implicit conversions we might have skipped.
3822 // The non-canonical typecheck is just an optimization;
3823 // CheckImplicitConversion will filter out dead implicit conversions.
3824 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003825 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003826
3827 // Now continue drilling into this expression.
3828
3829 // Skip past explicit casts.
3830 if (isa<ExplicitCastExpr>(E)) {
3831 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00003832 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003833 }
3834
John McCalld2a53122010-11-09 23:24:47 +00003835 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3836 // Do a somewhat different check with comparison operators.
3837 if (BO->isComparisonOp())
3838 return AnalyzeComparison(S, BO);
3839
3840 // And with assignments and compound assignments.
3841 if (BO->isAssignmentOp())
3842 return AnalyzeAssignment(S, BO);
3843 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003844
3845 // These break the otherwise-useful invariant below. Fortunately,
3846 // we don't really need to recurse into them, because any internal
3847 // expressions should have been analyzed already when they were
3848 // built into statements.
3849 if (isa<StmtExpr>(E)) return;
3850
3851 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003852 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00003853
3854 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00003855 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00003856 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3857 bool IsLogicalOperator = BO && BO->isLogicalOp();
3858 for (Stmt::child_range I = E->children(); I; ++I) {
3859 Expr *ChildExpr = cast<Expr>(*I);
3860 if (IsLogicalOperator &&
3861 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3862 // Ignore checking string literals that are in logical operators.
3863 continue;
3864 AnalyzeImplicitConversions(S, ChildExpr, CC);
3865 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003866}
3867
3868} // end anonymous namespace
3869
3870/// Diagnoses "dangerous" implicit conversions within the given
3871/// expression (which is a full expression). Implements -Wconversion
3872/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003873///
3874/// \param CC the "context" location of the implicit conversion, i.e.
3875/// the most location of the syntactic entity requiring the implicit
3876/// conversion
3877void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003878 // Don't diagnose in unevaluated contexts.
3879 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3880 return;
3881
3882 // Don't diagnose for value- or type-dependent expressions.
3883 if (E->isTypeDependent() || E->isValueDependent())
3884 return;
3885
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003886 // Check for array bounds violations in cases where the check isn't triggered
3887 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3888 // ArraySubscriptExpr is on the RHS of a variable initialization.
3889 CheckArrayAccess(E);
3890
John McCallacf0ee52010-10-08 02:01:28 +00003891 // This is not the right CC for (e.g.) a variable initialization.
3892 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003893}
3894
John McCall1f425642010-11-11 03:21:53 +00003895void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3896 FieldDecl *BitField,
3897 Expr *Init) {
3898 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3899}
3900
Mike Stump0c2ec772010-01-21 03:59:47 +00003901/// CheckParmsForFunctionDef - Check that the parameters of the given
3902/// function are appropriate for the definition of a function. This
3903/// takes care of any checks that cannot be performed on the
3904/// declaration itself, e.g., that the types of each of the function
3905/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00003906bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3907 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00003908 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00003909 for (; P != PEnd; ++P) {
3910 ParmVarDecl *Param = *P;
3911
Mike Stump0c2ec772010-01-21 03:59:47 +00003912 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3913 // function declarator that is part of a function definition of
3914 // that function shall not have incomplete type.
3915 //
3916 // This is also C++ [dcl.fct]p6.
3917 if (!Param->isInvalidDecl() &&
3918 RequireCompleteType(Param->getLocation(), Param->getType(),
3919 diag::err_typecheck_decl_incomplete_type)) {
3920 Param->setInvalidDecl();
3921 HasInvalidParm = true;
3922 }
3923
3924 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3925 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00003926 if (CheckParameterNames &&
3927 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00003928 !Param->isImplicit() &&
3929 !getLangOptions().CPlusPlus)
3930 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00003931
3932 // C99 6.7.5.3p12:
3933 // If the function declarator is not part of a definition of that
3934 // function, parameters may have incomplete type and may use the [*]
3935 // notation in their sequences of declarator specifiers to specify
3936 // variable length array types.
3937 QualType PType = Param->getOriginalType();
3938 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3939 if (AT->getSizeModifier() == ArrayType::Star) {
3940 // FIXME: This diagnosic should point the the '[*]' if source-location
3941 // information is added for it.
3942 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3943 }
3944 }
Mike Stump0c2ec772010-01-21 03:59:47 +00003945 }
3946
3947 return HasInvalidParm;
3948}
John McCall2b5c1b22010-08-12 21:44:57 +00003949
3950/// CheckCastAlign - Implements -Wcast-align, which warns when a
3951/// pointer cast increases the alignment requirements.
3952void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3953 // This is actually a lot of work to potentially be doing on every
3954 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003955 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3956 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00003957 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00003958 return;
3959
3960 // Ignore dependent types.
3961 if (T->isDependentType() || Op->getType()->isDependentType())
3962 return;
3963
3964 // Require that the destination be a pointer type.
3965 const PointerType *DestPtr = T->getAs<PointerType>();
3966 if (!DestPtr) return;
3967
3968 // If the destination has alignment 1, we're done.
3969 QualType DestPointee = DestPtr->getPointeeType();
3970 if (DestPointee->isIncompleteType()) return;
3971 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3972 if (DestAlign.isOne()) return;
3973
3974 // Require that the source be a pointer type.
3975 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3976 if (!SrcPtr) return;
3977 QualType SrcPointee = SrcPtr->getPointeeType();
3978
3979 // Whitelist casts from cv void*. We already implicitly
3980 // whitelisted casts to cv void*, since they have alignment 1.
3981 // Also whitelist casts involving incomplete types, which implicitly
3982 // includes 'void'.
3983 if (SrcPointee->isIncompleteType()) return;
3984
3985 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3986 if (SrcAlign >= DestAlign) return;
3987
3988 Diag(TRange.getBegin(), diag::warn_cast_align)
3989 << Op->getType() << T
3990 << static_cast<unsigned>(SrcAlign.getQuantity())
3991 << static_cast<unsigned>(DestAlign.getQuantity())
3992 << TRange << Op->getSourceRange();
3993}
3994
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003995static const Type* getElementType(const Expr *BaseExpr) {
3996 const Type* EltType = BaseExpr->getType().getTypePtr();
3997 if (EltType->isAnyPointerType())
3998 return EltType->getPointeeType().getTypePtr();
3999 else if (EltType->isArrayType())
4000 return EltType->getBaseElementTypeUnsafe();
4001 return EltType;
4002}
4003
Chandler Carruth28389f02011-08-05 09:10:50 +00004004/// \brief Check whether this array fits the idiom of a size-one tail padded
4005/// array member of a struct.
4006///
4007/// We avoid emitting out-of-bounds access warnings for such arrays as they are
4008/// commonly used to emulate flexible arrays in C89 code.
4009static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
4010 const NamedDecl *ND) {
4011 if (Size != 1 || !ND) return false;
4012
4013 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
4014 if (!FD) return false;
4015
4016 // Don't consider sizes resulting from macro expansions or template argument
4017 // substitution to form C89 tail-padded arrays.
4018 ConstantArrayTypeLoc TL =
4019 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
4020 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
4021 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
4022 return false;
4023
4024 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
4025 if (!RD || !RD->isStruct())
4026 return false;
4027
Benjamin Kramer8c543672011-08-06 03:04:42 +00004028 // See if this is the last field decl in the record.
4029 const Decl *D = FD;
4030 while ((D = D->getNextDeclInContext()))
4031 if (isa<FieldDecl>(D))
4032 return false;
4033 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00004034}
4035
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004036void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
4037 bool isSubscript, bool AllowOnePastEnd) {
4038 const Type* EffectiveType = getElementType(BaseExpr);
4039 BaseExpr = BaseExpr->IgnoreParenCasts();
4040 IndexExpr = IndexExpr->IgnoreParenCasts();
4041
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004042 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004043 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004044 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00004045 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00004046
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004047 if (IndexExpr->isValueDependent())
Ted Kremenek64699be2011-02-16 01:57:07 +00004048 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004049 llvm::APSInt index;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004050 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00004051 return;
Ted Kremenek108b2d52011-02-16 04:01:44 +00004052
Chandler Carruth126b1552011-08-05 08:07:29 +00004053 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00004054 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
4055 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00004056 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00004057 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00004058
Ted Kremeneke4b316c2011-02-23 23:06:04 +00004059 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004060 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00004061 if (!size.isStrictlyPositive())
4062 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004063
4064 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00004065 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004066 // Make sure we're comparing apples to apples when comparing index to size
4067 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
4068 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00004069 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00004070 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004071 if (ptrarith_typesize != array_typesize) {
4072 // There's a cast to a different size type involved
4073 uint64_t ratio = array_typesize / ptrarith_typesize;
4074 // TODO: Be smarter about handling cases where array_typesize is not a
4075 // multiple of ptrarith_typesize
4076 if (ptrarith_typesize * ratio == array_typesize)
4077 size *= llvm::APInt(size.getBitWidth(), ratio);
4078 }
4079 }
4080
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004081 if (size.getBitWidth() > index.getBitWidth())
4082 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00004083 else if (size.getBitWidth() < index.getBitWidth())
4084 size = size.sext(index.getBitWidth());
4085
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004086 // For array subscripting the index must be less than size, but for pointer
4087 // arithmetic also allow the index (offset) to be equal to size since
4088 // computing the next address after the end of the array is legal and
4089 // commonly done e.g. in C++ iterators and range-based for loops.
4090 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00004091 return;
4092
4093 // Also don't warn for arrays of size 1 which are members of some
4094 // structure. These are often used to approximate flexible arrays in C89
4095 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004096 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00004097 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004098
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004099 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4100 if (isSubscript)
4101 DiagID = diag::warn_array_index_exceeds_bounds;
4102
4103 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4104 PDiag(DiagID) << index.toString(10, true)
4105 << size.toString(10, true)
4106 << (unsigned)size.getLimitedValue(~0U)
4107 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004108 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004109 unsigned DiagID = diag::warn_array_index_precedes_bounds;
4110 if (!isSubscript) {
4111 DiagID = diag::warn_ptr_arith_precedes_bounds;
4112 if (index.isNegative()) index = -index;
4113 }
4114
4115 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4116 PDiag(DiagID) << index.toString(10, true)
4117 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00004118 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00004119
Chandler Carruth1af88f12011-02-17 21:10:52 +00004120 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004121 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4122 PDiag(diag::note_array_index_out_of_bounds)
4123 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00004124}
4125
Ted Kremenekdf26df72011-03-01 18:41:00 +00004126void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004127 int AllowOnePastEnd = 0;
4128 while (expr) {
4129 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00004130 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004131 case Stmt::ArraySubscriptExprClass: {
4132 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4133 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4134 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00004135 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004136 }
4137 case Stmt::UnaryOperatorClass: {
4138 // Only unwrap the * and & unary operators
4139 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4140 expr = UO->getSubExpr();
4141 switch (UO->getOpcode()) {
4142 case UO_AddrOf:
4143 AllowOnePastEnd++;
4144 break;
4145 case UO_Deref:
4146 AllowOnePastEnd--;
4147 break;
4148 default:
4149 return;
4150 }
4151 break;
4152 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004153 case Stmt::ConditionalOperatorClass: {
4154 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4155 if (const Expr *lhs = cond->getLHS())
4156 CheckArrayAccess(lhs);
4157 if (const Expr *rhs = cond->getRHS())
4158 CheckArrayAccess(rhs);
4159 return;
4160 }
4161 default:
4162 return;
4163 }
Peter Collingbourne91147592011-04-15 00:35:48 +00004164 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004165}
John McCall31168b02011-06-15 23:02:42 +00004166
4167//===--- CHECK: Objective-C retain cycles ----------------------------------//
4168
4169namespace {
4170 struct RetainCycleOwner {
4171 RetainCycleOwner() : Variable(0), Indirect(false) {}
4172 VarDecl *Variable;
4173 SourceRange Range;
4174 SourceLocation Loc;
4175 bool Indirect;
4176
4177 void setLocsFrom(Expr *e) {
4178 Loc = e->getExprLoc();
4179 Range = e->getSourceRange();
4180 }
4181 };
4182}
4183
4184/// Consider whether capturing the given variable can possibly lead to
4185/// a retain cycle.
4186static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4187 // In ARC, it's captured strongly iff the variable has __strong
4188 // lifetime. In MRR, it's captured strongly if the variable is
4189 // __block and has an appropriate type.
4190 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4191 return false;
4192
4193 owner.Variable = var;
4194 owner.setLocsFrom(ref);
4195 return true;
4196}
4197
4198static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4199 while (true) {
4200 e = e->IgnoreParens();
4201 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4202 switch (cast->getCastKind()) {
4203 case CK_BitCast:
4204 case CK_LValueBitCast:
4205 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00004206 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00004207 e = cast->getSubExpr();
4208 continue;
4209
John McCall31168b02011-06-15 23:02:42 +00004210 default:
4211 return false;
4212 }
4213 }
4214
4215 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4216 ObjCIvarDecl *ivar = ref->getDecl();
4217 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4218 return false;
4219
4220 // Try to find a retain cycle in the base.
4221 if (!findRetainCycleOwner(ref->getBase(), owner))
4222 return false;
4223
4224 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4225 owner.Indirect = true;
4226 return true;
4227 }
4228
4229 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4230 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4231 if (!var) return false;
4232 return considerVariable(var, ref, owner);
4233 }
4234
4235 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4236 owner.Variable = ref->getDecl();
4237 owner.setLocsFrom(ref);
4238 return true;
4239 }
4240
4241 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4242 if (member->isArrow()) return false;
4243
4244 // Don't count this as an indirect ownership.
4245 e = member->getBase();
4246 continue;
4247 }
4248
John McCallfe96e0b2011-11-06 09:01:30 +00004249 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
4250 // Only pay attention to pseudo-objects on property references.
4251 ObjCPropertyRefExpr *pre
4252 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
4253 ->IgnoreParens());
4254 if (!pre) return false;
4255 if (pre->isImplicitProperty()) return false;
4256 ObjCPropertyDecl *property = pre->getExplicitProperty();
4257 if (!property->isRetaining() &&
4258 !(property->getPropertyIvarDecl() &&
4259 property->getPropertyIvarDecl()->getType()
4260 .getObjCLifetime() == Qualifiers::OCL_Strong))
4261 return false;
4262
4263 owner.Indirect = true;
4264 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
4265 ->getSourceExpr());
4266 continue;
4267 }
4268
John McCall31168b02011-06-15 23:02:42 +00004269 // Array ivars?
4270
4271 return false;
4272 }
4273}
4274
4275namespace {
4276 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4277 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4278 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4279 Variable(variable), Capturer(0) {}
4280
4281 VarDecl *Variable;
4282 Expr *Capturer;
4283
4284 void VisitDeclRefExpr(DeclRefExpr *ref) {
4285 if (ref->getDecl() == Variable && !Capturer)
4286 Capturer = ref;
4287 }
4288
4289 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4290 if (ref->getDecl() == Variable && !Capturer)
4291 Capturer = ref;
4292 }
4293
4294 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4295 if (Capturer) return;
4296 Visit(ref->getBase());
4297 if (Capturer && ref->isFreeIvar())
4298 Capturer = ref;
4299 }
4300
4301 void VisitBlockExpr(BlockExpr *block) {
4302 // Look inside nested blocks
4303 if (block->getBlockDecl()->capturesVariable(Variable))
4304 Visit(block->getBlockDecl()->getBody());
4305 }
4306 };
4307}
4308
4309/// Check whether the given argument is a block which captures a
4310/// variable.
4311static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4312 assert(owner.Variable && owner.Loc.isValid());
4313
4314 e = e->IgnoreParenCasts();
4315 BlockExpr *block = dyn_cast<BlockExpr>(e);
4316 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4317 return 0;
4318
4319 FindCaptureVisitor visitor(S.Context, owner.Variable);
4320 visitor.Visit(block->getBlockDecl()->getBody());
4321 return visitor.Capturer;
4322}
4323
4324static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4325 RetainCycleOwner &owner) {
4326 assert(capturer);
4327 assert(owner.Variable && owner.Loc.isValid());
4328
4329 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4330 << owner.Variable << capturer->getSourceRange();
4331 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4332 << owner.Indirect << owner.Range;
4333}
4334
4335/// Check for a keyword selector that starts with the word 'add' or
4336/// 'set'.
4337static bool isSetterLikeSelector(Selector sel) {
4338 if (sel.isUnarySelector()) return false;
4339
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004340 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00004341 while (!str.empty() && str.front() == '_') str = str.substr(1);
4342 if (str.startswith("set") || str.startswith("add"))
4343 str = str.substr(3);
4344 else
4345 return false;
4346
4347 if (str.empty()) return true;
4348 return !islower(str.front());
4349}
4350
4351/// Check a message send to see if it's likely to cause a retain cycle.
4352void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4353 // Only check instance methods whose selector looks like a setter.
4354 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4355 return;
4356
4357 // Try to find a variable that the receiver is strongly owned by.
4358 RetainCycleOwner owner;
4359 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4360 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4361 return;
4362 } else {
4363 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4364 owner.Variable = getCurMethodDecl()->getSelfDecl();
4365 owner.Loc = msg->getSuperLoc();
4366 owner.Range = msg->getSuperLoc();
4367 }
4368
4369 // Check whether the receiver is captured by any of the arguments.
4370 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4371 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4372 return diagnoseRetainCycle(*this, capturer, owner);
4373}
4374
4375/// Check a property assign to see if it's likely to cause a retain cycle.
4376void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4377 RetainCycleOwner owner;
4378 if (!findRetainCycleOwner(receiver, owner))
4379 return;
4380
4381 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4382 diagnoseRetainCycle(*this, capturer, owner);
4383}
4384
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004385bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCall31168b02011-06-15 23:02:42 +00004386 QualType LHS, Expr *RHS) {
4387 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4388 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004389 return false;
4390 // strip off any implicit cast added to get to the one arc-specific
4391 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004392 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCall31168b02011-06-15 23:02:42 +00004393 Diag(Loc, diag::warn_arc_retained_assign)
4394 << (LT == Qualifiers::OCL_ExplicitNone)
4395 << RHS->getSourceRange();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004396 return true;
4397 }
4398 RHS = cast->getSubExpr();
4399 }
4400 return false;
John McCall31168b02011-06-15 23:02:42 +00004401}
4402
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004403void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4404 Expr *LHS, Expr *RHS) {
4405 QualType LHSType = LHS->getType();
4406 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4407 return;
4408 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4409 // FIXME. Check for other life times.
4410 if (LT != Qualifiers::OCL_None)
4411 return;
4412
John McCall526ab472011-10-25 17:37:35 +00004413 if (ObjCPropertyRefExpr *PRE
4414 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens())) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004415 if (PRE->isImplicitProperty())
4416 return;
4417 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4418 if (!PD)
4419 return;
4420
4421 unsigned Attributes = PD->getPropertyAttributes();
4422 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4423 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004424 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004425 Diag(Loc, diag::warn_arc_retained_property_assign)
4426 << RHS->getSourceRange();
4427 return;
4428 }
4429 RHS = cast->getSubExpr();
4430 }
4431 }
4432}