blob: 329adf89e8ad88ad13228e1dad9bfb98a5f44a45 [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) {
248 bool quad = t & 0x10;
249
250 switch (t & 0x7) {
251 case 0: // i8
Nate Begemandbafec12010-06-17 02:26:59 +0000252 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000253 case 1: // i16
Nate Begemandbafec12010-06-17 02:26:59 +0000254 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000255 case 2: // i32
Nate Begemandbafec12010-06-17 02:26:59 +0000256 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000257 case 3: // i64
Nate Begemandbafec12010-06-17 02:26:59 +0000258 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000259 case 4: // f32
260 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000261 return (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000262 case 5: // poly8
Bob Wilsona880fa02010-12-10 19:45:06 +0000263 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000264 case 6: // poly16
Bob Wilsona880fa02010-12-10 19:45:06 +0000265 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000266 case 7: // float16
267 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000268 return (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000269 }
270 return 0;
271}
272
Nate Begeman4904e322010-06-08 02:47:44 +0000273bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000274 llvm::APSInt Result;
275
Nate Begemand773fe62010-06-13 04:47:52 +0000276 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000277 unsigned TV = 0;
Nate Begeman55483092010-06-09 01:10:23 +0000278 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000279#define GET_NEON_OVERLOAD_CHECK
280#include "clang/Basic/arm_neon.inc"
281#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000282 }
283
Nate Begemand773fe62010-06-13 04:47:52 +0000284 // For NEON intrinsics which are overloaded on vector element type, validate
285 // the immediate which specifies which variant to emit.
286 if (mask) {
287 unsigned ArgNo = TheCall->getNumArgs()-1;
288 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
289 return true;
290
Nate Begeman91e1fea2010-06-14 05:21:25 +0000291 TV = Result.getLimitedValue(32);
292 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000293 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
294 << TheCall->getArg(ArgNo)->getSourceRange();
295 }
Nate Begeman55483092010-06-09 01:10:23 +0000296
Nate Begemand773fe62010-06-13 04:47:52 +0000297 // For NEON intrinsics which take an immediate value as part of the
298 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000299 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000300 switch (BuiltinID) {
301 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000302 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
303 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000304 case ARM::BI__builtin_arm_vcvtr_f:
305 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000306#define GET_NEON_IMMEDIATE_CHECK
307#include "clang/Basic/arm_neon.inc"
308#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000309 };
310
Nate Begeman91e1fea2010-06-14 05:21:25 +0000311 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000312 if (SemaBuiltinConstantArg(TheCall, i, Result))
313 return true;
314
Nate Begeman91e1fea2010-06-14 05:21:25 +0000315 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000316 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000317 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000318 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000319 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000320
Nate Begemanf568b072010-08-03 21:32:34 +0000321 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000322 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000323}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000324
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000325/// CheckFunctionCall - Check a direct function call for various correctness
326/// and safety properties not strictly enforced by the C type system.
327bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
328 // Get the IdentifierInfo* for the called function.
329 IdentifierInfo *FnInfo = FDecl->getIdentifier();
330
331 // None of the checks below are needed for functions that don't have
332 // simple names (e.g., C++ conversion functions).
333 if (!FnInfo)
334 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000335
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000336 // FIXME: This mechanism should be abstracted to be less fragile and
337 // more efficient. For example, just map function ids to custom
338 // handlers.
339
Ted Kremenekb8176da2010-09-09 04:33:05 +0000340 // Printf and scanf checking.
341 for (specific_attr_iterator<FormatAttr>
342 i = FDecl->specific_attr_begin<FormatAttr>(),
343 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
344
345 const FormatAttr *Format = *i;
Ted Kremenek02087932010-07-16 02:11:22 +0000346 const bool b = Format->getType() == "scanf";
347 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000348 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000349 CheckPrintfScanfArguments(TheCall, HasVAListArg,
350 Format->getFormatIdx() - 1,
351 HasVAListArg ? 0 : Format->getFirstArg() - 1,
352 !b);
Douglas Gregore711f702009-02-14 18:57:46 +0000353 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Ted Kremenekb8176da2010-09-09 04:33:05 +0000356 for (specific_attr_iterator<NonNullAttr>
357 i = FDecl->specific_attr_begin<NonNullAttr>(),
358 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +0000359 CheckNonNullArguments(*i, TheCall->getArgs(),
360 TheCall->getCallee()->getLocStart());
Ted Kremenekb8176da2010-09-09 04:33:05 +0000361 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000362
Peter Collingbourne5aa6ecb2011-10-16 21:17:32 +0000363 CheckStaticArrayArguments(FDecl, TheCall->getArgs(),
364 TheCall->getCallee()->getLocStart());
365
Ted Kremenek6865f772011-08-18 20:55:45 +0000366 // Builtin handling
Douglas Gregor18739c32011-06-16 17:56:04 +0000367 int CMF = -1;
368 switch (FDecl->getBuiltinID()) {
369 case Builtin::BI__builtin_memset:
370 case Builtin::BI__builtin___memset_chk:
371 case Builtin::BImemset:
372 CMF = CMF_Memset;
373 break;
374
375 case Builtin::BI__builtin_memcpy:
376 case Builtin::BI__builtin___memcpy_chk:
377 case Builtin::BImemcpy:
378 CMF = CMF_Memcpy;
379 break;
380
381 case Builtin::BI__builtin_memmove:
382 case Builtin::BI__builtin___memmove_chk:
383 case Builtin::BImemmove:
384 CMF = CMF_Memmove;
385 break;
Ted Kremenek6865f772011-08-18 20:55:45 +0000386
387 case Builtin::BIstrlcpy:
388 case Builtin::BIstrlcat:
389 CheckStrlcpycatArguments(TheCall, FnInfo);
390 break;
Douglas Gregor18739c32011-06-16 17:56:04 +0000391
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000392 case Builtin::BI__builtin_memcmp:
393 CMF = CMF_Memcmp;
394 break;
395
Nico Weber39bfed82011-10-13 22:30:23 +0000396 case Builtin::BI__builtin_strncpy:
397 case Builtin::BI__builtin___strncpy_chk:
398 case Builtin::BIstrncpy:
399 CMF = CMF_Strncpy;
400 break;
401
402 case Builtin::BI__builtin_strncmp:
403 CMF = CMF_Strncmp;
404 break;
405
406 case Builtin::BI__builtin_strncasecmp:
407 CMF = CMF_Strncasecmp;
408 break;
409
410 case Builtin::BI__builtin_strncat:
411 case Builtin::BIstrncat:
412 CMF = CMF_Strncat;
413 break;
414
415 case Builtin::BI__builtin_strndup:
416 case Builtin::BIstrndup:
417 CMF = CMF_Strndup;
418 break;
419
Douglas Gregor18739c32011-06-16 17:56:04 +0000420 default:
421 if (FDecl->getLinkage() == ExternalLinkage &&
422 (!getLangOptions().CPlusPlus || FDecl->isExternC())) {
423 if (FnInfo->isStr("memset"))
424 CMF = CMF_Memset;
425 else if (FnInfo->isStr("memcpy"))
426 CMF = CMF_Memcpy;
427 else if (FnInfo->isStr("memmove"))
428 CMF = CMF_Memmove;
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000429 else if (FnInfo->isStr("memcmp"))
430 CMF = CMF_Memcmp;
Nico Weber39bfed82011-10-13 22:30:23 +0000431 else if (FnInfo->isStr("strncpy"))
432 CMF = CMF_Strncpy;
433 else if (FnInfo->isStr("strncmp"))
434 CMF = CMF_Strncmp;
435 else if (FnInfo->isStr("strncasecmp"))
436 CMF = CMF_Strncasecmp;
437 else if (FnInfo->isStr("strncat"))
438 CMF = CMF_Strncat;
439 else if (FnInfo->isStr("strndup"))
440 CMF = CMF_Strndup;
Douglas Gregor18739c32011-06-16 17:56:04 +0000441 }
442 break;
Douglas Gregor3bb2a812011-05-03 20:37:33 +0000443 }
Douglas Gregor18739c32011-06-16 17:56:04 +0000444
Ted Kremenek6865f772011-08-18 20:55:45 +0000445 // Memset/memcpy/memmove handling
Douglas Gregor18739c32011-06-16 17:56:04 +0000446 if (CMF != -1)
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +0000447 CheckMemaccessArguments(TheCall, CheckedMemoryFunction(CMF), FnInfo);
Chandler Carruth53caa4d2011-04-27 07:05:31 +0000448
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000449 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000450}
451
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000452bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000453 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000454 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000455 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000456 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000457
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000458 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
459 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000460 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000461
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000462 QualType Ty = V->getType();
463 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000464 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000465
Ted Kremenek02087932010-07-16 02:11:22 +0000466 const bool b = Format->getType() == "scanf";
467 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000468 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000469
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000470 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000471 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
472 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000473
474 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000475}
476
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000477ExprResult
478Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op) {
479 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
480 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000481
482 // All these operations take one of the following four forms:
483 // T __atomic_load(_Atomic(T)*, int) (loads)
484 // T* __atomic_add(_Atomic(T*)*, ptrdiff_t, int) (pointer add/sub)
485 // int __atomic_compare_exchange_strong(_Atomic(T)*, T*, T, int, int)
486 // (cmpxchg)
487 // T __atomic_exchange(_Atomic(T)*, T, int) (everything else)
488 // where T is an appropriate type, and the int paremeterss are for orderings.
489 unsigned NumVals = 1;
490 unsigned NumOrders = 1;
491 if (Op == AtomicExpr::Load) {
492 NumVals = 0;
493 } else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong) {
494 NumVals = 2;
495 NumOrders = 2;
496 }
497
498 if (TheCall->getNumArgs() < NumVals+NumOrders+1) {
499 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
500 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
501 << TheCall->getCallee()->getSourceRange();
502 return ExprError();
503 } else if (TheCall->getNumArgs() > NumVals+NumOrders+1) {
504 Diag(TheCall->getArg(NumVals+NumOrders+1)->getLocStart(),
505 diag::err_typecheck_call_too_many_args)
506 << 0 << NumVals+NumOrders+1 << TheCall->getNumArgs()
507 << TheCall->getCallee()->getSourceRange();
508 return ExprError();
509 }
510
511 // Inspect the first argument of the atomic operation. This should always be
512 // a pointer to an _Atomic type.
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000513 Expr *Ptr = TheCall->getArg(0);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000514 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
515 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
516 if (!pointerType) {
517 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
518 << Ptr->getType() << Ptr->getSourceRange();
519 return ExprError();
520 }
521
522 QualType AtomTy = pointerType->getPointeeType();
523 if (!AtomTy->isAtomicType()) {
524 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
525 << Ptr->getType() << Ptr->getSourceRange();
526 return ExprError();
527 }
528 QualType ValType = AtomTy->getAs<AtomicType>()->getValueType();
529
530 if ((Op == AtomicExpr::Add || Op == AtomicExpr::Sub) &&
531 !ValType->isIntegerType() && !ValType->isPointerType()) {
532 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
533 << Ptr->getType() << Ptr->getSourceRange();
534 return ExprError();
535 }
536
537 if (!ValType->isIntegerType() &&
538 (Op == AtomicExpr::And || Op == AtomicExpr::Or || Op == AtomicExpr::Xor)){
539 Diag(DRE->getLocStart(), diag::err_atomic_op_logical_needs_atomic_int)
540 << Ptr->getType() << Ptr->getSourceRange();
541 return ExprError();
542 }
543
544 switch (ValType.getObjCLifetime()) {
545 case Qualifiers::OCL_None:
546 case Qualifiers::OCL_ExplicitNone:
547 // okay
548 break;
549
550 case Qualifiers::OCL_Weak:
551 case Qualifiers::OCL_Strong:
552 case Qualifiers::OCL_Autoreleasing:
553 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
554 << ValType << Ptr->getSourceRange();
555 return ExprError();
556 }
557
558 QualType ResultType = ValType;
559 if (Op == AtomicExpr::Store)
560 ResultType = Context.VoidTy;
561 else if (Op == AtomicExpr::CmpXchgWeak || Op == AtomicExpr::CmpXchgStrong)
562 ResultType = Context.BoolTy;
563
564 // The first argument --- the pointer --- has a fixed type; we
565 // deduce the types of the rest of the arguments accordingly. Walk
566 // the remaining arguments, converting them to the deduced value type.
567 for (unsigned i = 1; i != NumVals+NumOrders+1; ++i) {
568 ExprResult Arg = TheCall->getArg(i);
569 QualType Ty;
570 if (i < NumVals+1) {
571 // The second argument to a cmpxchg is a pointer to the data which will
572 // be exchanged. The second argument to a pointer add/subtract is the
573 // amount to add/subtract, which must be a ptrdiff_t. The third
574 // argument to a cmpxchg and the second argument in all other cases
575 // is the type of the value.
576 if (i == 1 && (Op == AtomicExpr::CmpXchgWeak ||
577 Op == AtomicExpr::CmpXchgStrong))
578 Ty = Context.getPointerType(ValType.getUnqualifiedType());
579 else if (!ValType->isIntegerType() &&
580 (Op == AtomicExpr::Add || Op == AtomicExpr::Sub))
581 Ty = Context.getPointerDiffType();
582 else
583 Ty = ValType;
584 } else {
585 // The order(s) are always converted to int.
586 Ty = Context.IntTy;
587 }
588 InitializedEntity Entity =
589 InitializedEntity::InitializeParameter(Context, Ty, false);
590 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
591 if (Arg.isInvalid())
592 return true;
593 TheCall->setArg(i, Arg.get());
594 }
595
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000596 SmallVector<Expr*, 5> SubExprs;
597 SubExprs.push_back(Ptr);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000598 if (Op == AtomicExpr::Load) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000599 SubExprs.push_back(TheCall->getArg(1)); // Order
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000600 } else if (Op != AtomicExpr::CmpXchgWeak && Op != AtomicExpr::CmpXchgStrong) {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000601 SubExprs.push_back(TheCall->getArg(2)); // Order
602 SubExprs.push_back(TheCall->getArg(1)); // Val1
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000603 } else {
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000604 SubExprs.push_back(TheCall->getArg(3)); // Order
605 SubExprs.push_back(TheCall->getArg(1)); // Val1
606 SubExprs.push_back(TheCall->getArg(2)); // Val2
607 SubExprs.push_back(TheCall->getArg(4)); // OrderFail
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000608 }
Eli Friedman8d3e43f2011-10-14 22:48:56 +0000609
610 return Owned(new (Context) AtomicExpr(TheCall->getCallee()->getLocStart(),
611 SubExprs.data(), SubExprs.size(),
612 ResultType, Op,
613 TheCall->getRParenLoc()));
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000614}
615
616
John McCall29ad95b2011-08-27 01:09:30 +0000617/// checkBuiltinArgument - Given a call to a builtin function, perform
618/// normal type-checking on the given argument, updating the call in
619/// place. This is useful when a builtin function requires custom
620/// type-checking for some of its arguments but not necessarily all of
621/// them.
622///
623/// Returns true on error.
624static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
625 FunctionDecl *Fn = E->getDirectCallee();
626 assert(Fn && "builtin call without direct callee!");
627
628 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
629 InitializedEntity Entity =
630 InitializedEntity::InitializeParameter(S.Context, Param);
631
632 ExprResult Arg = E->getArg(0);
633 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
634 if (Arg.isInvalid())
635 return true;
636
637 E->setArg(ArgIndex, Arg.take());
638 return false;
639}
640
Chris Lattnerdc046542009-05-08 06:58:22 +0000641/// SemaBuiltinAtomicOverloaded - We have a call to a function like
642/// __sync_fetch_and_add, which is an overloaded function based on the pointer
643/// type of its first argument. The main ActOnCallExpr routines have already
644/// promoted the types of arguments because all of these calls are prototyped as
645/// void(...).
646///
647/// This function goes through and does final semantic checking for these
648/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000649ExprResult
650Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000651 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000652 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
653 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
654
655 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000656 if (TheCall->getNumArgs() < 1) {
657 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
658 << 0 << 1 << TheCall->getNumArgs()
659 << TheCall->getCallee()->getSourceRange();
660 return ExprError();
661 }
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattnerdc046542009-05-08 06:58:22 +0000663 // Inspect the first argument of the atomic builtin. This should always be
664 // a pointer type, whose element is an integral scalar or pointer type.
665 // Because it is a pointer type, we don't have to worry about any implicit
666 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000667 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000668 Expr *FirstArg = TheCall->getArg(0);
John McCall31168b02011-06-15 23:02:42 +0000669 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
670 if (!pointerType) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000671 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
672 << FirstArg->getType() << FirstArg->getSourceRange();
673 return ExprError();
674 }
Mike Stump11289f42009-09-09 15:08:12 +0000675
John McCall31168b02011-06-15 23:02:42 +0000676 QualType ValType = pointerType->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000677 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000678 !ValType->isBlockPointerType()) {
679 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
680 << FirstArg->getType() << FirstArg->getSourceRange();
681 return ExprError();
682 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000683
John McCall31168b02011-06-15 23:02:42 +0000684 switch (ValType.getObjCLifetime()) {
685 case Qualifiers::OCL_None:
686 case Qualifiers::OCL_ExplicitNone:
687 // okay
688 break;
689
690 case Qualifiers::OCL_Weak:
691 case Qualifiers::OCL_Strong:
692 case Qualifiers::OCL_Autoreleasing:
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +0000693 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
John McCall31168b02011-06-15 23:02:42 +0000694 << ValType << FirstArg->getSourceRange();
695 return ExprError();
696 }
697
John McCallb50451a2011-10-05 07:41:44 +0000698 // Strip any qualifiers off ValType.
699 ValType = ValType.getUnqualifiedType();
700
Chandler Carruth3973af72010-07-18 20:54:12 +0000701 // The majority of builtins return a value, but a few have special return
702 // types, so allow them to override appropriately below.
703 QualType ResultType = ValType;
704
Chris Lattnerdc046542009-05-08 06:58:22 +0000705 // We need to figure out which concrete builtin this maps onto. For example,
706 // __sync_fetch_and_add with a 2 byte object turns into
707 // __sync_fetch_and_add_2.
708#define BUILTIN_ROW(x) \
709 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
710 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000711
Chris Lattnerdc046542009-05-08 06:58:22 +0000712 static const unsigned BuiltinIndices[][5] = {
713 BUILTIN_ROW(__sync_fetch_and_add),
714 BUILTIN_ROW(__sync_fetch_and_sub),
715 BUILTIN_ROW(__sync_fetch_and_or),
716 BUILTIN_ROW(__sync_fetch_and_and),
717 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000718
Chris Lattnerdc046542009-05-08 06:58:22 +0000719 BUILTIN_ROW(__sync_add_and_fetch),
720 BUILTIN_ROW(__sync_sub_and_fetch),
721 BUILTIN_ROW(__sync_and_and_fetch),
722 BUILTIN_ROW(__sync_or_and_fetch),
723 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000724
Chris Lattnerdc046542009-05-08 06:58:22 +0000725 BUILTIN_ROW(__sync_val_compare_and_swap),
726 BUILTIN_ROW(__sync_bool_compare_and_swap),
727 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000728 BUILTIN_ROW(__sync_lock_release),
729 BUILTIN_ROW(__sync_swap)
Chris Lattnerdc046542009-05-08 06:58:22 +0000730 };
Mike Stump11289f42009-09-09 15:08:12 +0000731#undef BUILTIN_ROW
732
Chris Lattnerdc046542009-05-08 06:58:22 +0000733 // Determine the index of the size.
734 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000735 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000736 case 1: SizeIndex = 0; break;
737 case 2: SizeIndex = 1; break;
738 case 4: SizeIndex = 2; break;
739 case 8: SizeIndex = 3; break;
740 case 16: SizeIndex = 4; break;
741 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000742 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
743 << FirstArg->getType() << FirstArg->getSourceRange();
744 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000745 }
Mike Stump11289f42009-09-09 15:08:12 +0000746
Chris Lattnerdc046542009-05-08 06:58:22 +0000747 // Each of these builtins has one pointer argument, followed by some number of
748 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
749 // that we ignore. Find out which row of BuiltinIndices to read from as well
750 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000751 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000752 unsigned BuiltinIndex, NumFixed = 1;
753 switch (BuiltinID) {
David Blaikie83d382b2011-09-23 05:06:16 +0000754 default: llvm_unreachable("Unknown overloaded atomic builtin!");
Chris Lattnerdc046542009-05-08 06:58:22 +0000755 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
756 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
757 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
758 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
759 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump11289f42009-09-09 15:08:12 +0000760
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000761 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
762 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
763 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
764 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
765 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump11289f42009-09-09 15:08:12 +0000766
Chris Lattnerdc046542009-05-08 06:58:22 +0000767 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000768 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000769 NumFixed = 2;
770 break;
771 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000772 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000773 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000774 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000775 break;
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000776 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000777 case Builtin::BI__sync_lock_release:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000778 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000779 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000780 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000781 break;
Chris Lattner9cb59fa2011-04-09 03:57:26 +0000782 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Chris Lattnerdc046542009-05-08 06:58:22 +0000785 // Now that we know how many fixed arguments we expect, first check that we
786 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000787 if (TheCall->getNumArgs() < 1+NumFixed) {
788 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
789 << 0 << 1+NumFixed << TheCall->getNumArgs()
790 << TheCall->getCallee()->getSourceRange();
791 return ExprError();
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattner5b9241b2009-05-08 15:36:58 +0000794 // Get the decl for the concrete builtin from this, we can tell what the
795 // concrete integer type we should convert to is.
796 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
797 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
798 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000799 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000800 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
801 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000802
John McCallcf142162010-08-07 06:22:56 +0000803 // The first argument --- the pointer --- has a fixed type; we
804 // deduce the types of the rest of the arguments accordingly. Walk
805 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000806 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +0000807 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000808
Chris Lattnerdc046542009-05-08 06:58:22 +0000809 // If the argument is an implicit cast, then there was a promotion due to
810 // "...", just remove it now.
John Wiegley01296292011-04-08 18:41:53 +0000811 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000812 Arg = ICE->getSubExpr();
813 ICE->setSubExpr(0);
John Wiegley01296292011-04-08 18:41:53 +0000814 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +0000815 }
Mike Stump11289f42009-09-09 15:08:12 +0000816
Chris Lattnerdc046542009-05-08 06:58:22 +0000817 // GCC does an implicit conversion to the pointer or integer ValType. This
818 // can fail in some cases (1i -> int**), check for this error case now.
John McCallb50451a2011-10-05 07:41:44 +0000819 // Initialize the argument.
820 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
821 ValType, /*consume*/ false);
822 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
John Wiegley01296292011-04-08 18:41:53 +0000823 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000824 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000825
Chris Lattnerdc046542009-05-08 06:58:22 +0000826 // Okay, we have something that *can* be converted to the right type. Check
827 // to see if there is a potentially weird extension going on here. This can
828 // happen when you do an atomic operation on something like an char* and
829 // pass in 42. The 42 gets converted to char. This is even more strange
830 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000831 // FIXME: Do this check.
John McCallb50451a2011-10-05 07:41:44 +0000832 TheCall->setArg(i+1, Arg.take());
Chris Lattnerdc046542009-05-08 06:58:22 +0000833 }
Mike Stump11289f42009-09-09 15:08:12 +0000834
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000835 ASTContext& Context = this->getASTContext();
836
837 // Create a new DeclRefExpr to refer to the new decl.
838 DeclRefExpr* NewDRE = DeclRefExpr::Create(
839 Context,
840 DRE->getQualifierLoc(),
841 NewBuiltinDecl,
842 DRE->getLocation(),
843 NewBuiltinDecl->getType(),
844 DRE->getValueKind());
Mike Stump11289f42009-09-09 15:08:12 +0000845
Chris Lattnerdc046542009-05-08 06:58:22 +0000846 // Set the callee in the CallExpr.
847 // FIXME: This leaks the original parens and implicit casts.
Douglas Gregor6b3bcf22011-09-09 16:51:10 +0000848 ExprResult PromotedCall = UsualUnaryConversions(NewDRE);
John Wiegley01296292011-04-08 18:41:53 +0000849 if (PromotedCall.isInvalid())
850 return ExprError();
851 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +0000852
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000853 // Change the result type of the call to match the original value type. This
854 // is arbitrary, but the codegen for these builtins ins design to handle it
855 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000856 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000857
858 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +0000859}
860
Chris Lattner6436fb62009-02-18 06:01:06 +0000861/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000862/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000863/// Note: It might also make sense to do the UTF-16 conversion here (would
864/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000865bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000866 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000867 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
868
Douglas Gregorfb65e592011-07-27 05:40:30 +0000869 if (!Literal || !Literal->isAscii()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000870 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
871 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000872 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000873 }
Mike Stump11289f42009-09-09 15:08:12 +0000874
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000875 if (Literal->containsNonAsciiOrNull()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876 StringRef String = Literal->getString();
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000877 unsigned NumBytes = String.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000878 SmallVector<UTF16, 128> ToBuf(NumBytes);
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000879 const UTF8 *FromPtr = (UTF8 *)String.data();
880 UTF16 *ToPtr = &ToBuf[0];
881
882 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
883 &ToPtr, ToPtr + NumBytes,
884 strictConversion);
885 // Check for conversion failure.
886 if (Result != conversionOK)
887 Diag(Arg->getLocStart(),
888 diag::warn_cfstring_truncated) << Arg->getSourceRange();
889 }
Anders Carlssona3a9c432007-08-17 15:44:17 +0000890 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000891}
892
Chris Lattnere202e6a2007-12-20 00:05:45 +0000893/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
894/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000895bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
896 Expr *Fn = TheCall->getCallee();
897 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000898 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000899 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000900 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
901 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000902 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000903 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000904 return true;
905 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000906
907 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +0000908 return Diag(TheCall->getLocEnd(),
909 diag::err_typecheck_call_too_few_args_at_least)
910 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000911 }
912
John McCall29ad95b2011-08-27 01:09:30 +0000913 // Type-check the first argument normally.
914 if (checkBuiltinArgument(*this, TheCall, 0))
915 return true;
916
Chris Lattnere202e6a2007-12-20 00:05:45 +0000917 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000918 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +0000919 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000920 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +0000921 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +0000922 else if (FunctionDecl *FD = getCurFunctionDecl())
923 isVariadic = FD->isVariadic();
924 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000925 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000926
Chris Lattnere202e6a2007-12-20 00:05:45 +0000927 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000928 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
929 return true;
930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
Chris Lattner43be2e62007-12-19 23:59:04 +0000932 // Verify that the second argument to the builtin is the last argument of the
933 // current function or method.
934 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000935 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000936
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000937 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
938 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000939 // FIXME: This isn't correct for methods (results in bogus warning).
940 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000941 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000942 if (CurBlock)
943 LastArg = *(CurBlock->TheDecl->param_end()-1);
944 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000945 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000946 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000947 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000948 SecondArgIsLastNamedArgument = PV == LastArg;
949 }
950 }
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner43be2e62007-12-19 23:59:04 +0000952 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000953 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +0000954 diag::warn_second_parameter_of_va_start_not_last_named_argument);
955 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +0000956}
Chris Lattner43be2e62007-12-19 23:59:04 +0000957
Chris Lattner2da14fb2007-12-20 00:26:33 +0000958/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
959/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +0000960bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
961 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000962 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000963 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +0000964 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +0000965 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000966 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000967 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +0000968 << SourceRange(TheCall->getArg(2)->getLocStart(),
969 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000970
John Wiegley01296292011-04-08 18:41:53 +0000971 ExprResult OrigArg0 = TheCall->getArg(0);
972 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000973
Chris Lattner2da14fb2007-12-20 00:26:33 +0000974 // Do standard promotions between the two arguments, returning their common
975 // type.
Chris Lattner08464942007-12-28 05:29:59 +0000976 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +0000977 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
978 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +0000979
980 // Make sure any conversions are pushed back into the call; this is
981 // type safe since unordered compare builtins are declared as "_Bool
982 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +0000983 TheCall->setArg(0, OrigArg0.get());
984 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +0000985
John Wiegley01296292011-04-08 18:41:53 +0000986 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +0000987 return false;
988
Chris Lattner2da14fb2007-12-20 00:26:33 +0000989 // If the common type isn't a real floating type, then the arguments were
990 // invalid for this operation.
991 if (!Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +0000992 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000993 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +0000994 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
995 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000996
Chris Lattner2da14fb2007-12-20 00:26:33 +0000997 return false;
998}
999
Benjamin Kramer634fc102010-02-15 22:42:31 +00001000/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
1001/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +00001002/// to check everything. We expect the last argument to be a floating point
1003/// value.
1004bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
1005 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +00001006 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +00001007 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +00001008 if (TheCall->getNumArgs() > NumArgs)
1009 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001010 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001011 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +00001012 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001013 (*(TheCall->arg_end()-1))->getLocEnd());
1014
Benjamin Kramer64aae502010-02-16 10:07:31 +00001015 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +00001016
Eli Friedman7e4faac2009-08-31 20:06:00 +00001017 if (OrigArg->isTypeDependent())
1018 return false;
1019
Chris Lattner68784ef2010-05-06 05:50:07 +00001020 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +00001021 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +00001022 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +00001023 diag::err_typecheck_call_invalid_unary_fp)
1024 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00001025
Chris Lattner68784ef2010-05-06 05:50:07 +00001026 // If this is an implicit conversion from float -> double, remove it.
1027 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
1028 Expr *CastArg = Cast->getSubExpr();
1029 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
1030 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
1031 "promotion from float to double is the only expected cast here");
1032 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +00001033 TheCall->setArg(NumArgs-1, CastArg);
1034 OrigArg = CastArg;
1035 }
1036 }
1037
Eli Friedman7e4faac2009-08-31 20:06:00 +00001038 return false;
1039}
1040
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001041/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
1042// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +00001043ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +00001044 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001045 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +00001046 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +00001047 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +00001048 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001049
Nate Begemana0110022010-06-08 00:16:34 +00001050 // Determine which of the following types of shufflevector we're checking:
1051 // 1) unary, vector mask: (lhs, mask)
1052 // 2) binary, vector mask: (lhs, rhs, mask)
1053 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
1054 QualType resType = TheCall->getArg(0)->getType();
1055 unsigned numElements = 0;
1056
Douglas Gregorc25f7662009-05-19 22:10:17 +00001057 if (!TheCall->getArg(0)->isTypeDependent() &&
1058 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +00001059 QualType LHSType = TheCall->getArg(0)->getType();
1060 QualType RHSType = TheCall->getArg(1)->getType();
1061
1062 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001063 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001064 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001065 TheCall->getArg(1)->getLocEnd());
1066 return ExprError();
1067 }
Nate Begemana0110022010-06-08 00:16:34 +00001068
1069 numElements = LHSType->getAs<VectorType>()->getNumElements();
1070 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +00001071
Nate Begemana0110022010-06-08 00:16:34 +00001072 // Check to see if we have a call with 2 vector arguments, the unary shuffle
1073 // with mask. If so, verify that RHS is an integer vector type with the
1074 // same number of elts as lhs.
1075 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00001076 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +00001077 RHSType->getAs<VectorType>()->getNumElements() != numElements)
1078 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
1079 << SourceRange(TheCall->getArg(1)->getLocStart(),
1080 TheCall->getArg(1)->getLocEnd());
1081 numResElements = numElements;
1082 }
1083 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001084 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +00001085 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +00001086 TheCall->getArg(1)->getLocEnd());
1087 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +00001088 } else if (numElements != numResElements) {
1089 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +00001090 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +00001091 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +00001092 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001093 }
1094
1095 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +00001096 if (TheCall->getArg(i)->isTypeDependent() ||
1097 TheCall->getArg(i)->isValueDependent())
1098 continue;
1099
Nate Begemana0110022010-06-08 00:16:34 +00001100 llvm::APSInt Result(32);
1101 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
1102 return ExprError(Diag(TheCall->getLocStart(),
1103 diag::err_shufflevector_nonconstant_argument)
1104 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001105
Chris Lattner7ab824e2008-08-10 02:05:13 +00001106 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001107 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001108 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +00001109 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001110 }
1111
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001112 SmallVector<Expr*, 32> exprs;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001113
Chris Lattner7ab824e2008-08-10 02:05:13 +00001114 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001115 exprs.push_back(TheCall->getArg(i));
1116 TheCall->setArg(i, 0);
1117 }
1118
Nate Begemanf485fb52009-08-12 02:10:25 +00001119 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +00001120 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +00001121 TheCall->getCallee()->getLocStart(),
1122 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001123}
Chris Lattner43be2e62007-12-19 23:59:04 +00001124
Daniel Dunbarb7257262008-07-21 22:59:13 +00001125/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
1126// This is declared to take (const void*, ...) and can take two
1127// optional constant int args.
1128bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +00001129 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001130
Chris Lattner3b054132008-11-19 05:08:23 +00001131 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001132 return Diag(TheCall->getLocEnd(),
1133 diag::err_typecheck_call_too_many_args_at_most)
1134 << 0 /*function call*/ << 3 << NumArgs
1135 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001136
1137 // Argument 0 is checked for us and the remaining arguments must be
1138 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +00001139 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +00001140 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001141
Eli Friedman5efba262009-12-04 00:30:06 +00001142 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +00001143 if (SemaBuiltinConstantArg(TheCall, i, Result))
1144 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001145
Daniel Dunbarb7257262008-07-21 22:59:13 +00001146 // FIXME: gcc issues a warning and rewrites these to 0. These
1147 // seems especially odd for the third argument since the default
1148 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +00001149 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +00001150 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +00001151 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001152 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001153 } else {
Eli Friedman5efba262009-12-04 00:30:06 +00001154 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +00001155 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +00001156 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +00001157 }
1158 }
1159
Chris Lattner3b054132008-11-19 05:08:23 +00001160 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +00001161}
1162
Eric Christopher8d0c6212010-04-17 02:26:23 +00001163/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
1164/// TheCall is a constant expression.
1165bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
1166 llvm::APSInt &Result) {
1167 Expr *Arg = TheCall->getArg(ArgNum);
1168 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
1169 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
1170
1171 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
1172
1173 if (!Arg->isIntegerConstantExpr(Result, Context))
1174 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +00001175 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +00001176
Chris Lattnerd545ad12009-09-23 06:06:36 +00001177 return false;
1178}
1179
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001180/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
1181/// int type). This simply type checks that type is one of the defined
1182/// constants (0-3).
Chris Lattner57540c52011-04-15 05:22:18 +00001183// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001184bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +00001185 llvm::APSInt Result;
1186
1187 // Check constant-ness first.
1188 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1189 return true;
1190
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001191 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001192 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +00001193 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
1194 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +00001195 }
1196
1197 return false;
1198}
1199
Eli Friedmanc97d0142009-05-03 06:04:26 +00001200/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001201/// This checks that val is a constant 1.
1202bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
1203 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +00001204 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +00001205
Eric Christopher8d0c6212010-04-17 02:26:23 +00001206 // TODO: This is less than ideal. Overload this to take a value.
1207 if (SemaBuiltinConstantArg(TheCall, 1, Result))
1208 return true;
1209
1210 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +00001211 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
1212 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
1213
1214 return false;
1215}
1216
Ted Kremeneka8890832011-02-24 23:03:04 +00001217// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001218bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
1219 bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001220 unsigned format_idx, unsigned firstDataArg,
1221 bool isPrintf) {
Ted Kremenek808829352010-09-09 03:51:39 +00001222 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +00001223 if (E->isTypeDependent() || E->isValueDependent())
1224 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001225
Peter Collingbourne91147592011-04-15 00:35:48 +00001226 E = E->IgnoreParens();
1227
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001228 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +00001229 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001230 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +00001231 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek02087932010-07-16 02:11:22 +00001232 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
1233 format_idx, firstDataArg, isPrintf)
John McCallc07a0c72011-02-17 10:25:35 +00001234 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001235 format_idx, firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001236 }
1237
Ted Kremenek1520dae2010-09-09 03:51:42 +00001238 case Stmt::IntegerLiteralClass:
1239 // Technically -Wformat-nonliteral does not warn about this case.
1240 // The behavior of printf and friends in this case is implementation
1241 // dependent. Ideally if the format string cannot be null then
1242 // it should have a 'nonnull' attribute in the function prototype.
1243 return true;
1244
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001245 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +00001246 E = cast<ImplicitCastExpr>(E)->getSubExpr();
1247 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001248 }
1249
John McCallc07a0c72011-02-17 10:25:35 +00001250 case Stmt::OpaqueValueExprClass:
1251 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
1252 E = src;
1253 goto tryAgain;
1254 }
1255 return false;
1256
Ted Kremeneka8890832011-02-24 23:03:04 +00001257 case Stmt::PredefinedExprClass:
1258 // While __func__, etc., are technically not string literals, they
1259 // cannot contain format specifiers and thus are not a security
1260 // liability.
1261 return true;
1262
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001263 case Stmt::DeclRefExprClass: {
1264 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001265
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001266 // As an exception, do not flag errors for variables binding to
1267 // const string literals.
1268 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
1269 bool isConstant = false;
1270 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001271
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001272 if (const ArrayType *AT = Context.getAsArrayType(T)) {
1273 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +00001274 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001275 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001276 PT->getPointeeType().isConstant(Context);
1277 }
Mike Stump11289f42009-09-09 15:08:12 +00001278
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001279 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001280 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001281 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek02087932010-07-16 02:11:22 +00001282 HasVAListArg, format_idx, firstDataArg,
1283 isPrintf);
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001284 }
Mike Stump11289f42009-09-09 15:08:12 +00001285
Anders Carlssonb012ca92009-06-28 19:55:58 +00001286 // For vprintf* functions (i.e., HasVAListArg==true), we add a
1287 // special check to see if the format string is a function parameter
1288 // of the function calling the printf function. If the function
1289 // has an attribute indicating it is a printf-like function, then we
1290 // should suppress warnings concerning non-literals being used in a call
1291 // to a vprintf function. For example:
1292 //
1293 // void
1294 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
1295 // va_list ap;
1296 // va_start(ap, fmt);
1297 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
1298 // ...
1299 //
1300 //
1301 // FIXME: We don't have full attribute support yet, so just check to see
1302 // if the argument is a DeclRefExpr that references a parameter. We'll
1303 // add proper support for checking the attribute later.
1304 if (HasVAListArg)
1305 if (isa<ParmVarDecl>(VD))
1306 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001307 }
Mike Stump11289f42009-09-09 15:08:12 +00001308
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001309 return false;
1310 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001311
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001312 case Stmt::CallExprClass: {
1313 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001314 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001315 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1316 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1317 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001318 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001319 unsigned ArgIndex = FA->getFormatIdx();
1320 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00001321
1322 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001323 format_idx, firstDataArg, isPrintf);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001324 }
1325 }
1326 }
1327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001329 return false;
1330 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001331 case Stmt::ObjCStringLiteralClass:
1332 case Stmt::StringLiteralClass: {
1333 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001334
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001335 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001336 StrE = ObjCFExpr->getString();
1337 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001338 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001339
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001340 if (StrE) {
Ted Kremenek02087932010-07-16 02:11:22 +00001341 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1342 firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001343 return true;
1344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001346 return false;
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001349 default:
1350 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001351 }
1352}
1353
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001354void
Mike Stump11289f42009-09-09 15:08:12 +00001355Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00001356 const Expr * const *ExprArgs,
1357 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001358 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1359 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001360 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00001361 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001362 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001363 Expr::NPC_ValueDependentIsNotNull))
Nick Lewyckyd4693212011-03-25 01:44:32 +00001364 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001365 }
1366}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001367
Peter Collingbourne5aa6ecb2011-10-16 21:17:32 +00001368static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
1369 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
1370 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
1371 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
1372 << ATL->getLocalSourceRange();
1373}
1374
1375/// CheckStaticArrayArguments - Check that each argument corresponding to a
1376/// static array parameter is non-null, and that if it is formed by
1377/// array-to-pointer decay, the underlying array is sufficiently large.
1378///
1379/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
1380/// array type derivation, then for each call to the function, the value of the
1381/// corresponding actual argument shall provide access to the first element of
1382/// an array with at least as many elements as specified by the size expression.
1383void
1384Sema::CheckStaticArrayArguments(const FunctionDecl *FDecl,
1385 const Expr * const *ExprArgs,
1386 SourceLocation CallSiteLoc) {
1387 // Static array parameters are not supported in C++.
1388 if (getLangOptions().CPlusPlus)
1389 return;
1390
1391 for (FunctionDecl::param_const_iterator i = FDecl->param_begin(),
1392 e = FDecl->param_end(); i != e; ++i, ++ExprArgs) {
1393 const Expr *ArgExpr = *ExprArgs;
1394 QualType OrigTy = (*i)->getOriginalType();
1395
1396 const ArrayType *AT = Context.getAsArrayType(OrigTy);
1397 if (!AT || AT->getSizeModifier() != ArrayType::Static)
1398 continue;
1399
1400 if (ArgExpr->isNullPointerConstant(Context,
1401 Expr::NPC_NeverValueDependent)) {
1402 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1403 DiagnoseCalleeStaticArrayParam(*this, *i);
1404 continue;
1405 }
1406
1407 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
1408 if (!CAT)
1409 continue;
1410
1411 const ConstantArrayType *ArgCAT =
1412 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
1413 if (!ArgCAT)
1414 continue;
1415
1416 if (ArgCAT->getSize().ult(CAT->getSize())) {
1417 Diag(CallSiteLoc, diag::warn_static_array_too_small)
1418 << ArgExpr->getSourceRange()
1419 << (unsigned) ArgCAT->getSize().getZExtValue()
1420 << (unsigned) CAT->getSize().getZExtValue();
1421 DiagnoseCalleeStaticArrayParam(*this, *i);
1422 }
1423 }
1424}
1425
Ted Kremenek02087932010-07-16 02:11:22 +00001426/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1427/// functions) for correct use of format strings.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001428void
Ted Kremenek02087932010-07-16 02:11:22 +00001429Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1430 unsigned format_idx, unsigned firstDataArg,
1431 bool isPrintf) {
1432
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001433 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +00001434
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001435 // The way the format attribute works in GCC, the implicit this argument
1436 // of member functions is counted. However, it doesn't appear in our own
1437 // lists, so decrement format_idx in that case.
1438 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth1c8383d2010-11-16 08:49:43 +00001439 const CXXMethodDecl *method_decl =
1440 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1441 if (method_decl && method_decl->isInstance()) {
1442 // Catch a format attribute mistakenly referring to the object argument.
1443 if (format_idx == 0)
1444 return;
1445 --format_idx;
1446 if(firstDataArg != 0)
1447 --firstDataArg;
1448 }
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001449 }
1450
Ted Kremenek02087932010-07-16 02:11:22 +00001451 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +00001452 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001453 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerf490e152008-11-19 05:27:50 +00001454 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001455 return;
1456 }
Mike Stump11289f42009-09-09 15:08:12 +00001457
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001458 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001459
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001460 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001461 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001462 // Dynamically generated format strings are difficult to
1463 // automatically vet at compile time. Requiring that format strings
1464 // are string literals: (1) permits the checking of format strings by
1465 // the compiler and thereby (2) can practically remove the source of
1466 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001467
Mike Stump11289f42009-09-09 15:08:12 +00001468 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001469 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001470 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001471 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001472 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek02087932010-07-16 02:11:22 +00001473 firstDataArg, isPrintf))
Chris Lattnere009a882009-04-29 04:49:34 +00001474 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001475
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001476 // If there are no arguments specified, warn with -Wformat-security, otherwise
1477 // warn only with -Wformat-nonliteral.
1478 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001479 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001480 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001481 << OrigFormatExpr->getSourceRange();
1482 else
Mike Stump11289f42009-09-09 15:08:12 +00001483 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001484 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001485 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001486}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001487
Ted Kremenekab278de2010-01-28 23:39:18 +00001488namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001489class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1490protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001491 Sema &S;
1492 const StringLiteral *FExpr;
1493 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001494 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001495 const unsigned NumDataArgs;
1496 const bool IsObjCLiteral;
1497 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001498 const bool HasVAListArg;
1499 const CallExpr *TheCall;
1500 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001501 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001502 bool usesPositionalArgs;
1503 bool atFirstArg;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001504public:
Ted Kremenek02087932010-07-16 02:11:22 +00001505 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001506 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001507 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001508 const char *beg, bool hasVAListArg,
1509 const CallExpr *theCall, unsigned formatIdx)
Ted Kremenekab278de2010-01-28 23:39:18 +00001510 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001511 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001512 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001513 IsObjCLiteral(isObjCLiteral), Beg(beg),
1514 HasVAListArg(hasVAListArg),
Ted Kremenekd1668192010-02-27 01:41:03 +00001515 TheCall(theCall), FormatIdx(formatIdx),
1516 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001517 CoveredArgs.resize(numDataArgs);
1518 CoveredArgs.reset();
1519 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001520
Ted Kremenek019d2242010-01-29 01:50:07 +00001521 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001522
Ted Kremenek02087932010-07-16 02:11:22 +00001523 void HandleIncompleteSpecifier(const char *startSpecifier,
1524 unsigned specifierLen);
1525
Ted Kremenekd1668192010-02-27 01:41:03 +00001526 virtual void HandleInvalidPosition(const char *startSpecifier,
1527 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001528 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001529
1530 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1531
Ted Kremenekab278de2010-01-28 23:39:18 +00001532 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001533
Ted Kremenek02087932010-07-16 02:11:22 +00001534protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001535 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1536 const char *startSpec,
1537 unsigned specifierLen,
1538 const char *csStart, unsigned csLen);
1539
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001540 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001541 CharSourceRange getSpecifierRange(const char *startSpecifier,
1542 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001543 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001544
Ted Kremenek5739de72010-01-29 01:06:55 +00001545 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001546
1547 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1548 const analyze_format_string::ConversionSpecifier &CS,
1549 const char *startSpecifier, unsigned specifierLen,
1550 unsigned argIndex);
Ted Kremenekab278de2010-01-28 23:39:18 +00001551};
1552}
1553
Ted Kremenek02087932010-07-16 02:11:22 +00001554SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001555 return OrigFormatExpr->getSourceRange();
1556}
1557
Ted Kremenek02087932010-07-16 02:11:22 +00001558CharSourceRange CheckFormatHandler::
1559getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001560 SourceLocation Start = getLocationOfByte(startSpecifier);
1561 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1562
1563 // Advance the end SourceLocation by one due to half-open ranges.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00001564 End = End.getLocWithOffset(1);
Tom Care3f272b82010-06-21 21:21:01 +00001565
1566 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001567}
1568
Ted Kremenek02087932010-07-16 02:11:22 +00001569SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001570 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001571}
1572
Ted Kremenek02087932010-07-16 02:11:22 +00001573void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1574 unsigned specifierLen){
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001575 SourceLocation Loc = getLocationOfByte(startSpecifier);
1576 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek02087932010-07-16 02:11:22 +00001577 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001578}
1579
Ted Kremenekd1668192010-02-27 01:41:03 +00001580void
Ted Kremenek02087932010-07-16 02:11:22 +00001581CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1582 analyze_format_string::PositionContext p) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001583 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001584 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1585 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001586}
1587
Ted Kremenek02087932010-07-16 02:11:22 +00001588void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001589 unsigned posLen) {
1590 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001591 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1592 << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001593}
1594
Ted Kremenek02087932010-07-16 02:11:22 +00001595void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001596 if (!IsObjCLiteral) {
1597 // The presence of a null character is likely an error.
1598 S.Diag(getLocationOfByte(nullCharacter),
1599 diag::warn_printf_format_string_contains_null_char)
1600 << getFormatStringRange();
1601 }
Ted Kremenek02087932010-07-16 02:11:22 +00001602}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001603
Ted Kremenek02087932010-07-16 02:11:22 +00001604const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1605 return TheCall->getArg(FirstDataArg + i);
1606}
1607
1608void CheckFormatHandler::DoneProcessing() {
1609 // Does the number of data arguments exceed the number of
1610 // format conversions in the format string?
1611 if (!HasVAListArg) {
1612 // Find any arguments that weren't covered.
1613 CoveredArgs.flip();
1614 signed notCoveredArg = CoveredArgs.find_first();
1615 if (notCoveredArg >= 0) {
1616 assert((unsigned)notCoveredArg < NumDataArgs);
1617 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1618 diag::warn_printf_data_arg_not_used)
1619 << getFormatStringRange();
1620 }
1621 }
1622}
1623
Ted Kremenekce815422010-07-19 21:25:57 +00001624bool
1625CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1626 SourceLocation Loc,
1627 const char *startSpec,
1628 unsigned specifierLen,
1629 const char *csStart,
1630 unsigned csLen) {
1631
1632 bool keepGoing = true;
1633 if (argIndex < NumDataArgs) {
1634 // Consider the argument coverered, even though the specifier doesn't
1635 // make sense.
1636 CoveredArgs.set(argIndex);
1637 }
1638 else {
1639 // If argIndex exceeds the number of data arguments we
1640 // don't issue a warning because that is just a cascade of warnings (and
1641 // they may have intended '%%' anyway). We don't want to continue processing
1642 // the format string after this point, however, as we will like just get
1643 // gibberish when trying to match arguments.
1644 keepGoing = false;
1645 }
1646
1647 S.Diag(Loc, diag::warn_format_invalid_conversion)
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001648 << StringRef(csStart, csLen)
Ted Kremenekce815422010-07-19 21:25:57 +00001649 << getSpecifierRange(startSpec, specifierLen);
1650
1651 return keepGoing;
1652}
1653
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001654bool
1655CheckFormatHandler::CheckNumArgs(
1656 const analyze_format_string::FormatSpecifier &FS,
1657 const analyze_format_string::ConversionSpecifier &CS,
1658 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1659
1660 if (argIndex >= NumDataArgs) {
1661 if (FS.usesPositionalArg()) {
1662 S.Diag(getLocationOfByte(CS.getStart()),
1663 diag::warn_printf_positional_arg_exceeds_data_args)
1664 << (argIndex+1) << NumDataArgs
1665 << getSpecifierRange(startSpecifier, specifierLen);
1666 }
1667 else {
1668 S.Diag(getLocationOfByte(CS.getStart()),
1669 diag::warn_printf_insufficient_data_args)
1670 << getSpecifierRange(startSpecifier, specifierLen);
1671 }
1672
1673 return false;
1674 }
1675 return true;
1676}
1677
Ted Kremenek02087932010-07-16 02:11:22 +00001678//===--- CHECK: Printf format string checking ------------------------------===//
1679
1680namespace {
1681class CheckPrintfHandler : public CheckFormatHandler {
1682public:
1683 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1684 const Expr *origFormatExpr, unsigned firstDataArg,
1685 unsigned numDataArgs, bool isObjCLiteral,
1686 const char *beg, bool hasVAListArg,
1687 const CallExpr *theCall, unsigned formatIdx)
1688 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1689 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1690 theCall, formatIdx) {}
1691
1692
1693 bool HandleInvalidPrintfConversionSpecifier(
1694 const analyze_printf::PrintfSpecifier &FS,
1695 const char *startSpecifier,
1696 unsigned specifierLen);
1697
1698 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1699 const char *startSpecifier,
1700 unsigned specifierLen);
1701
1702 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1703 const char *startSpecifier, unsigned specifierLen);
1704 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1705 const analyze_printf::OptionalAmount &Amt,
1706 unsigned type,
1707 const char *startSpecifier, unsigned specifierLen);
1708 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1709 const analyze_printf::OptionalFlag &flag,
1710 const char *startSpecifier, unsigned specifierLen);
1711 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1712 const analyze_printf::OptionalFlag &ignoredFlag,
1713 const analyze_printf::OptionalFlag &flag,
1714 const char *startSpecifier, unsigned specifierLen);
1715};
1716}
1717
1718bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1719 const analyze_printf::PrintfSpecifier &FS,
1720 const char *startSpecifier,
1721 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001722 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001723 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001724
Ted Kremenekce815422010-07-19 21:25:57 +00001725 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1726 getLocationOfByte(CS.getStart()),
1727 startSpecifier, specifierLen,
1728 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001729}
1730
Ted Kremenek02087932010-07-16 02:11:22 +00001731bool CheckPrintfHandler::HandleAmount(
1732 const analyze_format_string::OptionalAmount &Amt,
1733 unsigned k, const char *startSpecifier,
1734 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001735
1736 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001737 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001738 unsigned argIndex = Amt.getArgIndex();
1739 if (argIndex >= NumDataArgs) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001740 S.Diag(getLocationOfByte(Amt.getStart()),
1741 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek02087932010-07-16 02:11:22 +00001742 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001743 // Don't do any more checking. We will just emit
1744 // spurious errors.
1745 return false;
1746 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001747
Ted Kremenek5739de72010-01-29 01:06:55 +00001748 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001749 // Although not in conformance with C99, we also allow the argument to be
1750 // an 'unsigned int' as that is a reasonably safe case. GCC also
1751 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001752 CoveredArgs.set(argIndex);
1753 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001754 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001755
1756 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1757 assert(ATR.isValid());
1758
1759 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001760 S.Diag(getLocationOfByte(Amt.getStart()),
1761 diag::warn_printf_asterisk_wrong_type)
1762 << k
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001763 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek02087932010-07-16 02:11:22 +00001764 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001765 << Arg->getSourceRange();
Ted Kremenek5739de72010-01-29 01:06:55 +00001766 // Don't do any more checking. We will just emit
1767 // spurious errors.
1768 return false;
1769 }
1770 }
1771 }
1772 return true;
1773}
Ted Kremenek5739de72010-01-29 01:06:55 +00001774
Tom Careb49ec692010-06-17 19:00:27 +00001775void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001776 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001777 const analyze_printf::OptionalAmount &Amt,
1778 unsigned type,
1779 const char *startSpecifier,
1780 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001781 const analyze_printf::PrintfConversionSpecifier &CS =
1782 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001783 switch (Amt.getHowSpecified()) {
1784 case analyze_printf::OptionalAmount::Constant:
1785 S.Diag(getLocationOfByte(Amt.getStart()),
1786 diag::warn_printf_nonsensical_optional_amount)
1787 << type
1788 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001789 << getSpecifierRange(startSpecifier, specifierLen)
1790 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001791 Amt.getConstantLength()));
1792 break;
1793
1794 default:
1795 S.Diag(getLocationOfByte(Amt.getStart()),
1796 diag::warn_printf_nonsensical_optional_amount)
1797 << type
1798 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001799 << getSpecifierRange(startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001800 break;
1801 }
1802}
1803
Ted Kremenek02087932010-07-16 02:11:22 +00001804void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001805 const analyze_printf::OptionalFlag &flag,
1806 const char *startSpecifier,
1807 unsigned specifierLen) {
1808 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001809 const analyze_printf::PrintfConversionSpecifier &CS =
1810 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001811 S.Diag(getLocationOfByte(flag.getPosition()),
1812 diag::warn_printf_nonsensical_flag)
1813 << flag.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001814 << getSpecifierRange(startSpecifier, specifierLen)
1815 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Careb49ec692010-06-17 19:00:27 +00001816}
1817
1818void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00001819 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001820 const analyze_printf::OptionalFlag &ignoredFlag,
1821 const analyze_printf::OptionalFlag &flag,
1822 const char *startSpecifier,
1823 unsigned specifierLen) {
1824 // Warn about ignored flag with a fixit removal.
1825 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1826 diag::warn_printf_ignored_flag)
1827 << ignoredFlag.toString() << flag.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001828 << getSpecifierRange(startSpecifier, specifierLen)
1829 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Careb49ec692010-06-17 19:00:27 +00001830 ignoredFlag.getPosition(), 1));
1831}
1832
Ted Kremenekab278de2010-01-28 23:39:18 +00001833bool
Ted Kremenek02087932010-07-16 02:11:22 +00001834CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00001835 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001836 const char *startSpecifier,
1837 unsigned specifierLen) {
1838
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001839 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00001840 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001841 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00001842
Ted Kremenek6cd69422010-07-19 22:01:06 +00001843 if (FS.consumesDataArgument()) {
1844 if (atFirstArg) {
1845 atFirstArg = false;
1846 usesPositionalArgs = FS.usesPositionalArg();
1847 }
1848 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1849 // Cannot mix-and-match positional and non-positional arguments.
1850 S.Diag(getLocationOfByte(CS.getStart()),
1851 diag::warn_format_mix_positional_nonpositional_args)
1852 << getSpecifierRange(startSpecifier, specifierLen);
1853 return false;
1854 }
Ted Kremenek5739de72010-01-29 01:06:55 +00001855 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001856
Ted Kremenekd1668192010-02-27 01:41:03 +00001857 // First check if the field width, precision, and conversion specifier
1858 // have matching data arguments.
1859 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1860 startSpecifier, specifierLen)) {
1861 return false;
1862 }
1863
1864 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1865 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001866 return false;
1867 }
1868
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001869 if (!CS.consumesDataArgument()) {
1870 // FIXME: Technically specifying a precision or field width here
1871 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001872 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001873 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001874
Ted Kremenek4a49d982010-02-26 19:18:41 +00001875 // Consume the argument.
1876 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00001877 if (argIndex < NumDataArgs) {
1878 // The check to see if the argIndex is valid will come later.
1879 // We set the bit here because we may exit early from this
1880 // function if we encounter some other error.
1881 CoveredArgs.set(argIndex);
1882 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00001883
1884 // Check for using an Objective-C specific conversion specifier
1885 // in a non-ObjC literal.
1886 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001887 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1888 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00001889 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001890
Tom Careb49ec692010-06-17 19:00:27 +00001891 // Check for invalid use of field width
1892 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00001893 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00001894 startSpecifier, specifierLen);
1895 }
1896
1897 // Check for invalid use of precision
1898 if (!FS.hasValidPrecision()) {
1899 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1900 startSpecifier, specifierLen);
1901 }
1902
1903 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00001904 if (!FS.hasValidThousandsGroupingPrefix())
1905 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001906 if (!FS.hasValidLeadingZeros())
1907 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1908 if (!FS.hasValidPlusPrefix())
1909 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00001910 if (!FS.hasValidSpacePrefix())
1911 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001912 if (!FS.hasValidAlternativeForm())
1913 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1914 if (!FS.hasValidLeftJustified())
1915 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1916
1917 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00001918 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1919 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1920 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001921 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1922 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1923 startSpecifier, specifierLen);
1924
1925 // Check the length modifier is valid with the given conversion specifier.
1926 const LengthModifier &LM = FS.getLengthModifier();
1927 if (!FS.hasValidLengthModifier())
1928 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenekb65a9d52010-07-20 20:03:43 +00001929 diag::warn_format_nonsensical_length)
Tom Careb49ec692010-06-17 19:00:27 +00001930 << LM.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001931 << getSpecifierRange(startSpecifier, specifierLen)
1932 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001933 LM.getLength()));
1934
1935 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00001936 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00001937 // Issue a warning about this being a possible security issue.
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001938 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek02087932010-07-16 02:11:22 +00001939 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001940 // Continue checking the other format specifiers.
1941 return true;
1942 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00001943
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001944 // The remaining checks depend on the data arguments.
1945 if (HasVAListArg)
1946 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001947
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001948 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001949 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001950
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001951 // Now type check the data expression that matches the
1952 // format specifier.
1953 const Expr *Ex = getDataArg(argIndex);
1954 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1955 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1956 // Check if we didn't match because of an implicit cast from a 'char'
1957 // or 'short' to an 'int'. This is done because printf is a varargs
1958 // function.
1959 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00001960 if (ICE->getType() == S.Context.IntTy) {
1961 // All further checking is done on the subexpression.
1962 Ex = ICE->getSubExpr();
1963 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001964 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00001965 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001966
1967 // We may be able to offer a FixItHint if it is a supported type.
1968 PrintfSpecifier fixedFS = FS;
1969 bool success = fixedFS.fixType(Ex->getType());
1970
1971 if (success) {
1972 // Get the fix string from the fixed format specifier
1973 llvm::SmallString<128> buf;
1974 llvm::raw_svector_ostream os(buf);
1975 fixedFS.toString(os);
1976
Ted Kremenek5f0c0662010-08-24 22:24:51 +00001977 // FIXME: getRepresentativeType() perhaps should return a string
1978 // instead of a QualType to better handle when the representative
1979 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001980 S.Diag(getLocationOfByte(CS.getStart()),
1981 diag::warn_printf_conversion_argument_type_mismatch)
1982 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1983 << getSpecifierRange(startSpecifier, specifierLen)
1984 << Ex->getSourceRange()
1985 << FixItHint::CreateReplacement(
1986 getSpecifierRange(startSpecifier, specifierLen),
1987 os.str());
1988 }
1989 else {
1990 S.Diag(getLocationOfByte(CS.getStart()),
1991 diag::warn_printf_conversion_argument_type_mismatch)
1992 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1993 << getSpecifierRange(startSpecifier, specifierLen)
1994 << Ex->getSourceRange();
1995 }
1996 }
1997
Ted Kremenekab278de2010-01-28 23:39:18 +00001998 return true;
1999}
2000
Ted Kremenek02087932010-07-16 02:11:22 +00002001//===--- CHECK: Scanf format string checking ------------------------------===//
2002
2003namespace {
2004class CheckScanfHandler : public CheckFormatHandler {
2005public:
2006 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
2007 const Expr *origFormatExpr, unsigned firstDataArg,
2008 unsigned numDataArgs, bool isObjCLiteral,
2009 const char *beg, bool hasVAListArg,
2010 const CallExpr *theCall, unsigned formatIdx)
2011 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
2012 numDataArgs, isObjCLiteral, beg, hasVAListArg,
2013 theCall, formatIdx) {}
2014
2015 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
2016 const char *startSpecifier,
2017 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00002018
2019 bool HandleInvalidScanfConversionSpecifier(
2020 const analyze_scanf::ScanfSpecifier &FS,
2021 const char *startSpecifier,
2022 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002023
2024 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00002025};
Ted Kremenek019d2242010-01-29 01:50:07 +00002026}
Ted Kremenekab278de2010-01-28 23:39:18 +00002027
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00002028void CheckScanfHandler::HandleIncompleteScanList(const char *start,
2029 const char *end) {
2030 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
2031 << getSpecifierRange(start, end - start);
2032}
2033
Ted Kremenekce815422010-07-19 21:25:57 +00002034bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
2035 const analyze_scanf::ScanfSpecifier &FS,
2036 const char *startSpecifier,
2037 unsigned specifierLen) {
2038
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002039 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00002040 FS.getConversionSpecifier();
2041
2042 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
2043 getLocationOfByte(CS.getStart()),
2044 startSpecifier, specifierLen,
2045 CS.getStart(), CS.getLength());
2046}
2047
Ted Kremenek02087932010-07-16 02:11:22 +00002048bool CheckScanfHandler::HandleScanfSpecifier(
2049 const analyze_scanf::ScanfSpecifier &FS,
2050 const char *startSpecifier,
2051 unsigned specifierLen) {
2052
2053 using namespace analyze_scanf;
2054 using namespace analyze_format_string;
2055
Ted Kremenekf03e6d852010-07-20 20:04:27 +00002056 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00002057
Ted Kremenek6cd69422010-07-19 22:01:06 +00002058 // Handle case where '%' and '*' don't consume an argument. These shouldn't
2059 // be used to decide if we are using positional arguments consistently.
2060 if (FS.consumesDataArgument()) {
2061 if (atFirstArg) {
2062 atFirstArg = false;
2063 usesPositionalArgs = FS.usesPositionalArg();
2064 }
2065 else if (usesPositionalArgs != FS.usesPositionalArg()) {
2066 // Cannot mix-and-match positional and non-positional arguments.
2067 S.Diag(getLocationOfByte(CS.getStart()),
2068 diag::warn_format_mix_positional_nonpositional_args)
2069 << getSpecifierRange(startSpecifier, specifierLen);
2070 return false;
2071 }
Ted Kremenek02087932010-07-16 02:11:22 +00002072 }
2073
2074 // Check if the field with is non-zero.
2075 const OptionalAmount &Amt = FS.getFieldWidth();
2076 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
2077 if (Amt.getConstantAmount() == 0) {
2078 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
2079 Amt.getConstantLength());
2080 S.Diag(getLocationOfByte(Amt.getStart()),
2081 diag::warn_scanf_nonzero_width)
2082 << R << FixItHint::CreateRemoval(R);
2083 }
2084 }
2085
2086 if (!FS.consumesDataArgument()) {
2087 // FIXME: Technically specifying a precision or field width here
2088 // makes no sense. Worth issuing a warning at some point.
2089 return true;
2090 }
2091
2092 // Consume the argument.
2093 unsigned argIndex = FS.getArgIndex();
2094 if (argIndex < NumDataArgs) {
2095 // The check to see if the argIndex is valid will come later.
2096 // We set the bit here because we may exit early from this
2097 // function if we encounter some other error.
2098 CoveredArgs.set(argIndex);
2099 }
2100
Ted Kremenek4407ea42010-07-20 20:04:47 +00002101 // Check the length modifier is valid with the given conversion specifier.
2102 const LengthModifier &LM = FS.getLengthModifier();
2103 if (!FS.hasValidLengthModifier()) {
2104 S.Diag(getLocationOfByte(LM.getStart()),
2105 diag::warn_format_nonsensical_length)
2106 << LM.toString() << CS.toString()
2107 << getSpecifierRange(startSpecifier, specifierLen)
2108 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
2109 LM.getLength()));
2110 }
2111
Ted Kremenek02087932010-07-16 02:11:22 +00002112 // The remaining checks depend on the data arguments.
2113 if (HasVAListArg)
2114 return true;
2115
Ted Kremenek6adb7e32010-07-26 19:45:42 +00002116 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00002117 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00002118
2119 // FIXME: Check that the argument type matches the format specifier.
2120
2121 return true;
2122}
2123
2124void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00002125 const Expr *OrigFormatExpr,
2126 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00002127 unsigned format_idx, unsigned firstDataArg,
2128 bool isPrintf) {
2129
Ted Kremenekab278de2010-01-28 23:39:18 +00002130 // CHECK: is the format string a wide literal?
Douglas Gregorfb65e592011-07-27 05:40:30 +00002131 if (!FExpr->isAscii()) {
Ted Kremenekab278de2010-01-28 23:39:18 +00002132 Diag(FExpr->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00002133 diag::warn_format_string_is_wide_literal)
Ted Kremenekab278de2010-01-28 23:39:18 +00002134 << OrigFormatExpr->getSourceRange();
2135 return;
2136 }
Ted Kremenek02087932010-07-16 02:11:22 +00002137
Ted Kremenekab278de2010-01-28 23:39:18 +00002138 // Str - The format string. NOTE: this is NOT null-terminated!
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002139 StringRef StrRef = FExpr->getString();
Benjamin Kramer35b077e2010-08-17 12:54:38 +00002140 const char *Str = StrRef.data();
2141 unsigned StrLen = StrRef.size();
Ted Kremenek6e302b22011-09-29 05:52:16 +00002142 const unsigned numDataArgs = TheCall->getNumArgs() - firstDataArg;
Ted Kremenek02087932010-07-16 02:11:22 +00002143
Ted Kremenekab278de2010-01-28 23:39:18 +00002144 // CHECK: empty format string?
Ted Kremenek6e302b22011-09-29 05:52:16 +00002145 if (StrLen == 0 && numDataArgs > 0) {
Ted Kremenek02087932010-07-16 02:11:22 +00002146 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremenekab278de2010-01-28 23:39:18 +00002147 << OrigFormatExpr->getSourceRange();
2148 return;
2149 }
Ted Kremenek02087932010-07-16 02:11:22 +00002150
2151 if (isPrintf) {
2152 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002153 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2154 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek02087932010-07-16 02:11:22 +00002155
2156 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
2157 H.DoneProcessing();
2158 }
2159 else {
2160 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
Ted Kremenek6e302b22011-09-29 05:52:16 +00002161 numDataArgs, isa<ObjCStringLiteral>(OrigFormatExpr),
2162 Str, HasVAListArg, TheCall, format_idx);
Ted Kremenek02087932010-07-16 02:11:22 +00002163
2164 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
2165 H.DoneProcessing();
2166 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00002167}
2168
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002169//===--- CHECK: Standard memory functions ---------------------------------===//
2170
Douglas Gregora74926b2011-05-03 20:05:22 +00002171/// \brief Determine whether the given type is a dynamic class type (e.g.,
2172/// whether it has a vtable).
2173static bool isDynamicClassType(QualType T) {
2174 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
2175 if (CXXRecordDecl *Definition = Record->getDefinition())
2176 if (Definition->isDynamicClass())
2177 return true;
2178
2179 return false;
2180}
2181
Chandler Carruth889ed862011-06-21 23:04:20 +00002182/// \brief If E is a sizeof expression, returns its argument expression,
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002183/// otherwise returns NULL.
2184static const Expr *getSizeOfExprArg(const Expr* E) {
Nico Weberc5e73862011-06-14 16:14:58 +00002185 if (const UnaryExprOrTypeTraitExpr *SizeOf =
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002186 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2187 if (SizeOf->getKind() == clang::UETT_SizeOf && !SizeOf->isArgumentType())
2188 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002189
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002190 return 0;
2191}
2192
Chandler Carruth889ed862011-06-21 23:04:20 +00002193/// \brief If E is a sizeof expression, returns its argument type.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002194static QualType getSizeOfArgType(const Expr* E) {
2195 if (const UnaryExprOrTypeTraitExpr *SizeOf =
2196 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
2197 if (SizeOf->getKind() == clang::UETT_SizeOf)
2198 return SizeOf->getTypeOfArgument();
2199
2200 return QualType();
Nico Weberc5e73862011-06-14 16:14:58 +00002201}
2202
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002203/// \brief Check for dangerous or invalid arguments to memset().
2204///
Chandler Carruthac687262011-06-03 06:23:57 +00002205/// This issues warnings on known problematic, dangerous or unspecified
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002206/// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
2207/// function calls.
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002208///
2209/// \param Call The call expression to diagnose.
Matt Beaumont-Gay3c489902011-08-05 00:22:34 +00002210void Sema::CheckMemaccessArguments(const CallExpr *Call,
2211 CheckedMemoryFunction CMF,
2212 IdentifierInfo *FnName) {
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002213 // It is possible to have a non-standard definition of memset. Validate
Douglas Gregor18739c32011-06-16 17:56:04 +00002214 // we have enough arguments, and if not, abort further checking.
Nico Weber39bfed82011-10-13 22:30:23 +00002215 unsigned ExpectedNumArgs = (CMF == CMF_Strndup ? 2 : 3);
2216 if (Call->getNumArgs() < ExpectedNumArgs)
Ted Kremenekb5fabb22011-04-28 01:38:02 +00002217 return;
2218
Nico Weber39bfed82011-10-13 22:30:23 +00002219 unsigned LastArg = (CMF == CMF_Memset || CMF == CMF_Strndup ? 1 : 2);
2220 unsigned LenArg = (CMF == CMF_Strndup ? 1 : 2);
2221 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002222
2223 // We have special checking when the length is a sizeof expression.
2224 QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
2225 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
2226 llvm::FoldingSetNodeID SizeOfArgID;
2227
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002228 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
2229 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
Nico Weberc5e73862011-06-14 16:14:58 +00002230 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002231
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002232 QualType DestTy = Dest->getType();
2233 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
2234 QualType PointeeTy = DestPtrTy->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002235
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002236 // Never warn about void type pointers. This can be used to suppress
2237 // false positives.
2238 if (PointeeTy->isVoidType())
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002239 continue;
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002240
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002241 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
2242 // actually comparing the expressions for equality. Because computing the
2243 // expression IDs can be expensive, we only do this if the diagnostic is
2244 // enabled.
2245 if (SizeOfArg &&
2246 Diags.getDiagnosticLevel(diag::warn_sizeof_pointer_expr_memaccess,
2247 SizeOfArg->getExprLoc())) {
2248 // We only compute IDs for expressions if the warning is enabled, and
2249 // cache the sizeof arg's ID.
2250 if (SizeOfArgID == llvm::FoldingSetNodeID())
2251 SizeOfArg->Profile(SizeOfArgID, Context, true);
2252 llvm::FoldingSetNodeID DestID;
2253 Dest->Profile(DestID, Context, true);
2254 if (DestID == SizeOfArgID) {
Nico Weber39bfed82011-10-13 22:30:23 +00002255 // TODO: For strncpy() and friends, this could suggest sizeof(dst)
2256 // over sizeof(src) as well.
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002257 unsigned ActionIdx = 0; // Default is to suggest dereferencing.
2258 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
2259 if (UnaryOp->getOpcode() == UO_AddrOf)
2260 ActionIdx = 1; // If its an address-of operator, just remove it.
2261 if (Context.getTypeSize(PointeeTy) == Context.getCharWidth())
2262 ActionIdx = 2; // If the pointee's size is sizeof(char),
2263 // suggest an explicit length.
Nico Weber39bfed82011-10-13 22:30:23 +00002264 unsigned DestSrcSelect = (CMF == CMF_Strndup ? 1 : ArgIdx);
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002265 DiagRuntimeBehavior(SizeOfArg->getExprLoc(), Dest,
2266 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
Nico Weber39bfed82011-10-13 22:30:23 +00002267 << FnName << DestSrcSelect << ActionIdx
Chandler Carruth8b9e5a72011-06-16 09:09:40 +00002268 << Dest->getSourceRange()
2269 << SizeOfArg->getSourceRange());
2270 break;
2271 }
2272 }
2273
2274 // Also check for cases where the sizeof argument is the exact same
2275 // type as the memory argument, and where it points to a user-defined
2276 // record type.
2277 if (SizeOfArgTy != QualType()) {
2278 if (PointeeTy->isRecordType() &&
2279 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
2280 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
2281 PDiag(diag::warn_sizeof_pointer_type_memaccess)
2282 << FnName << SizeOfArgTy << ArgIdx
2283 << PointeeTy << Dest->getSourceRange()
2284 << LenExpr->getSourceRange());
2285 break;
2286 }
Nico Weberc5e73862011-06-14 16:14:58 +00002287 }
2288
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002289 // Always complain about dynamic classes.
John McCall31168b02011-06-15 23:02:42 +00002290 if (isDynamicClassType(PointeeTy))
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002291 DiagRuntimeBehavior(
2292 Dest->getExprLoc(), Dest,
2293 PDiag(diag::warn_dyn_class_memaccess)
2294 << (CMF == CMF_Memcmp ? ArgIdx + 2 : ArgIdx) << FnName << PointeeTy
2295 // "overwritten" if we're warning about the destination for any call
2296 // but memcmp; otherwise a verb appropriate to the call.
2297 << (ArgIdx == 0 && CMF != CMF_Memcmp ? 0 : (unsigned)CMF)
2298 << Call->getCallee()->getSourceRange());
Douglas Gregor18739c32011-06-16 17:56:04 +00002299 else if (PointeeTy.hasNonTrivialObjCLifetime() && CMF != CMF_Memset)
Matt Beaumont-Gay335e6532011-08-19 20:40:18 +00002300 DiagRuntimeBehavior(
2301 Dest->getExprLoc(), Dest,
2302 PDiag(diag::warn_arc_object_memaccess)
2303 << ArgIdx << FnName << PointeeTy
2304 << Call->getCallee()->getSourceRange());
John McCall31168b02011-06-15 23:02:42 +00002305 else
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002306 continue;
John McCall31168b02011-06-15 23:02:42 +00002307
2308 DiagRuntimeBehavior(
2309 Dest->getExprLoc(), Dest,
Chandler Carruthac687262011-06-03 06:23:57 +00002310 PDiag(diag::note_bad_memaccess_silence)
Douglas Gregor3bb2a812011-05-03 20:37:33 +00002311 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
2312 break;
2313 }
Chandler Carruth53caa4d2011-04-27 07:05:31 +00002314 }
2315}
2316
Ted Kremenek6865f772011-08-18 20:55:45 +00002317// A little helper routine: ignore addition and subtraction of integer literals.
2318// This intentionally does not ignore all integer constant expressions because
2319// we don't want to remove sizeof().
2320static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
2321 Ex = Ex->IgnoreParenCasts();
2322
2323 for (;;) {
2324 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
2325 if (!BO || !BO->isAdditiveOp())
2326 break;
2327
2328 const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
2329 const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
2330
2331 if (isa<IntegerLiteral>(RHS))
2332 Ex = LHS;
2333 else if (isa<IntegerLiteral>(LHS))
2334 Ex = RHS;
2335 else
2336 break;
2337 }
2338
2339 return Ex;
2340}
2341
2342// Warn if the user has made the 'size' argument to strlcpy or strlcat
2343// be the size of the source, instead of the destination.
2344void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
2345 IdentifierInfo *FnName) {
2346
2347 // Don't crash if the user has the wrong number of arguments
2348 if (Call->getNumArgs() != 3)
2349 return;
2350
2351 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
2352 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
2353 const Expr *CompareWithSrc = NULL;
2354
2355 // Look for 'strlcpy(dst, x, sizeof(x))'
2356 if (const Expr *Ex = getSizeOfExprArg(SizeArg))
2357 CompareWithSrc = Ex;
2358 else {
2359 // Look for 'strlcpy(dst, x, strlen(x))'
2360 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
2361 if (SizeCall->isBuiltinCall(Context) == Builtin::BIstrlen
2362 && SizeCall->getNumArgs() == 1)
2363 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
2364 }
2365 }
2366
2367 if (!CompareWithSrc)
2368 return;
2369
2370 // Determine if the argument to sizeof/strlen is equal to the source
2371 // argument. In principle there's all kinds of things you could do
2372 // here, for instance creating an == expression and evaluating it with
2373 // EvaluateAsBooleanCondition, but this uses a more direct technique:
2374 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
2375 if (!SrcArgDRE)
2376 return;
2377
2378 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
2379 if (!CompareWithSrcDRE ||
2380 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
2381 return;
2382
2383 const Expr *OriginalSizeArg = Call->getArg(2);
2384 Diag(CompareWithSrcDRE->getLocStart(), diag::warn_strlcpycat_wrong_size)
2385 << OriginalSizeArg->getSourceRange() << FnName;
2386
2387 // Output a FIXIT hint if the destination is an array (rather than a
2388 // pointer to an array). This could be enhanced to handle some
2389 // pointers if we know the actual size, like if DstArg is 'array+2'
2390 // we could say 'sizeof(array)-2'.
2391 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
Ted Kremenek18db5d42011-08-18 22:48:41 +00002392 QualType DstArgTy = DstArg->getType();
Ted Kremenek6865f772011-08-18 20:55:45 +00002393
Ted Kremenek18db5d42011-08-18 22:48:41 +00002394 // Only handle constant-sized or VLAs, but not flexible members.
2395 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(DstArgTy)) {
2396 // Only issue the FIXIT for arrays of size > 1.
2397 if (CAT->getSize().getSExtValue() <= 1)
2398 return;
2399 } else if (!DstArgTy->isVariableArrayType()) {
2400 return;
Ted Kremenek6865f772011-08-18 20:55:45 +00002401 }
Ted Kremenek18db5d42011-08-18 22:48:41 +00002402
2403 llvm::SmallString<128> sizeString;
2404 llvm::raw_svector_ostream OS(sizeString);
2405 OS << "sizeof(";
Douglas Gregor75acd922011-09-27 23:30:47 +00002406 DstArg->printPretty(OS, Context, 0, getPrintingPolicy());
Ted Kremenek18db5d42011-08-18 22:48:41 +00002407 OS << ")";
2408
2409 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
2410 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
2411 OS.str());
Ted Kremenek6865f772011-08-18 20:55:45 +00002412}
2413
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002414//===--- CHECK: Return Address of Stack Variable --------------------------===//
2415
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002416static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars);
2417static Expr *EvalAddr(Expr* E, SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002418
2419/// CheckReturnStackAddr - Check if a return statement returns the address
2420/// of a stack variable.
2421void
2422Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
2423 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00002424
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002425 Expr *stackE = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002426 SmallVector<DeclRefExpr *, 8> refVars;
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002427
2428 // Perform checking for returned stack addresses, local blocks,
2429 // label addresses or references to temporaries.
John McCall31168b02011-06-15 23:02:42 +00002430 if (lhsType->isPointerType() ||
2431 (!getLangOptions().ObjCAutoRefCount && lhsType->isBlockPointerType())) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002432 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00002433 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002434 stackE = EvalVal(RetValExp, refVars);
2435 }
2436
2437 if (stackE == 0)
2438 return; // Nothing suspicious was found.
2439
2440 SourceLocation diagLoc;
2441 SourceRange diagRange;
2442 if (refVars.empty()) {
2443 diagLoc = stackE->getLocStart();
2444 diagRange = stackE->getSourceRange();
2445 } else {
2446 // We followed through a reference variable. 'stackE' contains the
2447 // problematic expression but we will warn at the return statement pointing
2448 // at the reference variable. We will later display the "trail" of
2449 // reference variables using notes.
2450 diagLoc = refVars[0]->getLocStart();
2451 diagRange = refVars[0]->getSourceRange();
2452 }
2453
2454 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
2455 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
2456 : diag::warn_ret_stack_addr)
2457 << DR->getDecl()->getDeclName() << diagRange;
2458 } else if (isa<BlockExpr>(stackE)) { // local block.
2459 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
2460 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
2461 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
2462 } else { // local temporary.
2463 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
2464 : diag::warn_ret_local_temp_addr)
2465 << diagRange;
2466 }
2467
2468 // Display the "trail" of reference variables that we followed until we
2469 // found the problematic expression using notes.
2470 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
2471 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
2472 // If this var binds to another reference var, show the range of the next
2473 // var, otherwise the var binds to the problematic expression, in which case
2474 // show the range of the expression.
2475 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
2476 : stackE->getSourceRange();
2477 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
2478 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002479 }
2480}
2481
2482/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
2483/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002484/// to a location on the stack, a local block, an address of a label, or a
2485/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002486/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002487/// encounter a subexpression that (1) clearly does not lead to one of the
2488/// above problematic expressions (2) is something we cannot determine leads to
2489/// a problematic expression based on such local checking.
2490///
2491/// Both EvalAddr and EvalVal follow through reference variables to evaluate
2492/// the expression that they point to. Such variables are added to the
2493/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002494///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002495/// EvalAddr processes expressions that are pointers that are used as
2496/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002497/// At the base case of the recursion is a check for the above problematic
2498/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002499///
2500/// This implementation handles:
2501///
2502/// * pointer-to-pointer casts
2503/// * implicit conversions from array references to pointers
2504/// * taking the address of fields
2505/// * arbitrary interplay between "&" and "*" operators
2506/// * pointer arithmetic from an address of a stack variable
2507/// * taking the address of an array element where the array is on the stack
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002508static Expr *EvalAddr(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002509 if (E->isTypeDependent())
2510 return NULL;
2511
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002512 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00002513 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002514 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002515 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00002516 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00002517
Peter Collingbourne91147592011-04-15 00:35:48 +00002518 E = E->IgnoreParens();
2519
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002520 // Our "symbolic interpreter" is just a dispatch off the currently
2521 // viewed AST node. We then recursively traverse the AST by calling
2522 // EvalAddr and EvalVal appropriately.
2523 switch (E->getStmtClass()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002524 case Stmt::DeclRefExprClass: {
2525 DeclRefExpr *DR = cast<DeclRefExpr>(E);
2526
2527 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
2528 // If this is a reference variable, follow through to the expression that
2529 // it points to.
2530 if (V->hasLocalStorage() &&
2531 V->getType()->isReferenceType() && V->hasInit()) {
2532 // Add the reference variable to the "trail".
2533 refVars.push_back(DR);
2534 return EvalAddr(V->getInit(), refVars);
2535 }
2536
2537 return NULL;
2538 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002539
Chris Lattner934edb22007-12-28 05:31:15 +00002540 case Stmt::UnaryOperatorClass: {
2541 // The only unary operator that make sense to handle here
2542 // is AddrOf. All others don't make sense as pointers.
2543 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002544
John McCalle3027922010-08-25 11:45:40 +00002545 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002546 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002547 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002548 return NULL;
2549 }
Mike Stump11289f42009-09-09 15:08:12 +00002550
Chris Lattner934edb22007-12-28 05:31:15 +00002551 case Stmt::BinaryOperatorClass: {
2552 // Handle pointer arithmetic. All other binary operators are not valid
2553 // in this context.
2554 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00002555 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00002556
John McCalle3027922010-08-25 11:45:40 +00002557 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00002558 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00002559
Chris Lattner934edb22007-12-28 05:31:15 +00002560 Expr *Base = B->getLHS();
2561
2562 // Determine which argument is the real pointer base. It could be
2563 // the RHS argument instead of the LHS.
2564 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00002565
Chris Lattner934edb22007-12-28 05:31:15 +00002566 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002567 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002568 }
Steve Naroff2752a172008-09-10 19:17:48 +00002569
Chris Lattner934edb22007-12-28 05:31:15 +00002570 // For conditional operators we need to see if either the LHS or RHS are
2571 // valid DeclRefExpr*s. If one of them is valid, we return it.
2572 case Stmt::ConditionalOperatorClass: {
2573 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002574
Chris Lattner934edb22007-12-28 05:31:15 +00002575 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002576 if (Expr *lhsExpr = C->getLHS()) {
2577 // In C++, we can have a throw-expression, which has 'void' type.
2578 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002579 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002580 return LHS;
2581 }
Chris Lattner934edb22007-12-28 05:31:15 +00002582
Douglas Gregor270b2ef2010-10-21 16:21:08 +00002583 // In C++, we can have a throw-expression, which has 'void' type.
2584 if (C->getRHS()->getType()->isVoidType())
2585 return NULL;
2586
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002587 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002588 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002589
2590 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00002591 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002592 return E; // local block.
2593 return NULL;
2594
2595 case Stmt::AddrLabelExprClass:
2596 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00002597
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002598 // For casts, we need to handle conversions from arrays to
2599 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00002600 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00002601 case Stmt::CStyleCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00002602 case Stmt::CXXFunctionalCastExprClass:
2603 case Stmt::ObjCBridgedCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00002604 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002605 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002606
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002607 if (SubExpr->getType()->isPointerType() ||
2608 SubExpr->getType()->isBlockPointerType() ||
2609 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002610 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002611 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002612 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002613 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00002614 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00002615 }
Mike Stump11289f42009-09-09 15:08:12 +00002616
Chris Lattner934edb22007-12-28 05:31:15 +00002617 // C++ casts. For dynamic casts, static casts, and const casts, we
2618 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00002619 // through the cast. In the case the dynamic cast doesn't fail (and
2620 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00002621 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00002622 // FIXME: The comment about is wrong; we're not always converting
2623 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00002624 // handle references to objects.
2625 case Stmt::CXXStaticCastExprClass:
2626 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00002627 case Stmt::CXXConstCastExprClass:
2628 case Stmt::CXXReinterpretCastExprClass: {
2629 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002630 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002631 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002632 else
2633 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00002634 }
Mike Stump11289f42009-09-09 15:08:12 +00002635
Douglas Gregorfe314812011-06-21 17:03:29 +00002636 case Stmt::MaterializeTemporaryExprClass:
2637 if (Expr *Result = EvalAddr(
2638 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2639 refVars))
2640 return Result;
2641
2642 return E;
2643
Chris Lattner934edb22007-12-28 05:31:15 +00002644 // Everything else: we simply don't reason about them.
2645 default:
2646 return NULL;
2647 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002648}
Mike Stump11289f42009-09-09 15:08:12 +00002649
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002650
2651/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2652/// See the comments for EvalAddr for more details.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002653static Expr *EvalVal(Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002654do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002655 // We should only be called for evaluating non-pointer expressions, or
2656 // expressions with a pointer type that are not used as references but instead
2657 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00002658
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002659 // Our "symbolic interpreter" is just a dispatch off the currently
2660 // viewed AST node. We then recursively traverse the AST by calling
2661 // EvalAddr and EvalVal appropriately.
Peter Collingbourne91147592011-04-15 00:35:48 +00002662
2663 E = E->IgnoreParens();
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002664 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002665 case Stmt::ImplicitCastExprClass: {
2666 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002667 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002668 E = IE->getSubExpr();
2669 continue;
2670 }
2671 return NULL;
2672 }
2673
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002674 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002675 // When we hit a DeclRefExpr we are looking at code that refers to a
2676 // variable's name. If it's not a reference variable we check if it has
2677 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002678 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002679
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002680 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002681 if (V->hasLocalStorage()) {
2682 if (!V->getType()->isReferenceType())
2683 return DR;
2684
2685 // Reference variable, follow through to the expression that
2686 // it points to.
2687 if (V->hasInit()) {
2688 // Add the reference variable to the "trail".
2689 refVars.push_back(DR);
2690 return EvalVal(V->getInit(), refVars);
2691 }
2692 }
Mike Stump11289f42009-09-09 15:08:12 +00002693
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002694 return NULL;
2695 }
Mike Stump11289f42009-09-09 15:08:12 +00002696
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002697 case Stmt::UnaryOperatorClass: {
2698 // The only unary operator that make sense to handle here
2699 // is Deref. All others don't resolve to a "name." This includes
2700 // handling all sorts of rvalues passed to a unary operator.
2701 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002702
John McCalle3027922010-08-25 11:45:40 +00002703 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002704 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002705
2706 return NULL;
2707 }
Mike Stump11289f42009-09-09 15:08:12 +00002708
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002709 case Stmt::ArraySubscriptExprClass: {
2710 // Array subscripts are potential references to data on the stack. We
2711 // retrieve the DeclRefExpr* for the array variable if it indeed
2712 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002713 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002714 }
Mike Stump11289f42009-09-09 15:08:12 +00002715
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002716 case Stmt::ConditionalOperatorClass: {
2717 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002718 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002719 ConditionalOperator *C = cast<ConditionalOperator>(E);
2720
Anders Carlsson801c5c72007-11-30 19:04:31 +00002721 // Handle the GNU extension for missing LHS.
2722 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002723 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002724 return LHS;
2725
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002726 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002727 }
Mike Stump11289f42009-09-09 15:08:12 +00002728
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002729 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002730 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002731 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002732
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002733 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002734 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002735 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002736
2737 // Check whether the member type is itself a reference, in which case
2738 // we're not going to refer to the member, but to what the member refers to.
2739 if (M->getMemberDecl()->getType()->isReferenceType())
2740 return NULL;
2741
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002742 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002743 }
Mike Stump11289f42009-09-09 15:08:12 +00002744
Douglas Gregorfe314812011-06-21 17:03:29 +00002745 case Stmt::MaterializeTemporaryExprClass:
2746 if (Expr *Result = EvalVal(
2747 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
2748 refVars))
2749 return Result;
2750
2751 return E;
2752
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002753 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002754 // Check that we don't return or take the address of a reference to a
2755 // temporary. This is only useful in C++.
2756 if (!E->isTypeDependent() && E->isRValue())
2757 return E;
2758
2759 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002760 return NULL;
2761 }
Ted Kremenekb7861562010-08-04 20:01:07 +00002762} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002763}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002764
2765//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2766
2767/// Check for comparisons of floating point operands using != and ==.
2768/// Issue a warning if these are no self-comparisons, as they are not likely
2769/// to do what the programmer intended.
Richard Trieu82402a02011-09-15 21:56:47 +00002770void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002771 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00002772
Richard Trieu82402a02011-09-15 21:56:47 +00002773 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
2774 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002775
2776 // Special case: check for x == x (which is OK).
2777 // Do not emit warnings for such cases.
2778 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2779 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2780 if (DRL->getDecl() == DRR->getDecl())
2781 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002782
2783
Ted Kremenekeda40e22007-11-29 00:59:04 +00002784 // Special case: check for comparisons against literals that can be exactly
2785 // represented by APFloat. In such cases, do not emit a warning. This
2786 // is a heuristic: often comparison against such literals are used to
2787 // detect if a value in a variable has not changed. This clearly can
2788 // lead to false negatives.
2789 if (EmitWarning) {
2790 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2791 if (FLL->isExact())
2792 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00002793 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00002794 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2795 if (FLR->isExact())
2796 EmitWarning = false;
2797 }
2798 }
Mike Stump11289f42009-09-09 15:08:12 +00002799
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002800 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002801 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002802 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002803 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002804 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002805
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002806 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002807 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002808 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002809 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002810
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002811 // Emit the diagnostic.
2812 if (EmitWarning)
Richard Trieu82402a02011-09-15 21:56:47 +00002813 Diag(Loc, diag::warn_floatingpoint_eq)
2814 << LHS->getSourceRange() << RHS->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002815}
John McCallca01b222010-01-04 23:21:16 +00002816
John McCall70aa5392010-01-06 05:24:50 +00002817//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2818//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00002819
John McCall70aa5392010-01-06 05:24:50 +00002820namespace {
John McCallca01b222010-01-04 23:21:16 +00002821
John McCall70aa5392010-01-06 05:24:50 +00002822/// Structure recording the 'active' range of an integer-valued
2823/// expression.
2824struct IntRange {
2825 /// The number of bits active in the int.
2826 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00002827
John McCall70aa5392010-01-06 05:24:50 +00002828 /// True if the int is known not to have negative values.
2829 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00002830
John McCall70aa5392010-01-06 05:24:50 +00002831 IntRange(unsigned Width, bool NonNegative)
2832 : Width(Width), NonNegative(NonNegative)
2833 {}
John McCallca01b222010-01-04 23:21:16 +00002834
John McCall817d4af2010-11-10 23:38:19 +00002835 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00002836 static IntRange forBoolType() {
2837 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00002838 }
2839
John McCall817d4af2010-11-10 23:38:19 +00002840 /// Returns the range of an opaque value of the given integral type.
2841 static IntRange forValueOfType(ASTContext &C, QualType T) {
2842 return forValueOfCanonicalType(C,
2843 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00002844 }
2845
John McCall817d4af2010-11-10 23:38:19 +00002846 /// Returns the range of an opaque value of a canonical integral type.
2847 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00002848 assert(T->isCanonicalUnqualified());
2849
2850 if (const VectorType *VT = dyn_cast<VectorType>(T))
2851 T = VT->getElementType().getTypePtr();
2852 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2853 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00002854
John McCall18a2c2c2010-11-09 22:22:12 +00002855 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00002856 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2857 EnumDecl *Enum = ET->getDecl();
John McCallf937c022011-10-07 06:10:15 +00002858 if (!Enum->isCompleteDefinition())
John McCall18a2c2c2010-11-09 22:22:12 +00002859 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2860
John McCallcc7e5bf2010-05-06 08:58:33 +00002861 unsigned NumPositive = Enum->getNumPositiveBits();
2862 unsigned NumNegative = Enum->getNumNegativeBits();
2863
2864 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2865 }
John McCall70aa5392010-01-06 05:24:50 +00002866
2867 const BuiltinType *BT = cast<BuiltinType>(T);
2868 assert(BT->isInteger());
2869
2870 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2871 }
2872
John McCall817d4af2010-11-10 23:38:19 +00002873 /// Returns the "target" range of a canonical integral type, i.e.
2874 /// the range of values expressible in the type.
2875 ///
2876 /// This matches forValueOfCanonicalType except that enums have the
2877 /// full range of their type, not the range of their enumerators.
2878 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2879 assert(T->isCanonicalUnqualified());
2880
2881 if (const VectorType *VT = dyn_cast<VectorType>(T))
2882 T = VT->getElementType().getTypePtr();
2883 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2884 T = CT->getElementType().getTypePtr();
2885 if (const EnumType *ET = dyn_cast<EnumType>(T))
Douglas Gregor3168dcf2011-09-08 23:29:05 +00002886 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
John McCall817d4af2010-11-10 23:38:19 +00002887
2888 const BuiltinType *BT = cast<BuiltinType>(T);
2889 assert(BT->isInteger());
2890
2891 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2892 }
2893
2894 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00002895 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00002896 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00002897 L.NonNegative && R.NonNegative);
2898 }
2899
John McCall817d4af2010-11-10 23:38:19 +00002900 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00002901 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00002902 return IntRange(std::min(L.Width, R.Width),
2903 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00002904 }
2905};
2906
2907IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2908 if (value.isSigned() && value.isNegative())
2909 return IntRange(value.getMinSignedBits(), false);
2910
2911 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002912 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002913
2914 // isNonNegative() just checks the sign bit without considering
2915 // signedness.
2916 return IntRange(value.getActiveBits(), true);
2917}
2918
John McCall74430522010-01-06 22:57:21 +00002919IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00002920 unsigned MaxWidth) {
2921 if (result.isInt())
2922 return GetValueRange(C, result.getInt(), MaxWidth);
2923
2924 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00002925 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2926 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2927 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2928 R = IntRange::join(R, El);
2929 }
John McCall70aa5392010-01-06 05:24:50 +00002930 return R;
2931 }
2932
2933 if (result.isComplexInt()) {
2934 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2935 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2936 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00002937 }
2938
2939 // This can happen with lossless casts to intptr_t of "based" lvalues.
2940 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00002941 // FIXME: The only reason we need to pass the type in here is to get
2942 // the sign right on this one case. It would be nice if APValue
2943 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00002944 assert(result.isLValue());
Douglas Gregor61b6e492011-05-21 16:28:01 +00002945 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
John McCall263a48b2010-01-04 23:31:57 +00002946}
John McCall70aa5392010-01-06 05:24:50 +00002947
2948/// Pseudo-evaluate the given integer expression, estimating the
2949/// range of values it might take.
2950///
2951/// \param MaxWidth - the width to which the value will be truncated
2952IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2953 E = E->IgnoreParens();
2954
2955 // Try a full evaluation first.
2956 Expr::EvalResult result;
2957 if (E->Evaluate(result, C))
John McCall74430522010-01-06 22:57:21 +00002958 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002959
2960 // I think we only want to look through implicit casts here; if the
2961 // user has an explicit widening cast, we should treat the value as
2962 // being of the new, wider type.
2963 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002964 if (CE->getCastKind() == CK_NoOp)
John McCall70aa5392010-01-06 05:24:50 +00002965 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2966
John McCall817d4af2010-11-10 23:38:19 +00002967 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00002968
John McCalle3027922010-08-25 11:45:40 +00002969 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00002970
John McCall70aa5392010-01-06 05:24:50 +00002971 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00002972 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00002973 return OutputTypeRange;
2974
2975 IntRange SubRange
2976 = GetExprRange(C, CE->getSubExpr(),
2977 std::min(MaxWidth, OutputTypeRange.Width));
2978
2979 // Bail out if the subexpr's range is as wide as the cast type.
2980 if (SubRange.Width >= OutputTypeRange.Width)
2981 return OutputTypeRange;
2982
2983 // Otherwise, we take the smaller width, and we're non-negative if
2984 // either the output type or the subexpr is.
2985 return IntRange(SubRange.Width,
2986 SubRange.NonNegative || OutputTypeRange.NonNegative);
2987 }
2988
2989 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2990 // If we can fold the condition, just take that operand.
2991 bool CondResult;
2992 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2993 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2994 : CO->getFalseExpr(),
2995 MaxWidth);
2996
2997 // Otherwise, conservatively merge.
2998 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2999 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
3000 return IntRange::join(L, R);
3001 }
3002
3003 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3004 switch (BO->getOpcode()) {
3005
3006 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00003007 case BO_LAnd:
3008 case BO_LOr:
3009 case BO_LT:
3010 case BO_GT:
3011 case BO_LE:
3012 case BO_GE:
3013 case BO_EQ:
3014 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00003015 return IntRange::forBoolType();
3016
John McCallc3688382011-07-13 06:35:24 +00003017 // The type of the assignments is the type of the LHS, so the RHS
3018 // is not necessarily the same type.
John McCalle3027922010-08-25 11:45:40 +00003019 case BO_MulAssign:
3020 case BO_DivAssign:
3021 case BO_RemAssign:
3022 case BO_AddAssign:
3023 case BO_SubAssign:
John McCallc3688382011-07-13 06:35:24 +00003024 case BO_XorAssign:
3025 case BO_OrAssign:
3026 // TODO: bitfields?
John McCall817d4af2010-11-10 23:38:19 +00003027 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00003028
John McCallc3688382011-07-13 06:35:24 +00003029 // Simple assignments just pass through the RHS, which will have
3030 // been coerced to the LHS type.
3031 case BO_Assign:
3032 // TODO: bitfields?
3033 return GetExprRange(C, BO->getRHS(), MaxWidth);
3034
John McCall70aa5392010-01-06 05:24:50 +00003035 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003036 case BO_PtrMemD:
3037 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00003038 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003039
John McCall2ce81ad2010-01-06 22:07:33 +00003040 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00003041 case BO_And:
3042 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00003043 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
3044 GetExprRange(C, BO->getRHS(), MaxWidth));
3045
John McCall70aa5392010-01-06 05:24:50 +00003046 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00003047 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00003048 // ...except that we want to treat '1 << (blah)' as logically
3049 // positive. It's an important idiom.
3050 if (IntegerLiteral *I
3051 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
3052 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00003053 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00003054 return IntRange(R.Width, /*NonNegative*/ true);
3055 }
3056 }
3057 // fallthrough
3058
John McCalle3027922010-08-25 11:45:40 +00003059 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00003060 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003061
John McCall2ce81ad2010-01-06 22:07:33 +00003062 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00003063 case BO_Shr:
3064 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00003065 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3066
3067 // If the shift amount is a positive constant, drop the width by
3068 // that much.
3069 llvm::APSInt shift;
3070 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
3071 shift.isNonNegative()) {
3072 unsigned zext = shift.getZExtValue();
3073 if (zext >= L.Width)
3074 L.Width = (L.NonNegative ? 0 : 1);
3075 else
3076 L.Width -= zext;
3077 }
3078
3079 return L;
3080 }
3081
3082 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00003083 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00003084 return GetExprRange(C, BO->getRHS(), MaxWidth);
3085
John McCall2ce81ad2010-01-06 22:07:33 +00003086 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00003087 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00003088 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00003089 return IntRange::forValueOfType(C, E->getType());
John McCall51431812011-07-14 22:39:48 +00003090 break;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00003091
John McCall51431812011-07-14 22:39:48 +00003092 // The width of a division result is mostly determined by the size
3093 // of the LHS.
3094 case BO_Div: {
3095 // Don't 'pre-truncate' the operands.
3096 unsigned opWidth = C.getIntWidth(E->getType());
3097 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3098
3099 // If the divisor is constant, use that.
3100 llvm::APSInt divisor;
3101 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
3102 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor))
3103 if (log2 >= L.Width)
3104 L.Width = (L.NonNegative ? 0 : 1);
3105 else
3106 L.Width = std::min(L.Width - log2, MaxWidth);
3107 return L;
3108 }
3109
3110 // Otherwise, just use the LHS's width.
3111 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3112 return IntRange(L.Width, L.NonNegative && R.NonNegative);
3113 }
3114
3115 // The result of a remainder can't be larger than the result of
3116 // either side.
3117 case BO_Rem: {
3118 // Don't 'pre-truncate' the operands.
3119 unsigned opWidth = C.getIntWidth(E->getType());
3120 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
3121 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
3122
3123 IntRange meet = IntRange::meet(L, R);
3124 meet.Width = std::min(meet.Width, MaxWidth);
3125 return meet;
3126 }
3127
3128 // The default behavior is okay for these.
3129 case BO_Mul:
3130 case BO_Add:
3131 case BO_Xor:
3132 case BO_Or:
John McCall70aa5392010-01-06 05:24:50 +00003133 break;
3134 }
3135
John McCall51431812011-07-14 22:39:48 +00003136 // The default case is to treat the operation as if it were closed
3137 // on the narrowest type that encompasses both operands.
John McCall70aa5392010-01-06 05:24:50 +00003138 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
3139 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
3140 return IntRange::join(L, R);
3141 }
3142
3143 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
3144 switch (UO->getOpcode()) {
3145 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00003146 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00003147 return IntRange::forBoolType();
3148
3149 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00003150 case UO_Deref:
3151 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00003152 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003153
3154 default:
3155 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
3156 }
3157 }
Douglas Gregor882211c2010-04-28 22:16:22 +00003158
3159 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00003160 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00003161 }
John McCall70aa5392010-01-06 05:24:50 +00003162
Richard Smithcaf33902011-10-10 18:28:20 +00003163 if (FieldDecl *BitField = E->getBitField())
3164 return IntRange(BitField->getBitWidthValue(C),
Douglas Gregor61b6e492011-05-21 16:28:01 +00003165 BitField->getType()->isUnsignedIntegerOrEnumerationType());
John McCall70aa5392010-01-06 05:24:50 +00003166
John McCall817d4af2010-11-10 23:38:19 +00003167 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00003168}
John McCall263a48b2010-01-04 23:31:57 +00003169
John McCallcc7e5bf2010-05-06 08:58:33 +00003170IntRange GetExprRange(ASTContext &C, Expr *E) {
3171 return GetExprRange(C, E, C.getIntWidth(E->getType()));
3172}
3173
John McCall263a48b2010-01-04 23:31:57 +00003174/// Checks whether the given value, which currently has the given
3175/// source semantics, has the same value when coerced through the
3176/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00003177bool IsSameFloatAfterCast(const llvm::APFloat &value,
3178 const llvm::fltSemantics &Src,
3179 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003180 llvm::APFloat truncated = value;
3181
3182 bool ignored;
3183 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
3184 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
3185
3186 return truncated.bitwiseIsEqual(value);
3187}
3188
3189/// Checks whether the given value, which currently has the given
3190/// source semantics, has the same value when coerced through the
3191/// target semantics.
3192///
3193/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00003194bool IsSameFloatAfterCast(const APValue &value,
3195 const llvm::fltSemantics &Src,
3196 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00003197 if (value.isFloat())
3198 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
3199
3200 if (value.isVector()) {
3201 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
3202 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
3203 return false;
3204 return true;
3205 }
3206
3207 assert(value.isComplexFloat());
3208 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
3209 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
3210}
3211
John McCallacf0ee52010-10-08 02:01:28 +00003212void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003213
Ted Kremenek6274be42010-09-23 21:43:44 +00003214static bool IsZero(Sema &S, Expr *E) {
3215 // Suppress cases where we are comparing against an enum constant.
3216 if (const DeclRefExpr *DR =
3217 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
3218 if (isa<EnumConstantDecl>(DR->getDecl()))
3219 return false;
3220
3221 // Suppress cases where the '0' value is expanded from a macro.
3222 if (E->getLocStart().isMacroID())
3223 return false;
3224
John McCallcc7e5bf2010-05-06 08:58:33 +00003225 llvm::APSInt Value;
3226 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
3227}
3228
John McCall2551c1b2010-10-06 00:25:24 +00003229static bool HasEnumType(Expr *E) {
3230 // Strip off implicit integral promotions.
3231 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003232 if (ICE->getCastKind() != CK_IntegralCast &&
3233 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00003234 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00003235 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00003236 }
3237
3238 return E->getType()->isEnumeralType();
3239}
3240
John McCallcc7e5bf2010-05-06 08:58:33 +00003241void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003242 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00003243 if (E->isValueDependent())
3244 return;
3245
John McCalle3027922010-08-25 11:45:40 +00003246 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003247 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003248 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003249 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003250 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003251 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003252 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003253 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003254 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003255 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003256 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003257 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00003258 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003259 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00003260 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00003261 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
3262 }
3263}
3264
3265/// Analyze the operands of the given comparison. Implements the
3266/// fallback case from AnalyzeComparison.
3267void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00003268 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3269 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00003270}
John McCall263a48b2010-01-04 23:31:57 +00003271
John McCallca01b222010-01-04 23:21:16 +00003272/// \brief Implements -Wsign-compare.
3273///
Richard Trieu82402a02011-09-15 21:56:47 +00003274/// \param E the binary operator to check for warnings
John McCallcc7e5bf2010-05-06 08:58:33 +00003275void AnalyzeComparison(Sema &S, BinaryOperator *E) {
3276 // The type the comparison is being performed in.
3277 QualType T = E->getLHS()->getType();
3278 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
3279 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00003280
John McCallcc7e5bf2010-05-06 08:58:33 +00003281 // We don't do anything special if this isn't an unsigned integral
3282 // comparison: we're only interested in integral comparisons, and
3283 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00003284 //
3285 // We also don't care about value-dependent expressions or expressions
3286 // whose result is a constant.
3287 if (!T->hasUnsignedIntegerRepresentation()
3288 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00003289 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00003290
Richard Trieu82402a02011-09-15 21:56:47 +00003291 Expr *LHS = E->getLHS()->IgnoreParenImpCasts();
3292 Expr *RHS = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00003293
John McCallcc7e5bf2010-05-06 08:58:33 +00003294 // Check to see if one of the (unmodified) operands is of different
3295 // signedness.
3296 Expr *signedOperand, *unsignedOperand;
Richard Trieu82402a02011-09-15 21:56:47 +00003297 if (LHS->getType()->hasSignedIntegerRepresentation()) {
3298 assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00003299 "unsigned comparison between two signed integer expressions?");
Richard Trieu82402a02011-09-15 21:56:47 +00003300 signedOperand = LHS;
3301 unsignedOperand = RHS;
3302 } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
3303 signedOperand = RHS;
3304 unsignedOperand = LHS;
John McCallca01b222010-01-04 23:21:16 +00003305 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00003306 CheckTrivialUnsignedComparison(S, E);
3307 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003308 }
3309
John McCallcc7e5bf2010-05-06 08:58:33 +00003310 // Otherwise, calculate the effective range of the signed operand.
3311 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00003312
John McCallcc7e5bf2010-05-06 08:58:33 +00003313 // Go ahead and analyze implicit conversions in the operands. Note
3314 // that we skip the implicit conversions on both sides.
Richard Trieu82402a02011-09-15 21:56:47 +00003315 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
3316 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00003317
John McCallcc7e5bf2010-05-06 08:58:33 +00003318 // If the signed range is non-negative, -Wsign-compare won't fire,
3319 // but we should still check for comparisons which are always true
3320 // or false.
3321 if (signedRange.NonNegative)
3322 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00003323
3324 // For (in)equality comparisons, if the unsigned operand is a
3325 // constant which cannot collide with a overflowed signed operand,
3326 // then reinterpreting the signed operand as unsigned will not
3327 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00003328 if (E->isEqualityOp()) {
3329 unsigned comparisonWidth = S.Context.getIntWidth(T);
3330 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00003331
John McCallcc7e5bf2010-05-06 08:58:33 +00003332 // We should never be unable to prove that the unsigned operand is
3333 // non-negative.
3334 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
3335
3336 if (unsignedRange.Width < comparisonWidth)
3337 return;
3338 }
3339
3340 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
Richard Trieu82402a02011-09-15 21:56:47 +00003341 << LHS->getType() << RHS->getType()
3342 << LHS->getSourceRange() << RHS->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00003343}
3344
John McCall1f425642010-11-11 03:21:53 +00003345/// Analyzes an attempt to assign the given value to a bitfield.
3346///
3347/// Returns true if there was something fishy about the attempt.
3348bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
3349 SourceLocation InitLoc) {
3350 assert(Bitfield->isBitField());
3351 if (Bitfield->isInvalidDecl())
3352 return false;
3353
John McCalldeebbcf2010-11-11 05:33:51 +00003354 // White-list bool bitfields.
3355 if (Bitfield->getType()->isBooleanType())
3356 return false;
3357
Douglas Gregor789adec2011-02-04 13:09:01 +00003358 // Ignore value- or type-dependent expressions.
3359 if (Bitfield->getBitWidth()->isValueDependent() ||
3360 Bitfield->getBitWidth()->isTypeDependent() ||
3361 Init->isValueDependent() ||
3362 Init->isTypeDependent())
3363 return false;
3364
John McCall1f425642010-11-11 03:21:53 +00003365 Expr *OriginalInit = Init->IgnoreParenImpCasts();
3366
John McCall1f425642010-11-11 03:21:53 +00003367 Expr::EvalResult InitValue;
Richard Smithcaf33902011-10-10 18:28:20 +00003368 if (!OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall1f425642010-11-11 03:21:53 +00003369 !InitValue.Val.isInt())
3370 return false;
3371
3372 const llvm::APSInt &Value = InitValue.Val.getInt();
3373 unsigned OriginalWidth = Value.getBitWidth();
Richard Smithcaf33902011-10-10 18:28:20 +00003374 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
John McCall1f425642010-11-11 03:21:53 +00003375
3376 if (OriginalWidth <= FieldWidth)
3377 return false;
3378
Jay Foad6d4db0c2010-12-07 08:25:34 +00003379 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall1f425642010-11-11 03:21:53 +00003380
3381 // It's fairly common to write values into signed bitfields
3382 // that, if sign-extended, would end up becoming a different
3383 // value. We don't want to warn about that.
3384 if (Value.isSigned() && Value.isNegative())
Jay Foad6d4db0c2010-12-07 08:25:34 +00003385 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003386 else
Jay Foad6d4db0c2010-12-07 08:25:34 +00003387 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00003388
3389 if (Value == TruncatedValue)
3390 return false;
3391
3392 std::string PrettyValue = Value.toString(10);
3393 std::string PrettyTrunc = TruncatedValue.toString(10);
3394
3395 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
3396 << PrettyValue << PrettyTrunc << OriginalInit->getType()
3397 << Init->getSourceRange();
3398
3399 return true;
3400}
3401
John McCalld2a53122010-11-09 23:24:47 +00003402/// Analyze the given simple or compound assignment for warning-worthy
3403/// operations.
3404void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
3405 // Just recurse on the LHS.
3406 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
3407
3408 // We want to recurse on the RHS as normal unless we're assigning to
3409 // a bitfield.
3410 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00003411 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
3412 E->getOperatorLoc())) {
3413 // Recurse, ignoring any implicit conversions on the RHS.
3414 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
3415 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00003416 }
3417 }
3418
3419 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
3420}
3421
John McCall263a48b2010-01-04 23:31:57 +00003422/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003423void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
3424 SourceLocation CContext, unsigned diag) {
3425 S.Diag(E->getExprLoc(), diag)
3426 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
3427}
3428
Chandler Carruth7f3654f2011-04-05 06:47:57 +00003429/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
3430void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
3431 unsigned diag) {
3432 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
3433}
3434
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003435/// Diagnose an implicit cast from a literal expression. Does not warn when the
3436/// cast wouldn't lose information.
Chandler Carruth016ef402011-04-10 08:36:24 +00003437void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
3438 SourceLocation CContext) {
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003439 // Try to convert the literal exactly to an integer. If we can, don't warn.
Chandler Carruth016ef402011-04-10 08:36:24 +00003440 bool isExact = false;
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003441 const llvm::APFloat &Value = FL->getValue();
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +00003442 llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
3443 T->hasUnsignedIntegerRepresentation());
3444 if (Value.convertToInteger(IntegerValue,
Chandler Carruth016ef402011-04-10 08:36:24 +00003445 llvm::APFloat::rmTowardZero, &isExact)
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003446 == llvm::APFloat::opOK && isExact)
Chandler Carruth016ef402011-04-10 08:36:24 +00003447 return;
3448
Matt Beaumont-Gayc6221632011-10-14 15:36:25 +00003449 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
3450 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
Chandler Carruth016ef402011-04-10 08:36:24 +00003451}
3452
John McCall18a2c2c2010-11-09 22:22:12 +00003453std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
3454 if (!Range.Width) return "0";
3455
3456 llvm::APSInt ValueInRange = Value;
3457 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00003458 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00003459 return ValueInRange.toString(10);
3460}
3461
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003462static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
3463 SourceManager &smgr = S.Context.getSourceManager();
3464 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
3465}
Chandler Carruth016ef402011-04-10 08:36:24 +00003466
John McCallcc7e5bf2010-05-06 08:58:33 +00003467void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003468 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003469 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00003470
John McCallcc7e5bf2010-05-06 08:58:33 +00003471 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
3472 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
3473 if (Source == Target) return;
3474 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00003475
Chandler Carruthc22845a2011-07-26 05:40:03 +00003476 // If the conversion context location is invalid don't complain. We also
3477 // don't want to emit a warning if the issue occurs from the expansion of
3478 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
3479 // delay this check as long as possible. Once we detect we are in that
3480 // scenario, we just return.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003481 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00003482 return;
3483
Richard Trieu021baa32011-09-23 20:10:00 +00003484 // Diagnose implicit casts to bool.
3485 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
3486 if (isa<StringLiteral>(E))
3487 // Warn on string literal to bool. Checks for string literals in logical
3488 // expressions, for instances, assert(0 && "error here"), is prevented
3489 // by a check in AnalyzeImplicitConversions().
3490 return DiagnoseImpCast(S, E, T, CC,
3491 diag::warn_impcast_string_literal_to_bool);
David Blaikie7833b7d2011-09-29 04:06:47 +00003492 return; // Other casts to bool are not checked.
Richard Trieu021baa32011-09-23 20:10:00 +00003493 }
John McCall263a48b2010-01-04 23:31:57 +00003494
3495 // Strip vector types.
3496 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003497 if (!isa<VectorType>(Target)) {
3498 if (isFromSystemMacro(S, CC))
3499 return;
John McCallacf0ee52010-10-08 02:01:28 +00003500 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003501 }
Chris Lattneree7286f2011-06-14 04:51:15 +00003502
3503 // If the vector cast is cast between two vectors of the same size, it is
3504 // a bitcast, not a conversion.
3505 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
3506 return;
John McCall263a48b2010-01-04 23:31:57 +00003507
3508 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
3509 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
3510 }
3511
3512 // Strip complex types.
3513 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003514 if (!isa<ComplexType>(Target)) {
3515 if (isFromSystemMacro(S, CC))
3516 return;
3517
John McCallacf0ee52010-10-08 02:01:28 +00003518 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003519 }
John McCall263a48b2010-01-04 23:31:57 +00003520
3521 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
3522 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
3523 }
3524
3525 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
3526 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
3527
3528 // If the source is floating point...
3529 if (SourceBT && SourceBT->isFloatingPoint()) {
3530 // ...and the target is floating point...
3531 if (TargetBT && TargetBT->isFloatingPoint()) {
3532 // ...then warn if we're dropping FP rank.
3533
3534 // Builtin FP kinds are ordered by increasing FP rank.
3535 if (SourceBT->getKind() > TargetBT->getKind()) {
3536 // Don't warn about float constants that are precisely
3537 // representable in the target type.
3538 Expr::EvalResult result;
John McCallcc7e5bf2010-05-06 08:58:33 +00003539 if (E->Evaluate(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00003540 // Value might be a float, a float vector, or a float complex.
3541 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00003542 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
3543 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00003544 return;
3545 }
3546
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003547 if (isFromSystemMacro(S, CC))
3548 return;
3549
John McCallacf0ee52010-10-08 02:01:28 +00003550 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00003551 }
3552 return;
3553 }
3554
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003555 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00003556 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003557 if (isFromSystemMacro(S, CC))
3558 return;
3559
Chandler Carruth22c7a792011-02-17 11:05:49 +00003560 Expr *InnerE = E->IgnoreParenImpCasts();
Matt Beaumont-Gay042ce8e2011-09-08 22:30:47 +00003561 // We also want to warn on, e.g., "int i = -1.234"
3562 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
3563 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
3564 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
3565
Chandler Carruth016ef402011-04-10 08:36:24 +00003566 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
3567 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carruth22c7a792011-02-17 11:05:49 +00003568 } else {
3569 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
3570 }
3571 }
John McCall263a48b2010-01-04 23:31:57 +00003572
3573 return;
3574 }
3575
John McCall70aa5392010-01-06 05:24:50 +00003576 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00003577 return;
3578
Richard Trieubeaf3452011-05-29 19:59:02 +00003579 if ((E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)
3580 == Expr::NPCK_GNUNull) && Target->isIntegerType()) {
3581 S.Diag(E->getExprLoc(), diag::warn_impcast_null_pointer_to_integer)
3582 << E->getSourceRange() << clang::SourceRange(CC);
3583 return;
3584 }
3585
John McCallcc7e5bf2010-05-06 08:58:33 +00003586 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00003587 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00003588
3589 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00003590 // If the source is a constant, use a default-on diagnostic.
3591 // TODO: this should happen for bitfield stores, too.
3592 llvm::APSInt Value(32);
3593 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003594 if (isFromSystemMacro(S, CC))
3595 return;
3596
John McCall18a2c2c2010-11-09 22:22:12 +00003597 std::string PrettySourceValue = Value.toString(10);
3598 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
3599
3600 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
3601 << PrettySourceValue << PrettyTargetValue
3602 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
3603 return;
3604 }
3605
Chris Lattneree7286f2011-06-14 04:51:15 +00003606 // People want to build with -Wshorten-64-to-32 and not -Wconversion.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003607 if (isFromSystemMacro(S, CC))
3608 return;
3609
John McCall70aa5392010-01-06 05:24:50 +00003610 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00003611 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
3612 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00003613 }
3614
3615 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
3616 (!TargetRange.NonNegative && SourceRange.NonNegative &&
3617 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003618
3619 if (isFromSystemMacro(S, CC))
3620 return;
3621
John McCallcc7e5bf2010-05-06 08:58:33 +00003622 unsigned DiagID = diag::warn_impcast_integer_sign;
3623
3624 // Traditionally, gcc has warned about this under -Wsign-compare.
3625 // We also want to warn about it in -Wconversion.
3626 // So if -Wconversion is off, use a completely identical diagnostic
3627 // in the sign-compare group.
3628 // The conditional-checking code will
3629 if (ICContext) {
3630 DiagID = diag::warn_impcast_integer_sign_conditional;
3631 *ICContext = true;
3632 }
3633
John McCallacf0ee52010-10-08 02:01:28 +00003634 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00003635 }
3636
Douglas Gregora78f1932011-02-22 02:45:07 +00003637 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00003638 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3639 // type, to give us better diagnostics.
3640 QualType SourceType = E->getType();
3641 if (!S.getLangOptions().CPlusPlus) {
3642 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3643 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3644 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3645 SourceType = S.Context.getTypeDeclType(Enum);
3646 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3647 }
3648 }
3649
Douglas Gregora78f1932011-02-22 02:45:07 +00003650 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3651 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3652 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003653 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregora78f1932011-02-22 02:45:07 +00003654 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smithdda56e42011-04-15 14:24:37 +00003655 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003656 SourceEnum != TargetEnum) {
3657 if (isFromSystemMacro(S, CC))
3658 return;
3659
Douglas Gregor364f7db2011-03-12 00:14:31 +00003660 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00003661 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00003662 }
Douglas Gregora78f1932011-02-22 02:45:07 +00003663
John McCall263a48b2010-01-04 23:31:57 +00003664 return;
3665}
3666
John McCallcc7e5bf2010-05-06 08:58:33 +00003667void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3668
3669void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00003670 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003671 E = E->IgnoreParenImpCasts();
3672
3673 if (isa<ConditionalOperator>(E))
3674 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3675
John McCallacf0ee52010-10-08 02:01:28 +00003676 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003677 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003678 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00003679 return;
3680}
3681
3682void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00003683 SourceLocation CC = E->getQuestionLoc();
3684
3685 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003686
3687 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00003688 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3689 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003690
3691 // If -Wconversion would have warned about either of the candidates
3692 // for a signedness conversion to the context type...
3693 if (!Suspicious) return;
3694
3695 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003696 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3697 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00003698 return;
3699
John McCallcc7e5bf2010-05-06 08:58:33 +00003700 // ...then check whether it would have warned about either of the
3701 // candidates for a signedness conversion to the condition type.
Richard Trieubb43dec2011-07-21 02:46:28 +00003702 if (E->getType() == T) return;
3703
3704 Suspicious = false;
3705 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
3706 E->getType(), CC, &Suspicious);
3707 if (!Suspicious)
3708 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00003709 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003710}
3711
3712/// AnalyzeImplicitConversions - Find and report any interesting
3713/// implicit conversions in the given expression. There are a couple
3714/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003715void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003716 QualType T = OrigE->getType();
3717 Expr *E = OrigE->IgnoreParenImpCasts();
3718
Douglas Gregor6e8da6a2011-10-10 17:38:18 +00003719 if (E->isTypeDependent() || E->isValueDependent())
3720 return;
3721
John McCallcc7e5bf2010-05-06 08:58:33 +00003722 // For conditional operators, we analyze the arguments as if they
3723 // were being fed directly into the output.
3724 if (isa<ConditionalOperator>(E)) {
3725 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3726 CheckConditionalOperator(S, CO, T);
3727 return;
3728 }
3729
3730 // Go ahead and check any implicit conversions we might have skipped.
3731 // The non-canonical typecheck is just an optimization;
3732 // CheckImplicitConversion will filter out dead implicit conversions.
3733 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003734 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003735
3736 // Now continue drilling into this expression.
3737
3738 // Skip past explicit casts.
3739 if (isa<ExplicitCastExpr>(E)) {
3740 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00003741 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003742 }
3743
John McCalld2a53122010-11-09 23:24:47 +00003744 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3745 // Do a somewhat different check with comparison operators.
3746 if (BO->isComparisonOp())
3747 return AnalyzeComparison(S, BO);
3748
3749 // And with assignments and compound assignments.
3750 if (BO->isAssignmentOp())
3751 return AnalyzeAssignment(S, BO);
3752 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003753
3754 // These break the otherwise-useful invariant below. Fortunately,
3755 // we don't really need to recurse into them, because any internal
3756 // expressions should have been analyzed already when they were
3757 // built into statements.
3758 if (isa<StmtExpr>(E)) return;
3759
3760 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003761 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00003762
3763 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00003764 CC = E->getExprLoc();
Richard Trieu021baa32011-09-23 20:10:00 +00003765 BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
3766 bool IsLogicalOperator = BO && BO->isLogicalOp();
3767 for (Stmt::child_range I = E->children(); I; ++I) {
3768 Expr *ChildExpr = cast<Expr>(*I);
3769 if (IsLogicalOperator &&
3770 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
3771 // Ignore checking string literals that are in logical operators.
3772 continue;
3773 AnalyzeImplicitConversions(S, ChildExpr, CC);
3774 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003775}
3776
3777} // end anonymous namespace
3778
3779/// Diagnoses "dangerous" implicit conversions within the given
3780/// expression (which is a full expression). Implements -Wconversion
3781/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003782///
3783/// \param CC the "context" location of the implicit conversion, i.e.
3784/// the most location of the syntactic entity requiring the implicit
3785/// conversion
3786void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003787 // Don't diagnose in unevaluated contexts.
3788 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3789 return;
3790
3791 // Don't diagnose for value- or type-dependent expressions.
3792 if (E->isTypeDependent() || E->isValueDependent())
3793 return;
3794
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003795 // Check for array bounds violations in cases where the check isn't triggered
3796 // elsewhere for other Expr types (like BinaryOperators), e.g. when an
3797 // ArraySubscriptExpr is on the RHS of a variable initialization.
3798 CheckArrayAccess(E);
3799
John McCallacf0ee52010-10-08 02:01:28 +00003800 // This is not the right CC for (e.g.) a variable initialization.
3801 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003802}
3803
John McCall1f425642010-11-11 03:21:53 +00003804void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3805 FieldDecl *BitField,
3806 Expr *Init) {
3807 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3808}
3809
Mike Stump0c2ec772010-01-21 03:59:47 +00003810/// CheckParmsForFunctionDef - Check that the parameters of the given
3811/// function are appropriate for the definition of a function. This
3812/// takes care of any checks that cannot be performed on the
3813/// declaration itself, e.g., that the types of each of the function
3814/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00003815bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3816 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00003817 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00003818 for (; P != PEnd; ++P) {
3819 ParmVarDecl *Param = *P;
3820
Mike Stump0c2ec772010-01-21 03:59:47 +00003821 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3822 // function declarator that is part of a function definition of
3823 // that function shall not have incomplete type.
3824 //
3825 // This is also C++ [dcl.fct]p6.
3826 if (!Param->isInvalidDecl() &&
3827 RequireCompleteType(Param->getLocation(), Param->getType(),
3828 diag::err_typecheck_decl_incomplete_type)) {
3829 Param->setInvalidDecl();
3830 HasInvalidParm = true;
3831 }
3832
3833 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3834 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00003835 if (CheckParameterNames &&
3836 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00003837 !Param->isImplicit() &&
3838 !getLangOptions().CPlusPlus)
3839 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00003840
3841 // C99 6.7.5.3p12:
3842 // If the function declarator is not part of a definition of that
3843 // function, parameters may have incomplete type and may use the [*]
3844 // notation in their sequences of declarator specifiers to specify
3845 // variable length array types.
3846 QualType PType = Param->getOriginalType();
3847 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3848 if (AT->getSizeModifier() == ArrayType::Star) {
3849 // FIXME: This diagnosic should point the the '[*]' if source-location
3850 // information is added for it.
3851 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3852 }
3853 }
Mike Stump0c2ec772010-01-21 03:59:47 +00003854 }
3855
3856 return HasInvalidParm;
3857}
John McCall2b5c1b22010-08-12 21:44:57 +00003858
3859/// CheckCastAlign - Implements -Wcast-align, which warns when a
3860/// pointer cast increases the alignment requirements.
3861void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3862 // This is actually a lot of work to potentially be doing on every
3863 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003864 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3865 TRange.getBegin())
David Blaikie9c902b52011-09-25 23:23:43 +00003866 == DiagnosticsEngine::Ignored)
John McCall2b5c1b22010-08-12 21:44:57 +00003867 return;
3868
3869 // Ignore dependent types.
3870 if (T->isDependentType() || Op->getType()->isDependentType())
3871 return;
3872
3873 // Require that the destination be a pointer type.
3874 const PointerType *DestPtr = T->getAs<PointerType>();
3875 if (!DestPtr) return;
3876
3877 // If the destination has alignment 1, we're done.
3878 QualType DestPointee = DestPtr->getPointeeType();
3879 if (DestPointee->isIncompleteType()) return;
3880 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3881 if (DestAlign.isOne()) return;
3882
3883 // Require that the source be a pointer type.
3884 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3885 if (!SrcPtr) return;
3886 QualType SrcPointee = SrcPtr->getPointeeType();
3887
3888 // Whitelist casts from cv void*. We already implicitly
3889 // whitelisted casts to cv void*, since they have alignment 1.
3890 // Also whitelist casts involving incomplete types, which implicitly
3891 // includes 'void'.
3892 if (SrcPointee->isIncompleteType()) return;
3893
3894 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3895 if (SrcAlign >= DestAlign) return;
3896
3897 Diag(TRange.getBegin(), diag::warn_cast_align)
3898 << Op->getType() << T
3899 << static_cast<unsigned>(SrcAlign.getQuantity())
3900 << static_cast<unsigned>(DestAlign.getQuantity())
3901 << TRange << Op->getSourceRange();
3902}
3903
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003904static const Type* getElementType(const Expr *BaseExpr) {
3905 const Type* EltType = BaseExpr->getType().getTypePtr();
3906 if (EltType->isAnyPointerType())
3907 return EltType->getPointeeType().getTypePtr();
3908 else if (EltType->isArrayType())
3909 return EltType->getBaseElementTypeUnsafe();
3910 return EltType;
3911}
3912
Chandler Carruth28389f02011-08-05 09:10:50 +00003913/// \brief Check whether this array fits the idiom of a size-one tail padded
3914/// array member of a struct.
3915///
3916/// We avoid emitting out-of-bounds access warnings for such arrays as they are
3917/// commonly used to emulate flexible arrays in C89 code.
3918static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size,
3919 const NamedDecl *ND) {
3920 if (Size != 1 || !ND) return false;
3921
3922 const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
3923 if (!FD) return false;
3924
3925 // Don't consider sizes resulting from macro expansions or template argument
3926 // substitution to form C89 tail-padded arrays.
3927 ConstantArrayTypeLoc TL =
3928 cast<ConstantArrayTypeLoc>(FD->getTypeSourceInfo()->getTypeLoc());
3929 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(TL.getSizeExpr());
3930 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
3931 return false;
3932
3933 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
3934 if (!RD || !RD->isStruct())
3935 return false;
3936
Benjamin Kramer8c543672011-08-06 03:04:42 +00003937 // See if this is the last field decl in the record.
3938 const Decl *D = FD;
3939 while ((D = D->getNextDeclInContext()))
3940 if (isa<FieldDecl>(D))
3941 return false;
3942 return true;
Chandler Carruth28389f02011-08-05 09:10:50 +00003943}
3944
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003945void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
3946 bool isSubscript, bool AllowOnePastEnd) {
3947 const Type* EffectiveType = getElementType(BaseExpr);
3948 BaseExpr = BaseExpr->IgnoreParenCasts();
3949 IndexExpr = IndexExpr->IgnoreParenCasts();
3950
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003951 const ConstantArrayType *ArrayTy =
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003952 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003953 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00003954 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00003955
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003956 if (IndexExpr->isValueDependent())
Ted Kremenek64699be2011-02-16 01:57:07 +00003957 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003958 llvm::APSInt index;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003959 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00003960 return;
Ted Kremenek108b2d52011-02-16 04:01:44 +00003961
Chandler Carruth126b1552011-08-05 08:07:29 +00003962 const NamedDecl *ND = NULL;
Chandler Carruth126b1552011-08-05 08:07:29 +00003963 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3964 ND = dyn_cast<NamedDecl>(DRE->getDecl());
Chandler Carruth28389f02011-08-05 09:10:50 +00003965 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
Chandler Carruth126b1552011-08-05 08:07:29 +00003966 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
Chandler Carruth126b1552011-08-05 08:07:29 +00003967
Ted Kremeneke4b316c2011-02-23 23:06:04 +00003968 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003969 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00003970 if (!size.isStrictlyPositive())
3971 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003972
3973 const Type* BaseType = getElementType(BaseExpr);
Nico Weber7c299802011-09-17 22:59:41 +00003974 if (BaseType != EffectiveType) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003975 // Make sure we're comparing apples to apples when comparing index to size
3976 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
3977 uint64_t array_typesize = Context.getTypeSize(BaseType);
Kaelyn Uhrain0fb0bb12011-08-10 19:47:25 +00003978 // Handle ptrarith_typesize being zero, such as when casting to void*
Kaelyn Uhraine5353762011-08-10 18:49:28 +00003979 if (!ptrarith_typesize) ptrarith_typesize = 1;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003980 if (ptrarith_typesize != array_typesize) {
3981 // There's a cast to a different size type involved
3982 uint64_t ratio = array_typesize / ptrarith_typesize;
3983 // TODO: Be smarter about handling cases where array_typesize is not a
3984 // multiple of ptrarith_typesize
3985 if (ptrarith_typesize * ratio == array_typesize)
3986 size *= llvm::APInt(size.getBitWidth(), ratio);
3987 }
3988 }
3989
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003990 if (size.getBitWidth() > index.getBitWidth())
3991 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003992 else if (size.getBitWidth() < index.getBitWidth())
3993 size = size.sext(index.getBitWidth());
3994
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003995 // For array subscripting the index must be less than size, but for pointer
3996 // arithmetic also allow the index (offset) to be equal to size since
3997 // computing the next address after the end of the array is legal and
3998 // commonly done e.g. in C++ iterators and range-based for loops.
3999 if (AllowOnePastEnd ? index.sle(size) : index.slt(size))
Chandler Carruth126b1552011-08-05 08:07:29 +00004000 return;
4001
4002 // Also don't warn for arrays of size 1 which are members of some
4003 // structure. These are often used to approximate flexible arrays in C89
4004 // code.
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004005 if (IsTailPaddedMemberArray(*this, size, ND))
Ted Kremenek108b2d52011-02-16 04:01:44 +00004006 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004007
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004008 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
4009 if (isSubscript)
4010 DiagID = diag::warn_array_index_exceeds_bounds;
4011
4012 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4013 PDiag(DiagID) << index.toString(10, true)
4014 << size.toString(10, true)
4015 << (unsigned)size.getLimitedValue(~0U)
4016 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00004017 } else {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004018 unsigned DiagID = diag::warn_array_index_precedes_bounds;
4019 if (!isSubscript) {
4020 DiagID = diag::warn_ptr_arith_precedes_bounds;
4021 if (index.isNegative()) index = -index;
4022 }
4023
4024 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
4025 PDiag(DiagID) << index.toString(10, true)
4026 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00004027 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00004028
Chandler Carruth1af88f12011-02-17 21:10:52 +00004029 if (ND)
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004030 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
4031 PDiag(diag::note_array_index_out_of_bounds)
4032 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00004033}
4034
Ted Kremenekdf26df72011-03-01 18:41:00 +00004035void Sema::CheckArrayAccess(const Expr *expr) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004036 int AllowOnePastEnd = 0;
4037 while (expr) {
4038 expr = expr->IgnoreParenImpCasts();
Ted Kremenekdf26df72011-03-01 18:41:00 +00004039 switch (expr->getStmtClass()) {
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004040 case Stmt::ArraySubscriptExprClass: {
4041 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
4042 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), true,
4043 AllowOnePastEnd > 0);
Ted Kremenekdf26df72011-03-01 18:41:00 +00004044 return;
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00004045 }
4046 case Stmt::UnaryOperatorClass: {
4047 // Only unwrap the * and & unary operators
4048 const UnaryOperator *UO = cast<UnaryOperator>(expr);
4049 expr = UO->getSubExpr();
4050 switch (UO->getOpcode()) {
4051 case UO_AddrOf:
4052 AllowOnePastEnd++;
4053 break;
4054 case UO_Deref:
4055 AllowOnePastEnd--;
4056 break;
4057 default:
4058 return;
4059 }
4060 break;
4061 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004062 case Stmt::ConditionalOperatorClass: {
4063 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
4064 if (const Expr *lhs = cond->getLHS())
4065 CheckArrayAccess(lhs);
4066 if (const Expr *rhs = cond->getRHS())
4067 CheckArrayAccess(rhs);
4068 return;
4069 }
4070 default:
4071 return;
4072 }
Peter Collingbourne91147592011-04-15 00:35:48 +00004073 }
Ted Kremenekdf26df72011-03-01 18:41:00 +00004074}
John McCall31168b02011-06-15 23:02:42 +00004075
4076//===--- CHECK: Objective-C retain cycles ----------------------------------//
4077
4078namespace {
4079 struct RetainCycleOwner {
4080 RetainCycleOwner() : Variable(0), Indirect(false) {}
4081 VarDecl *Variable;
4082 SourceRange Range;
4083 SourceLocation Loc;
4084 bool Indirect;
4085
4086 void setLocsFrom(Expr *e) {
4087 Loc = e->getExprLoc();
4088 Range = e->getSourceRange();
4089 }
4090 };
4091}
4092
4093/// Consider whether capturing the given variable can possibly lead to
4094/// a retain cycle.
4095static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
4096 // In ARC, it's captured strongly iff the variable has __strong
4097 // lifetime. In MRR, it's captured strongly if the variable is
4098 // __block and has an appropriate type.
4099 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4100 return false;
4101
4102 owner.Variable = var;
4103 owner.setLocsFrom(ref);
4104 return true;
4105}
4106
4107static bool findRetainCycleOwner(Expr *e, RetainCycleOwner &owner) {
4108 while (true) {
4109 e = e->IgnoreParens();
4110 if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
4111 switch (cast->getCastKind()) {
4112 case CK_BitCast:
4113 case CK_LValueBitCast:
4114 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00004115 case CK_ARCReclaimReturnedObject:
John McCall31168b02011-06-15 23:02:42 +00004116 e = cast->getSubExpr();
4117 continue;
4118
4119 case CK_GetObjCProperty: {
4120 // Bail out if this isn't a strong explicit property.
4121 const ObjCPropertyRefExpr *pre = cast->getSubExpr()->getObjCProperty();
4122 if (pre->isImplicitProperty()) return false;
4123 ObjCPropertyDecl *property = pre->getExplicitProperty();
John McCall43192862011-09-13 18:31:23 +00004124 if (!property->isRetaining() &&
John McCall31168b02011-06-15 23:02:42 +00004125 !(property->getPropertyIvarDecl() &&
4126 property->getPropertyIvarDecl()->getType()
4127 .getObjCLifetime() == Qualifiers::OCL_Strong))
4128 return false;
4129
4130 owner.Indirect = true;
4131 e = const_cast<Expr*>(pre->getBase());
4132 continue;
4133 }
4134
4135 default:
4136 return false;
4137 }
4138 }
4139
4140 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
4141 ObjCIvarDecl *ivar = ref->getDecl();
4142 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
4143 return false;
4144
4145 // Try to find a retain cycle in the base.
4146 if (!findRetainCycleOwner(ref->getBase(), owner))
4147 return false;
4148
4149 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
4150 owner.Indirect = true;
4151 return true;
4152 }
4153
4154 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
4155 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
4156 if (!var) return false;
4157 return considerVariable(var, ref, owner);
4158 }
4159
4160 if (BlockDeclRefExpr *ref = dyn_cast<BlockDeclRefExpr>(e)) {
4161 owner.Variable = ref->getDecl();
4162 owner.setLocsFrom(ref);
4163 return true;
4164 }
4165
4166 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
4167 if (member->isArrow()) return false;
4168
4169 // Don't count this as an indirect ownership.
4170 e = member->getBase();
4171 continue;
4172 }
4173
4174 // Array ivars?
4175
4176 return false;
4177 }
4178}
4179
4180namespace {
4181 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
4182 FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
4183 : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
4184 Variable(variable), Capturer(0) {}
4185
4186 VarDecl *Variable;
4187 Expr *Capturer;
4188
4189 void VisitDeclRefExpr(DeclRefExpr *ref) {
4190 if (ref->getDecl() == Variable && !Capturer)
4191 Capturer = ref;
4192 }
4193
4194 void VisitBlockDeclRefExpr(BlockDeclRefExpr *ref) {
4195 if (ref->getDecl() == Variable && !Capturer)
4196 Capturer = ref;
4197 }
4198
4199 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
4200 if (Capturer) return;
4201 Visit(ref->getBase());
4202 if (Capturer && ref->isFreeIvar())
4203 Capturer = ref;
4204 }
4205
4206 void VisitBlockExpr(BlockExpr *block) {
4207 // Look inside nested blocks
4208 if (block->getBlockDecl()->capturesVariable(Variable))
4209 Visit(block->getBlockDecl()->getBody());
4210 }
4211 };
4212}
4213
4214/// Check whether the given argument is a block which captures a
4215/// variable.
4216static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
4217 assert(owner.Variable && owner.Loc.isValid());
4218
4219 e = e->IgnoreParenCasts();
4220 BlockExpr *block = dyn_cast<BlockExpr>(e);
4221 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
4222 return 0;
4223
4224 FindCaptureVisitor visitor(S.Context, owner.Variable);
4225 visitor.Visit(block->getBlockDecl()->getBody());
4226 return visitor.Capturer;
4227}
4228
4229static void diagnoseRetainCycle(Sema &S, Expr *capturer,
4230 RetainCycleOwner &owner) {
4231 assert(capturer);
4232 assert(owner.Variable && owner.Loc.isValid());
4233
4234 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
4235 << owner.Variable << capturer->getSourceRange();
4236 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
4237 << owner.Indirect << owner.Range;
4238}
4239
4240/// Check for a keyword selector that starts with the word 'add' or
4241/// 'set'.
4242static bool isSetterLikeSelector(Selector sel) {
4243 if (sel.isUnarySelector()) return false;
4244
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004245 StringRef str = sel.getNameForSlot(0);
John McCall31168b02011-06-15 23:02:42 +00004246 while (!str.empty() && str.front() == '_') str = str.substr(1);
4247 if (str.startswith("set") || str.startswith("add"))
4248 str = str.substr(3);
4249 else
4250 return false;
4251
4252 if (str.empty()) return true;
4253 return !islower(str.front());
4254}
4255
4256/// Check a message send to see if it's likely to cause a retain cycle.
4257void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
4258 // Only check instance methods whose selector looks like a setter.
4259 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
4260 return;
4261
4262 // Try to find a variable that the receiver is strongly owned by.
4263 RetainCycleOwner owner;
4264 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
4265 if (!findRetainCycleOwner(msg->getInstanceReceiver(), owner))
4266 return;
4267 } else {
4268 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
4269 owner.Variable = getCurMethodDecl()->getSelfDecl();
4270 owner.Loc = msg->getSuperLoc();
4271 owner.Range = msg->getSuperLoc();
4272 }
4273
4274 // Check whether the receiver is captured by any of the arguments.
4275 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i)
4276 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner))
4277 return diagnoseRetainCycle(*this, capturer, owner);
4278}
4279
4280/// Check a property assign to see if it's likely to cause a retain cycle.
4281void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
4282 RetainCycleOwner owner;
4283 if (!findRetainCycleOwner(receiver, owner))
4284 return;
4285
4286 if (Expr *capturer = findCapturingExpr(*this, argument, owner))
4287 diagnoseRetainCycle(*this, capturer, owner);
4288}
4289
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004290bool Sema::checkUnsafeAssigns(SourceLocation Loc,
John McCall31168b02011-06-15 23:02:42 +00004291 QualType LHS, Expr *RHS) {
4292 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
4293 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004294 return false;
4295 // strip off any implicit cast added to get to the one arc-specific
4296 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004297 if (cast->getCastKind() == CK_ARCConsumeObject) {
John McCall31168b02011-06-15 23:02:42 +00004298 Diag(Loc, diag::warn_arc_retained_assign)
4299 << (LT == Qualifiers::OCL_ExplicitNone)
4300 << RHS->getSourceRange();
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004301 return true;
4302 }
4303 RHS = cast->getSubExpr();
4304 }
4305 return false;
John McCall31168b02011-06-15 23:02:42 +00004306}
4307
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004308void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
4309 Expr *LHS, Expr *RHS) {
4310 QualType LHSType = LHS->getType();
4311 if (checkUnsafeAssigns(Loc, LHSType, RHS))
4312 return;
4313 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
4314 // FIXME. Check for other life times.
4315 if (LT != Qualifiers::OCL_None)
4316 return;
4317
4318 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(LHS)) {
4319 if (PRE->isImplicitProperty())
4320 return;
4321 const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
4322 if (!PD)
4323 return;
4324
4325 unsigned Attributes = PD->getPropertyAttributes();
4326 if (Attributes & ObjCPropertyDecl::OBJC_PR_assign)
4327 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
John McCall2d637d22011-09-10 06:18:15 +00004328 if (cast->getCastKind() == CK_ARCConsumeObject) {
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00004329 Diag(Loc, diag::warn_arc_retained_property_assign)
4330 << RHS->getSourceRange();
4331 return;
4332 }
4333 RHS = cast->getSubExpr();
4334 }
4335 }
4336}