blob: 6b219612d14127752e6e91f89b3afd6b3e7db089 [file] [log] [blame]
Chris Lattner59907c42007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner59907c42007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump1eb44332009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattner59907c42007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall2d887082010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCall781472f2010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek826a3452010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattner59907c42007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall384aff82010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenek23245122007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek7ff22b22008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattner59907c42007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stumpf8c49212010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Tom Care3bfc5f42010-06-09 04:11:11 +000031#include "llvm/Support/raw_ostream.h"
Eric Christopher691ebc32010-04-17 02:26:23 +000032#include "clang/Basic/TargetBuiltins.h"
Nate Begeman26a31422010-06-08 02:47:44 +000033#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian7da71022010-09-07 19:38:13 +000034#include "clang/Basic/ConvertUTF.h"
Zhongxing Xua1f3dba2009-05-20 01:55:10 +000035#include <limits>
Chris Lattner59907c42007-08-10 20:18:51 +000036using namespace clang;
John McCall781472f2010-08-25 08:40:02 +000037using namespace sema;
Chris Lattner59907c42007-08-10 20:18:51 +000038
Chris Lattner60800082009-02-18 17:49:48 +000039SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
Chris Lattner08f92e32010-11-17 07:37:15 +000041 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattner60800082009-02-18 17:49:48 +000043}
Chris Lattner08f92e32010-11-17 07:37:15 +000044
Chris Lattner60800082009-02-18 17:49:48 +000045
Ryan Flynn4403a5e2009-08-06 03:00:50 +000046/// CheckablePrintfAttr - does a function call have a "printf" attribute
47/// and arguments that merit checking?
48bool Sema::CheckablePrintfAttr(const FormatAttr *Format, CallExpr *TheCall) {
49 if (Format->getType() == "printf") return true;
50 if (Format->getType() == "printf0") {
51 // printf0 allows null "format" string; if so don't check format/args
52 unsigned format_idx = Format->getFormatIdx() - 1;
Sebastian Redl4a2614e2009-11-17 18:02:24 +000053 // Does the index refer to the implicit object argument?
54 if (isa<CXXMemberCallExpr>(TheCall)) {
55 if (format_idx == 0)
56 return false;
57 --format_idx;
58 }
Ryan Flynn4403a5e2009-08-06 03:00:50 +000059 if (format_idx < TheCall->getNumArgs()) {
60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekefaff192010-02-27 01:41:03 +000061 if (!Format->isNullPointerConstant(Context,
62 Expr::NPC_ValueDependentIsNull))
Ryan Flynn4403a5e2009-08-06 03:00:50 +000063 return true;
64 }
65 }
66 return false;
67}
Chris Lattner60800082009-02-18 17:49:48 +000068
John McCall8e10f3b2011-02-26 05:39:39 +000069/// Checks that a call expression's argument count is the desired number.
70/// This is useful when doing custom type-checking. Returns true on error.
71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
72 unsigned argCount = call->getNumArgs();
73 if (argCount == desiredArgCount) return false;
74
75 if (argCount < desiredArgCount)
76 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
77 << 0 /*function call*/ << desiredArgCount << argCount
78 << call->getSourceRange();
79
80 // Highlight all the excess arguments.
81 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
82 call->getArg(argCount - 1)->getLocEnd());
83
84 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
85 << 0 /*function call*/ << desiredArgCount << argCount
86 << call->getArg(1)->getSourceRange();
87}
88
John McCall60d7b3a2010-08-24 06:29:42 +000089ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000090Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000091 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000092
Chris Lattner946928f2010-10-01 23:23:24 +000093 // Find out if any arguments are required to be integer constant expressions.
94 unsigned ICEArguments = 0;
95 ASTContext::GetBuiltinTypeError Error;
96 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
97 if (Error != ASTContext::GE_None)
98 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
99
100 // If any arguments are required to be ICE's, check and diagnose.
101 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
102 // Skip arguments not required to be ICE's.
103 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
104
105 llvm::APSInt Result;
106 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
107 return true;
108 ICEArguments &= ~(1 << ArgNo);
109 }
110
Anders Carlssond406bf02009-08-16 01:56:34 +0000111 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000112 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +0000113 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +0000114 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +0000115 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +0000116 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000117 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +0000118 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +0000119 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000120 if (SemaBuiltinVAStart(TheCall))
121 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000122 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000123 case Builtin::BI__builtin_isgreater:
124 case Builtin::BI__builtin_isgreaterequal:
125 case Builtin::BI__builtin_isless:
126 case Builtin::BI__builtin_islessequal:
127 case Builtin::BI__builtin_islessgreater:
128 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinUnorderedCompare(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000132 case Builtin::BI__builtin_fpclassify:
133 if (SemaBuiltinFPClassification(TheCall, 6))
134 return ExprError();
135 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000136 case Builtin::BI__builtin_isfinite:
137 case Builtin::BI__builtin_isinf:
138 case Builtin::BI__builtin_isinf_sign:
139 case Builtin::BI__builtin_isnan:
140 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000141 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000142 return ExprError();
143 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000144 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000145 return SemaBuiltinShuffleVector(TheCall);
146 // TheCall will be freed by the smart pointer here, but that's fine, since
147 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000148 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000149 if (SemaBuiltinPrefetch(TheCall))
150 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000151 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000152 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000153 if (SemaBuiltinObjectSize(TheCall))
154 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000155 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000156 case Builtin::BI__builtin_longjmp:
157 if (SemaBuiltinLongjmp(TheCall))
158 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000159 break;
John McCall8e10f3b2011-02-26 05:39:39 +0000160
161 case Builtin::BI__builtin_classify_type:
162 if (checkArgCount(*this, TheCall, 1)) return true;
163 TheCall->setType(Context.IntTy);
164 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000165 case Builtin::BI__builtin_constant_p:
John McCall8e10f3b2011-02-26 05:39:39 +0000166 if (checkArgCount(*this, TheCall, 1)) return true;
167 TheCall->setType(Context.IntTy);
Chris Lattner75c29a02010-10-12 17:47:42 +0000168 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000169 case Builtin::BI__sync_fetch_and_add:
170 case Builtin::BI__sync_fetch_and_sub:
171 case Builtin::BI__sync_fetch_and_or:
172 case Builtin::BI__sync_fetch_and_and:
173 case Builtin::BI__sync_fetch_and_xor:
174 case Builtin::BI__sync_add_and_fetch:
175 case Builtin::BI__sync_sub_and_fetch:
176 case Builtin::BI__sync_and_and_fetch:
177 case Builtin::BI__sync_or_and_fetch:
178 case Builtin::BI__sync_xor_and_fetch:
179 case Builtin::BI__sync_val_compare_and_swap:
180 case Builtin::BI__sync_bool_compare_and_swap:
181 case Builtin::BI__sync_lock_test_and_set:
182 case Builtin::BI__sync_lock_release:
Chris Lattner23aa9c82011-04-09 03:57:26 +0000183 case Builtin::BI__sync_swap:
Chandler Carruthd2014572010-07-09 18:59:35 +0000184 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000185 }
186
187 // Since the target specific builtins for each arch overlap, only check those
188 // of the arch we are compiling for.
189 if (BuiltinID >= Builtin::FirstTSBuiltin) {
190 switch (Context.Target.getTriple().getArch()) {
191 case llvm::Triple::arm:
192 case llvm::Triple::thumb:
193 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
194 return ExprError();
195 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000196 default:
197 break;
198 }
199 }
200
201 return move(TheCallResult);
202}
203
Nate Begeman61eecf52010-06-14 05:21:25 +0000204// Get the valid immediate range for the specified NEON type code.
205static unsigned RFT(unsigned t, bool shift = false) {
206 bool quad = t & 0x10;
207
208 switch (t & 0x7) {
209 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000210 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000211 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000212 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000213 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000214 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000216 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 case 4: // f32
218 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000219 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000220 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000221 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000222 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000223 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000224 case 7: // float16
225 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000226 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000227 }
228 return 0;
229}
230
Nate Begeman26a31422010-06-08 02:47:44 +0000231bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000232 llvm::APSInt Result;
233
Nate Begeman0d15c532010-06-13 04:47:52 +0000234 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000235 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000236 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000237#define GET_NEON_OVERLOAD_CHECK
238#include "clang/Basic/arm_neon.inc"
239#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000240 }
241
Nate Begeman0d15c532010-06-13 04:47:52 +0000242 // For NEON intrinsics which are overloaded on vector element type, validate
243 // the immediate which specifies which variant to emit.
244 if (mask) {
245 unsigned ArgNo = TheCall->getNumArgs()-1;
246 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 return true;
248
Nate Begeman61eecf52010-06-14 05:21:25 +0000249 TV = Result.getLimitedValue(32);
250 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000251 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
252 << TheCall->getArg(ArgNo)->getSourceRange();
253 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000254
Nate Begeman0d15c532010-06-13 04:47:52 +0000255 // For NEON intrinsics which take an immediate value as part of the
256 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000258 switch (BuiltinID) {
259 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000260 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
261 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000262 case ARM::BI__builtin_arm_vcvtr_f:
263 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000264#define GET_NEON_IMMEDIATE_CHECK
265#include "clang/Basic/arm_neon.inc"
266#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000267 };
268
Nate Begeman61eecf52010-06-14 05:21:25 +0000269 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000270 if (SemaBuiltinConstantArg(TheCall, i, Result))
271 return true;
272
Nate Begeman61eecf52010-06-14 05:21:25 +0000273 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000274 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000275 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000276 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000277 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000278
Nate Begeman99c40bb2010-08-03 21:32:34 +0000279 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000280 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000281}
Daniel Dunbarde454282008-10-02 18:44:07 +0000282
Anders Carlssond406bf02009-08-16 01:56:34 +0000283/// CheckFunctionCall - Check a direct function call for various correctness
284/// and safety properties not strictly enforced by the C type system.
285bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
286 // Get the IdentifierInfo* for the called function.
287 IdentifierInfo *FnInfo = FDecl->getIdentifier();
288
289 // None of the checks below are needed for functions that don't have
290 // simple names (e.g., C++ conversion functions).
291 if (!FnInfo)
292 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Daniel Dunbarde454282008-10-02 18:44:07 +0000294 // FIXME: This mechanism should be abstracted to be less fragile and
295 // more efficient. For example, just map function ids to custom
296 // handlers.
297
Ted Kremenekc82faca2010-09-09 04:33:05 +0000298 // Printf and scanf checking.
299 for (specific_attr_iterator<FormatAttr>
300 i = FDecl->specific_attr_begin<FormatAttr>(),
301 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
302
303 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000304 const bool b = Format->getType() == "scanf";
305 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000306 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000307 CheckPrintfScanfArguments(TheCall, HasVAListArg,
308 Format->getFormatIdx() - 1,
309 HasVAListArg ? 0 : Format->getFirstArg() - 1,
310 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000311 }
Chris Lattner59907c42007-08-10 20:18:51 +0000312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Ted Kremenekc82faca2010-09-09 04:33:05 +0000314 for (specific_attr_iterator<NonNullAttr>
315 i = FDecl->specific_attr_begin<NonNullAttr>(),
316 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +0000317 CheckNonNullArguments(*i, TheCall->getArgs(),
318 TheCall->getCallee()->getLocStart());
Ted Kremenekc82faca2010-09-09 04:33:05 +0000319 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000320
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000321 // Memset handling
322 if (FnInfo->isStr("memset"))
323 CheckMemsetArguments(TheCall);
324
Anders Carlssond406bf02009-08-16 01:56:34 +0000325 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000326}
327
Anders Carlssond406bf02009-08-16 01:56:34 +0000328bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000329 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000330 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000331 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000332 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000334 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
335 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000336 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000337
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000338 QualType Ty = V->getType();
339 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000340 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000341
Ted Kremenek826a3452010-07-16 02:11:22 +0000342 const bool b = Format->getType() == "scanf";
343 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000344 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000345
Anders Carlssond406bf02009-08-16 01:56:34 +0000346 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000347 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
348 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000349
350 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000351}
352
Chris Lattner5caa3702009-05-08 06:58:22 +0000353/// SemaBuiltinAtomicOverloaded - We have a call to a function like
354/// __sync_fetch_and_add, which is an overloaded function based on the pointer
355/// type of its first argument. The main ActOnCallExpr routines have already
356/// promoted the types of arguments because all of these calls are prototyped as
357/// void(...).
358///
359/// This function goes through and does final semantic checking for these
360/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000361ExprResult
362Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000363 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000364 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
365 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
366
367 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000368 if (TheCall->getNumArgs() < 1) {
369 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
370 << 0 << 1 << TheCall->getNumArgs()
371 << TheCall->getCallee()->getSourceRange();
372 return ExprError();
373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 // Inspect the first argument of the atomic builtin. This should always be
376 // a pointer type, whose element is an integral scalar or pointer type.
377 // Because it is a pointer type, we don't have to worry about any implicit
378 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000379 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000380 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000381 if (!FirstArg->getType()->isPointerType()) {
382 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
383 << FirstArg->getType() << FirstArg->getSourceRange();
384 return ExprError();
385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Chandler Carruthd2014572010-07-09 18:59:35 +0000387 QualType ValType =
388 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000389 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000390 !ValType->isBlockPointerType()) {
391 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
392 << FirstArg->getType() << FirstArg->getSourceRange();
393 return ExprError();
394 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000395
Chandler Carruth8d13d222010-07-18 20:54:12 +0000396 // The majority of builtins return a value, but a few have special return
397 // types, so allow them to override appropriately below.
398 QualType ResultType = ValType;
399
Chris Lattner5caa3702009-05-08 06:58:22 +0000400 // We need to figure out which concrete builtin this maps onto. For example,
401 // __sync_fetch_and_add with a 2 byte object turns into
402 // __sync_fetch_and_add_2.
403#define BUILTIN_ROW(x) \
404 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
405 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 static const unsigned BuiltinIndices[][5] = {
408 BUILTIN_ROW(__sync_fetch_and_add),
409 BUILTIN_ROW(__sync_fetch_and_sub),
410 BUILTIN_ROW(__sync_fetch_and_or),
411 BUILTIN_ROW(__sync_fetch_and_and),
412 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 BUILTIN_ROW(__sync_add_and_fetch),
415 BUILTIN_ROW(__sync_sub_and_fetch),
416 BUILTIN_ROW(__sync_and_and_fetch),
417 BUILTIN_ROW(__sync_or_and_fetch),
418 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner5caa3702009-05-08 06:58:22 +0000420 BUILTIN_ROW(__sync_val_compare_and_swap),
421 BUILTIN_ROW(__sync_bool_compare_and_swap),
422 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000423 BUILTIN_ROW(__sync_lock_release),
424 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000425 };
Mike Stump1eb44332009-09-09 15:08:12 +0000426#undef BUILTIN_ROW
427
Chris Lattner5caa3702009-05-08 06:58:22 +0000428 // Determine the index of the size.
429 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000430 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000431 case 1: SizeIndex = 0; break;
432 case 2: SizeIndex = 1; break;
433 case 4: SizeIndex = 2; break;
434 case 8: SizeIndex = 3; break;
435 case 16: SizeIndex = 4; break;
436 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000437 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
438 << FirstArg->getType() << FirstArg->getSourceRange();
439 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 }
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Chris Lattner5caa3702009-05-08 06:58:22 +0000442 // Each of these builtins has one pointer argument, followed by some number of
443 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
444 // that we ignore. Find out which row of BuiltinIndices to read from as well
445 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000446 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000447 unsigned BuiltinIndex, NumFixed = 1;
448 switch (BuiltinID) {
449 default: assert(0 && "Unknown overloaded atomic builtin!");
450 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
451 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
452 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
453 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
454 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000456 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
457 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
458 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
459 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
460 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattner5caa3702009-05-08 06:58:22 +0000462 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000463 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000464 NumFixed = 2;
465 break;
466 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000467 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000468 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000469 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000471 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000472 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000473 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000475 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000477 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
Chris Lattner5caa3702009-05-08 06:58:22 +0000480 // Now that we know how many fixed arguments we expect, first check that we
481 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000482 if (TheCall->getNumArgs() < 1+NumFixed) {
483 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
484 << 0 << 1+NumFixed << TheCall->getNumArgs()
485 << TheCall->getCallee()->getSourceRange();
486 return ExprError();
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000489 // Get the decl for the concrete builtin from this, we can tell what the
490 // concrete integer type we should convert to is.
491 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
492 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
493 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000494 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000495 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
496 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000497
John McCallf871d0c2010-08-07 06:22:56 +0000498 // The first argument --- the pointer --- has a fixed type; we
499 // deduce the types of the rest of the arguments accordingly. Walk
500 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000502 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner5caa3702009-05-08 06:58:22 +0000504 // If the argument is an implicit cast, then there was a promotion due to
505 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000506 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000507 Arg = ICE->getSubExpr();
508 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000509 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Chris Lattner5caa3702009-05-08 06:58:22 +0000512 // GCC does an implicit conversion to the pointer or integer ValType. This
513 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000514 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000515 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000516 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000517 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath);
518 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000519 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Chris Lattner5caa3702009-05-08 06:58:22 +0000521 // Okay, we have something that *can* be converted to the right type. Check
522 // to see if there is a potentially weird extension going on here. This can
523 // happen when you do an atomic operation on something like an char* and
524 // pass in 42. The 42 gets converted to char. This is even more strange
525 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000526 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000527 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
528 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000529 }
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Chris Lattner5caa3702009-05-08 06:58:22 +0000531 // Switch the DeclRefExpr to refer to the new decl.
532 DRE->setDecl(NewBuiltinDecl);
533 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000534
Chris Lattner5caa3702009-05-08 06:58:22 +0000535 // Set the callee in the CallExpr.
536 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000537 ExprResult PromotedCall = UsualUnaryConversions(DRE);
538 if (PromotedCall.isInvalid())
539 return ExprError();
540 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000542 // Change the result type of the call to match the original value type. This
543 // is arbitrary, but the codegen for these builtins ins design to handle it
544 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000545 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000546
547 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000548}
549
550
Chris Lattner69039812009-02-18 06:01:06 +0000551/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000552/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000553/// Note: It might also make sense to do the UTF-16 conversion here (would
554/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000555bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000556 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000557 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
558
559 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000560 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
561 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000562 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000563 }
Mike Stump1eb44332009-09-09 15:08:12 +0000564
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000565 if (Literal->containsNonAsciiOrNull()) {
566 llvm::StringRef String = Literal->getString();
567 unsigned NumBytes = String.size();
568 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
569 const UTF8 *FromPtr = (UTF8 *)String.data();
570 UTF16 *ToPtr = &ToBuf[0];
571
572 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
573 &ToPtr, ToPtr + NumBytes,
574 strictConversion);
575 // Check for conversion failure.
576 if (Result != conversionOK)
577 Diag(Arg->getLocStart(),
578 diag::warn_cfstring_truncated) << Arg->getSourceRange();
579 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000580 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000581}
582
Chris Lattnerc27c6652007-12-20 00:05:45 +0000583/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
584/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000585bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
586 Expr *Fn = TheCall->getCallee();
587 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000588 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000589 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000590 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
591 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000592 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000593 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000594 return true;
595 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000596
597 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000598 return Diag(TheCall->getLocEnd(),
599 diag::err_typecheck_call_too_few_args_at_least)
600 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000601 }
602
Chris Lattnerc27c6652007-12-20 00:05:45 +0000603 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000604 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000605 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000606 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000607 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000608 else if (FunctionDecl *FD = getCurFunctionDecl())
609 isVariadic = FD->isVariadic();
610 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000611 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000612
Chris Lattnerc27c6652007-12-20 00:05:45 +0000613 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000614 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
615 return true;
616 }
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Chris Lattner30ce3442007-12-19 23:59:04 +0000618 // Verify that the second argument to the builtin is the last argument of the
619 // current function or method.
620 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000621 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Anders Carlsson88cf2262008-02-11 04:20:54 +0000623 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
624 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000625 // FIXME: This isn't correct for methods (results in bogus warning).
626 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000627 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000628 if (CurBlock)
629 LastArg = *(CurBlock->TheDecl->param_end()-1);
630 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000631 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000632 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000633 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 SecondArgIsLastNamedArgument = PV == LastArg;
635 }
636 }
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Chris Lattner30ce3442007-12-19 23:59:04 +0000638 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000639 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000640 diag::warn_second_parameter_of_va_start_not_last_named_argument);
641 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000642}
Chris Lattner30ce3442007-12-19 23:59:04 +0000643
Chris Lattner1b9a0792007-12-20 00:26:33 +0000644/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
645/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000646bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
647 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000648 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000649 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000650 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000651 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000652 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000653 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 << SourceRange(TheCall->getArg(2)->getLocStart(),
655 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000656
John Wiegley429bb272011-04-08 18:41:53 +0000657 ExprResult OrigArg0 = TheCall->getArg(0);
658 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000659
Chris Lattner1b9a0792007-12-20 00:26:33 +0000660 // Do standard promotions between the two arguments, returning their common
661 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000662 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000663 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
664 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000665
666 // Make sure any conversions are pushed back into the call; this is
667 // type safe since unordered compare builtins are declared as "_Bool
668 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000669 TheCall->setArg(0, OrigArg0.get());
670 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000671
John Wiegley429bb272011-04-08 18:41:53 +0000672 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000673 return false;
674
Chris Lattner1b9a0792007-12-20 00:26:33 +0000675 // If the common type isn't a real floating type, then the arguments were
676 // invalid for this operation.
677 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000678 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000679 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000680 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
681 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000682
Chris Lattner1b9a0792007-12-20 00:26:33 +0000683 return false;
684}
685
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000686/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
687/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000688/// to check everything. We expect the last argument to be a floating point
689/// value.
690bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
691 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000692 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000693 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000694 if (TheCall->getNumArgs() > NumArgs)
695 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000696 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000697 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000698 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000699 (*(TheCall->arg_end()-1))->getLocEnd());
700
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000701 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Eli Friedman9ac6f622009-08-31 20:06:00 +0000703 if (OrigArg->isTypeDependent())
704 return false;
705
Chris Lattner81368fb2010-05-06 05:50:07 +0000706 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000707 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000708 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000709 diag::err_typecheck_call_invalid_unary_fp)
710 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattner81368fb2010-05-06 05:50:07 +0000712 // If this is an implicit conversion from float -> double, remove it.
713 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
714 Expr *CastArg = Cast->getSubExpr();
715 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
716 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
717 "promotion from float to double is the only expected cast here");
718 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000719 TheCall->setArg(NumArgs-1, CastArg);
720 OrigArg = CastArg;
721 }
722 }
723
Eli Friedman9ac6f622009-08-31 20:06:00 +0000724 return false;
725}
726
Eli Friedmand38617c2008-05-14 19:38:39 +0000727/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
728// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000729ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000730 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000731 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000732 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000733 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000734 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000735
Nate Begeman37b6a572010-06-08 00:16:34 +0000736 // Determine which of the following types of shufflevector we're checking:
737 // 1) unary, vector mask: (lhs, mask)
738 // 2) binary, vector mask: (lhs, rhs, mask)
739 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
740 QualType resType = TheCall->getArg(0)->getType();
741 unsigned numElements = 0;
742
Douglas Gregorcde01732009-05-19 22:10:17 +0000743 if (!TheCall->getArg(0)->isTypeDependent() &&
744 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000745 QualType LHSType = TheCall->getArg(0)->getType();
746 QualType RHSType = TheCall->getArg(1)->getType();
747
748 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000749 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000750 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000751 TheCall->getArg(1)->getLocEnd());
752 return ExprError();
753 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000754
755 numElements = LHSType->getAs<VectorType>()->getNumElements();
756 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Nate Begeman37b6a572010-06-08 00:16:34 +0000758 // Check to see if we have a call with 2 vector arguments, the unary shuffle
759 // with mask. If so, verify that RHS is an integer vector type with the
760 // same number of elts as lhs.
761 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000762 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000763 RHSType->getAs<VectorType>()->getNumElements() != numElements)
764 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
765 << SourceRange(TheCall->getArg(1)->getLocStart(),
766 TheCall->getArg(1)->getLocEnd());
767 numResElements = numElements;
768 }
769 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000770 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000771 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000772 TheCall->getArg(1)->getLocEnd());
773 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000774 } else if (numElements != numResElements) {
775 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000776 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000777 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000778 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000779 }
780
781 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000782 if (TheCall->getArg(i)->isTypeDependent() ||
783 TheCall->getArg(i)->isValueDependent())
784 continue;
785
Nate Begeman37b6a572010-06-08 00:16:34 +0000786 llvm::APSInt Result(32);
787 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
788 return ExprError(Diag(TheCall->getLocStart(),
789 diag::err_shufflevector_nonconstant_argument)
790 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000791
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000792 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000793 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000794 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000795 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000796 }
797
798 llvm::SmallVector<Expr*, 32> exprs;
799
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000800 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000801 exprs.push_back(TheCall->getArg(i));
802 TheCall->setArg(i, 0);
803 }
804
Nate Begemana88dc302009-08-12 02:10:25 +0000805 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000806 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000807 TheCall->getCallee()->getLocStart(),
808 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000809}
Chris Lattner30ce3442007-12-19 23:59:04 +0000810
Daniel Dunbar4493f792008-07-21 22:59:13 +0000811/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
812// This is declared to take (const void*, ...) and can take two
813// optional constant int args.
814bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000815 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000816
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000817 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000818 return Diag(TheCall->getLocEnd(),
819 diag::err_typecheck_call_too_many_args_at_most)
820 << 0 /*function call*/ << 3 << NumArgs
821 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000822
823 // Argument 0 is checked for us and the remaining arguments must be
824 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000825 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000826 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000827
Eli Friedman9aef7262009-12-04 00:30:06 +0000828 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000829 if (SemaBuiltinConstantArg(TheCall, i, Result))
830 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Daniel Dunbar4493f792008-07-21 22:59:13 +0000832 // FIXME: gcc issues a warning and rewrites these to 0. These
833 // seems especially odd for the third argument since the default
834 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000835 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000836 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000837 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000838 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000839 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000840 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000841 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000842 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000843 }
844 }
845
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000846 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000847}
848
Eric Christopher691ebc32010-04-17 02:26:23 +0000849/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
850/// TheCall is a constant expression.
851bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
852 llvm::APSInt &Result) {
853 Expr *Arg = TheCall->getArg(ArgNum);
854 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
855 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
856
857 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
858
859 if (!Arg->isIntegerConstantExpr(Result, Context))
860 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000861 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000862
Chris Lattner21fb98e2009-09-23 06:06:36 +0000863 return false;
864}
865
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000866/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
867/// int type). This simply type checks that type is one of the defined
868/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000869// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000870bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000871 llvm::APSInt Result;
872
873 // Check constant-ness first.
874 if (SemaBuiltinConstantArg(TheCall, 1, Result))
875 return true;
876
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000877 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000878 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000879 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
880 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000881 }
882
883 return false;
884}
885
Eli Friedman586d6a82009-05-03 06:04:26 +0000886/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000887/// This checks that val is a constant 1.
888bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
889 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000890 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000891
Eric Christopher691ebc32010-04-17 02:26:23 +0000892 // TODO: This is less than ideal. Overload this to take a value.
893 if (SemaBuiltinConstantArg(TheCall, 1, Result))
894 return true;
895
896 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000897 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
898 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
899
900 return false;
901}
902
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000903// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000904bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
905 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000906 unsigned format_idx, unsigned firstDataArg,
907 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000908 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000909 if (E->isTypeDependent() || E->isValueDependent())
910 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000911
Peter Collingbournef111d932011-04-15 00:35:48 +0000912 E = E->IgnoreParens();
913
Ted Kremenekd30ef872009-01-12 23:09:09 +0000914 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000915 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000916 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000917 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000918 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
919 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000920 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000921 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000922 }
923
Ted Kremenek95355bb2010-09-09 03:51:42 +0000924 case Stmt::IntegerLiteralClass:
925 // Technically -Wformat-nonliteral does not warn about this case.
926 // The behavior of printf and friends in this case is implementation
927 // dependent. Ideally if the format string cannot be null then
928 // it should have a 'nonnull' attribute in the function prototype.
929 return true;
930
Ted Kremenekd30ef872009-01-12 23:09:09 +0000931 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000932 E = cast<ImplicitCastExpr>(E)->getSubExpr();
933 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000934 }
935
John McCall56ca35d2011-02-17 10:25:35 +0000936 case Stmt::OpaqueValueExprClass:
937 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
938 E = src;
939 goto tryAgain;
940 }
941 return false;
942
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000943 case Stmt::PredefinedExprClass:
944 // While __func__, etc., are technically not string literals, they
945 // cannot contain format specifiers and thus are not a security
946 // liability.
947 return true;
948
Ted Kremenek082d9362009-03-20 21:35:28 +0000949 case Stmt::DeclRefExprClass: {
950 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Ted Kremenek082d9362009-03-20 21:35:28 +0000952 // As an exception, do not flag errors for variables binding to
953 // const string literals.
954 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
955 bool isConstant = false;
956 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000957
Ted Kremenek082d9362009-03-20 21:35:28 +0000958 if (const ArrayType *AT = Context.getAsArrayType(T)) {
959 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000960 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000961 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000962 PT->getPointeeType().isConstant(Context);
963 }
Mike Stump1eb44332009-09-09 15:08:12 +0000964
Ted Kremenek082d9362009-03-20 21:35:28 +0000965 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000966 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000967 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000968 HasVAListArg, format_idx, firstDataArg,
969 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Anders Carlssond966a552009-06-28 19:55:58 +0000972 // For vprintf* functions (i.e., HasVAListArg==true), we add a
973 // special check to see if the format string is a function parameter
974 // of the function calling the printf function. If the function
975 // has an attribute indicating it is a printf-like function, then we
976 // should suppress warnings concerning non-literals being used in a call
977 // to a vprintf function. For example:
978 //
979 // void
980 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
981 // va_list ap;
982 // va_start(ap, fmt);
983 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
984 // ...
985 //
986 //
987 // FIXME: We don't have full attribute support yet, so just check to see
988 // if the argument is a DeclRefExpr that references a parameter. We'll
989 // add proper support for checking the attribute later.
990 if (HasVAListArg)
991 if (isa<ParmVarDecl>(VD))
992 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Ted Kremenek082d9362009-03-20 21:35:28 +0000995 return false;
996 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000997
Anders Carlsson8f031b32009-06-27 04:05:33 +0000998 case Stmt::CallExprClass: {
999 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001000 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001001 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1003 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001004 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001005 unsigned ArgIndex = FA->getFormatIdx();
1006 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
1008 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001009 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001010 }
1011 }
1012 }
1013 }
Mike Stump1eb44332009-09-09 15:08:12 +00001014
Anders Carlsson8f031b32009-06-27 04:05:33 +00001015 return false;
1016 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001017 case Stmt::ObjCStringLiteralClass:
1018 case Stmt::StringLiteralClass: {
1019 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Ted Kremenek082d9362009-03-20 21:35:28 +00001021 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001022 StrE = ObjCFExpr->getString();
1023 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001024 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001025
Ted Kremenekd30ef872009-01-12 23:09:09 +00001026 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001027 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1028 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001029 return true;
1030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Ted Kremenekd30ef872009-01-12 23:09:09 +00001032 return false;
1033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Ted Kremenek082d9362009-03-20 21:35:28 +00001035 default:
1036 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001037 }
1038}
1039
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001040void
Mike Stump1eb44332009-09-09 15:08:12 +00001041Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001042 const Expr * const *ExprArgs,
1043 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001044 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1045 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001046 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001047 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001048 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001049 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001050 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001051 }
1052}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001053
Ted Kremenek826a3452010-07-16 02:11:22 +00001054/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1055/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001056void
Ted Kremenek826a3452010-07-16 02:11:22 +00001057Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1058 unsigned format_idx, unsigned firstDataArg,
1059 bool isPrintf) {
1060
Ted Kremenek082d9362009-03-20 21:35:28 +00001061 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001062
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001063 // The way the format attribute works in GCC, the implicit this argument
1064 // of member functions is counted. However, it doesn't appear in our own
1065 // lists, so decrement format_idx in that case.
1066 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001067 const CXXMethodDecl *method_decl =
1068 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1069 if (method_decl && method_decl->isInstance()) {
1070 // Catch a format attribute mistakenly referring to the object argument.
1071 if (format_idx == 0)
1072 return;
1073 --format_idx;
1074 if(firstDataArg != 0)
1075 --firstDataArg;
1076 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001077 }
1078
Ted Kremenek826a3452010-07-16 02:11:22 +00001079 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001080 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001081 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001082 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001083 return;
1084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Ted Kremenek082d9362009-03-20 21:35:28 +00001086 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Chris Lattner59907c42007-08-10 20:18:51 +00001088 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001089 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001090 // Dynamically generated format strings are difficult to
1091 // automatically vet at compile time. Requiring that format strings
1092 // are string literals: (1) permits the checking of format strings by
1093 // the compiler and thereby (2) can practically remove the source of
1094 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001095
Mike Stump1eb44332009-09-09 15:08:12 +00001096 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001097 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001098 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001099 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001100 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001101 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001102 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001103
Chris Lattner655f1412009-04-29 04:59:47 +00001104 // If there are no arguments specified, warn with -Wformat-security, otherwise
1105 // warn only with -Wformat-nonliteral.
1106 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001107 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001108 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001109 << OrigFormatExpr->getSourceRange();
1110 else
Mike Stump1eb44332009-09-09 15:08:12 +00001111 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001112 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001113 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001114}
Ted Kremenek71895b92007-08-14 17:39:48 +00001115
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001117class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1118protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001119 Sema &S;
1120 const StringLiteral *FExpr;
1121 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001122 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001123 const unsigned NumDataArgs;
1124 const bool IsObjCLiteral;
1125 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001126 const bool HasVAListArg;
1127 const CallExpr *TheCall;
1128 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001129 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001130 bool usesPositionalArgs;
1131 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001132public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001133 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001134 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001135 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001136 const char *beg, bool hasVAListArg,
1137 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001138 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001139 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001140 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001141 IsObjCLiteral(isObjCLiteral), Beg(beg),
1142 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001143 TheCall(theCall), FormatIdx(formatIdx),
1144 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001145 CoveredArgs.resize(numDataArgs);
1146 CoveredArgs.reset();
1147 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001148
Ted Kremenek07d161f2010-01-29 01:50:07 +00001149 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001150
Ted Kremenek826a3452010-07-16 02:11:22 +00001151 void HandleIncompleteSpecifier(const char *startSpecifier,
1152 unsigned specifierLen);
1153
Ted Kremenekefaff192010-02-27 01:41:03 +00001154 virtual void HandleInvalidPosition(const char *startSpecifier,
1155 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001156 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001157
1158 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1159
Ted Kremeneke0e53132010-01-28 23:39:18 +00001160 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001161
Ted Kremenek826a3452010-07-16 02:11:22 +00001162protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001163 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1164 const char *startSpec,
1165 unsigned specifierLen,
1166 const char *csStart, unsigned csLen);
1167
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001168 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001169 CharSourceRange getSpecifierRange(const char *startSpecifier,
1170 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001171 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001172
Ted Kremenek0d277352010-01-29 01:06:55 +00001173 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001174
1175 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1176 const analyze_format_string::ConversionSpecifier &CS,
1177 const char *startSpecifier, unsigned specifierLen,
1178 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001179};
1180}
1181
Ted Kremenek826a3452010-07-16 02:11:22 +00001182SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001183 return OrigFormatExpr->getSourceRange();
1184}
1185
Ted Kremenek826a3452010-07-16 02:11:22 +00001186CharSourceRange CheckFormatHandler::
1187getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001188 SourceLocation Start = getLocationOfByte(startSpecifier);
1189 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1190
1191 // Advance the end SourceLocation by one due to half-open ranges.
1192 End = End.getFileLocWithOffset(1);
1193
1194 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001195}
1196
Ted Kremenek826a3452010-07-16 02:11:22 +00001197SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001198 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001199}
1200
Ted Kremenek826a3452010-07-16 02:11:22 +00001201void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1202 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001203 SourceLocation Loc = getLocationOfByte(startSpecifier);
1204 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001205 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001206}
1207
Ted Kremenekefaff192010-02-27 01:41:03 +00001208void
Ted Kremenek826a3452010-07-16 02:11:22 +00001209CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1210 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001211 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001212 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1213 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001214}
1215
Ted Kremenek826a3452010-07-16 02:11:22 +00001216void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001217 unsigned posLen) {
1218 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001219 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1220 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001221}
1222
Ted Kremenek826a3452010-07-16 02:11:22 +00001223void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001224 if (!IsObjCLiteral) {
1225 // The presence of a null character is likely an error.
1226 S.Diag(getLocationOfByte(nullCharacter),
1227 diag::warn_printf_format_string_contains_null_char)
1228 << getFormatStringRange();
1229 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001230}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001231
Ted Kremenek826a3452010-07-16 02:11:22 +00001232const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1233 return TheCall->getArg(FirstDataArg + i);
1234}
1235
1236void CheckFormatHandler::DoneProcessing() {
1237 // Does the number of data arguments exceed the number of
1238 // format conversions in the format string?
1239 if (!HasVAListArg) {
1240 // Find any arguments that weren't covered.
1241 CoveredArgs.flip();
1242 signed notCoveredArg = CoveredArgs.find_first();
1243 if (notCoveredArg >= 0) {
1244 assert((unsigned)notCoveredArg < NumDataArgs);
1245 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1246 diag::warn_printf_data_arg_not_used)
1247 << getFormatStringRange();
1248 }
1249 }
1250}
1251
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001252bool
1253CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1254 SourceLocation Loc,
1255 const char *startSpec,
1256 unsigned specifierLen,
1257 const char *csStart,
1258 unsigned csLen) {
1259
1260 bool keepGoing = true;
1261 if (argIndex < NumDataArgs) {
1262 // Consider the argument coverered, even though the specifier doesn't
1263 // make sense.
1264 CoveredArgs.set(argIndex);
1265 }
1266 else {
1267 // If argIndex exceeds the number of data arguments we
1268 // don't issue a warning because that is just a cascade of warnings (and
1269 // they may have intended '%%' anyway). We don't want to continue processing
1270 // the format string after this point, however, as we will like just get
1271 // gibberish when trying to match arguments.
1272 keepGoing = false;
1273 }
1274
1275 S.Diag(Loc, diag::warn_format_invalid_conversion)
1276 << llvm::StringRef(csStart, csLen)
1277 << getSpecifierRange(startSpec, specifierLen);
1278
1279 return keepGoing;
1280}
1281
Ted Kremenek666a1972010-07-26 19:45:42 +00001282bool
1283CheckFormatHandler::CheckNumArgs(
1284 const analyze_format_string::FormatSpecifier &FS,
1285 const analyze_format_string::ConversionSpecifier &CS,
1286 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1287
1288 if (argIndex >= NumDataArgs) {
1289 if (FS.usesPositionalArg()) {
1290 S.Diag(getLocationOfByte(CS.getStart()),
1291 diag::warn_printf_positional_arg_exceeds_data_args)
1292 << (argIndex+1) << NumDataArgs
1293 << getSpecifierRange(startSpecifier, specifierLen);
1294 }
1295 else {
1296 S.Diag(getLocationOfByte(CS.getStart()),
1297 diag::warn_printf_insufficient_data_args)
1298 << getSpecifierRange(startSpecifier, specifierLen);
1299 }
1300
1301 return false;
1302 }
1303 return true;
1304}
1305
Ted Kremenek826a3452010-07-16 02:11:22 +00001306//===--- CHECK: Printf format string checking ------------------------------===//
1307
1308namespace {
1309class CheckPrintfHandler : public CheckFormatHandler {
1310public:
1311 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1312 const Expr *origFormatExpr, unsigned firstDataArg,
1313 unsigned numDataArgs, bool isObjCLiteral,
1314 const char *beg, bool hasVAListArg,
1315 const CallExpr *theCall, unsigned formatIdx)
1316 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1317 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1318 theCall, formatIdx) {}
1319
1320
1321 bool HandleInvalidPrintfConversionSpecifier(
1322 const analyze_printf::PrintfSpecifier &FS,
1323 const char *startSpecifier,
1324 unsigned specifierLen);
1325
1326 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1327 const char *startSpecifier,
1328 unsigned specifierLen);
1329
1330 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1331 const char *startSpecifier, unsigned specifierLen);
1332 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1333 const analyze_printf::OptionalAmount &Amt,
1334 unsigned type,
1335 const char *startSpecifier, unsigned specifierLen);
1336 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1337 const analyze_printf::OptionalFlag &flag,
1338 const char *startSpecifier, unsigned specifierLen);
1339 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1340 const analyze_printf::OptionalFlag &ignoredFlag,
1341 const analyze_printf::OptionalFlag &flag,
1342 const char *startSpecifier, unsigned specifierLen);
1343};
1344}
1345
1346bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1347 const analyze_printf::PrintfSpecifier &FS,
1348 const char *startSpecifier,
1349 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001350 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001351 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001352
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001353 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1354 getLocationOfByte(CS.getStart()),
1355 startSpecifier, specifierLen,
1356 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001357}
1358
Ted Kremenek826a3452010-07-16 02:11:22 +00001359bool CheckPrintfHandler::HandleAmount(
1360 const analyze_format_string::OptionalAmount &Amt,
1361 unsigned k, const char *startSpecifier,
1362 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001363
1364 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001365 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001366 unsigned argIndex = Amt.getArgIndex();
1367 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001368 S.Diag(getLocationOfByte(Amt.getStart()),
1369 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001370 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001371 // Don't do any more checking. We will just emit
1372 // spurious errors.
1373 return false;
1374 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001375
Ted Kremenek0d277352010-01-29 01:06:55 +00001376 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001377 // Although not in conformance with C99, we also allow the argument to be
1378 // an 'unsigned int' as that is a reasonably safe case. GCC also
1379 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001380 CoveredArgs.set(argIndex);
1381 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001382 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001383
1384 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1385 assert(ATR.isValid());
1386
1387 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001388 S.Diag(getLocationOfByte(Amt.getStart()),
1389 diag::warn_printf_asterisk_wrong_type)
1390 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001391 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001392 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001393 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001394 // Don't do any more checking. We will just emit
1395 // spurious errors.
1396 return false;
1397 }
1398 }
1399 }
1400 return true;
1401}
Ted Kremenek0d277352010-01-29 01:06:55 +00001402
Tom Caree4ee9662010-06-17 19:00:27 +00001403void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001404 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001405 const analyze_printf::OptionalAmount &Amt,
1406 unsigned type,
1407 const char *startSpecifier,
1408 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001409 const analyze_printf::PrintfConversionSpecifier &CS =
1410 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001411 switch (Amt.getHowSpecified()) {
1412 case analyze_printf::OptionalAmount::Constant:
1413 S.Diag(getLocationOfByte(Amt.getStart()),
1414 diag::warn_printf_nonsensical_optional_amount)
1415 << type
1416 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001417 << getSpecifierRange(startSpecifier, specifierLen)
1418 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001419 Amt.getConstantLength()));
1420 break;
1421
1422 default:
1423 S.Diag(getLocationOfByte(Amt.getStart()),
1424 diag::warn_printf_nonsensical_optional_amount)
1425 << type
1426 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001427 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001428 break;
1429 }
1430}
1431
Ted Kremenek826a3452010-07-16 02:11:22 +00001432void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001433 const analyze_printf::OptionalFlag &flag,
1434 const char *startSpecifier,
1435 unsigned specifierLen) {
1436 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001437 const analyze_printf::PrintfConversionSpecifier &CS =
1438 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001439 S.Diag(getLocationOfByte(flag.getPosition()),
1440 diag::warn_printf_nonsensical_flag)
1441 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001442 << getSpecifierRange(startSpecifier, specifierLen)
1443 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001444}
1445
1446void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001447 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001448 const analyze_printf::OptionalFlag &ignoredFlag,
1449 const analyze_printf::OptionalFlag &flag,
1450 const char *startSpecifier,
1451 unsigned specifierLen) {
1452 // Warn about ignored flag with a fixit removal.
1453 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1454 diag::warn_printf_ignored_flag)
1455 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001456 << getSpecifierRange(startSpecifier, specifierLen)
1457 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001458 ignoredFlag.getPosition(), 1));
1459}
1460
Ted Kremeneke0e53132010-01-28 23:39:18 +00001461bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001462CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001463 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001464 const char *startSpecifier,
1465 unsigned specifierLen) {
1466
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001467 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001468 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001469 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001470
Ted Kremenekbaa40062010-07-19 22:01:06 +00001471 if (FS.consumesDataArgument()) {
1472 if (atFirstArg) {
1473 atFirstArg = false;
1474 usesPositionalArgs = FS.usesPositionalArg();
1475 }
1476 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1477 // Cannot mix-and-match positional and non-positional arguments.
1478 S.Diag(getLocationOfByte(CS.getStart()),
1479 diag::warn_format_mix_positional_nonpositional_args)
1480 << getSpecifierRange(startSpecifier, specifierLen);
1481 return false;
1482 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001483 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001484
Ted Kremenekefaff192010-02-27 01:41:03 +00001485 // First check if the field width, precision, and conversion specifier
1486 // have matching data arguments.
1487 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1488 startSpecifier, specifierLen)) {
1489 return false;
1490 }
1491
1492 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1493 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001494 return false;
1495 }
1496
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001497 if (!CS.consumesDataArgument()) {
1498 // FIXME: Technically specifying a precision or field width here
1499 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001500 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001501 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001502
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001503 // Consume the argument.
1504 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001505 if (argIndex < NumDataArgs) {
1506 // The check to see if the argIndex is valid will come later.
1507 // We set the bit here because we may exit early from this
1508 // function if we encounter some other error.
1509 CoveredArgs.set(argIndex);
1510 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001511
1512 // Check for using an Objective-C specific conversion specifier
1513 // in a non-ObjC literal.
1514 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001515 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1516 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001517 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001518
Tom Caree4ee9662010-06-17 19:00:27 +00001519 // Check for invalid use of field width
1520 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001521 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001522 startSpecifier, specifierLen);
1523 }
1524
1525 // Check for invalid use of precision
1526 if (!FS.hasValidPrecision()) {
1527 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1528 startSpecifier, specifierLen);
1529 }
1530
1531 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001532 if (!FS.hasValidThousandsGroupingPrefix())
1533 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001534 if (!FS.hasValidLeadingZeros())
1535 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1536 if (!FS.hasValidPlusPrefix())
1537 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001538 if (!FS.hasValidSpacePrefix())
1539 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001540 if (!FS.hasValidAlternativeForm())
1541 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1542 if (!FS.hasValidLeftJustified())
1543 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1544
1545 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001546 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1547 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1548 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001549 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1550 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1551 startSpecifier, specifierLen);
1552
1553 // Check the length modifier is valid with the given conversion specifier.
1554 const LengthModifier &LM = FS.getLengthModifier();
1555 if (!FS.hasValidLengthModifier())
1556 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001557 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001558 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001559 << getSpecifierRange(startSpecifier, specifierLen)
1560 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001561 LM.getLength()));
1562
1563 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001564 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001565 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001566 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001567 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001568 // Continue checking the other format specifiers.
1569 return true;
1570 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001571
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001572 // The remaining checks depend on the data arguments.
1573 if (HasVAListArg)
1574 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001575
Ted Kremenek666a1972010-07-26 19:45:42 +00001576 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001577 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001578
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001579 // Now type check the data expression that matches the
1580 // format specifier.
1581 const Expr *Ex = getDataArg(argIndex);
1582 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1583 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1584 // Check if we didn't match because of an implicit cast from a 'char'
1585 // or 'short' to an 'int'. This is done because printf is a varargs
1586 // function.
1587 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001588 if (ICE->getType() == S.Context.IntTy) {
1589 // All further checking is done on the subexpression.
1590 Ex = ICE->getSubExpr();
1591 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001592 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001593 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001594
1595 // We may be able to offer a FixItHint if it is a supported type.
1596 PrintfSpecifier fixedFS = FS;
1597 bool success = fixedFS.fixType(Ex->getType());
1598
1599 if (success) {
1600 // Get the fix string from the fixed format specifier
1601 llvm::SmallString<128> buf;
1602 llvm::raw_svector_ostream os(buf);
1603 fixedFS.toString(os);
1604
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001605 // FIXME: getRepresentativeType() perhaps should return a string
1606 // instead of a QualType to better handle when the representative
1607 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001608 S.Diag(getLocationOfByte(CS.getStart()),
1609 diag::warn_printf_conversion_argument_type_mismatch)
1610 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1611 << getSpecifierRange(startSpecifier, specifierLen)
1612 << Ex->getSourceRange()
1613 << FixItHint::CreateReplacement(
1614 getSpecifierRange(startSpecifier, specifierLen),
1615 os.str());
1616 }
1617 else {
1618 S.Diag(getLocationOfByte(CS.getStart()),
1619 diag::warn_printf_conversion_argument_type_mismatch)
1620 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1621 << getSpecifierRange(startSpecifier, specifierLen)
1622 << Ex->getSourceRange();
1623 }
1624 }
1625
Ted Kremeneke0e53132010-01-28 23:39:18 +00001626 return true;
1627}
1628
Ted Kremenek826a3452010-07-16 02:11:22 +00001629//===--- CHECK: Scanf format string checking ------------------------------===//
1630
1631namespace {
1632class CheckScanfHandler : public CheckFormatHandler {
1633public:
1634 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1635 const Expr *origFormatExpr, unsigned firstDataArg,
1636 unsigned numDataArgs, bool isObjCLiteral,
1637 const char *beg, bool hasVAListArg,
1638 const CallExpr *theCall, unsigned formatIdx)
1639 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1640 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1641 theCall, formatIdx) {}
1642
1643 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1644 const char *startSpecifier,
1645 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001646
1647 bool HandleInvalidScanfConversionSpecifier(
1648 const analyze_scanf::ScanfSpecifier &FS,
1649 const char *startSpecifier,
1650 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001651
1652 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001653};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001654}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001655
Ted Kremenekb7c21012010-07-16 18:28:03 +00001656void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1657 const char *end) {
1658 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1659 << getSpecifierRange(start, end - start);
1660}
1661
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001662bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1663 const analyze_scanf::ScanfSpecifier &FS,
1664 const char *startSpecifier,
1665 unsigned specifierLen) {
1666
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001667 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001668 FS.getConversionSpecifier();
1669
1670 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1671 getLocationOfByte(CS.getStart()),
1672 startSpecifier, specifierLen,
1673 CS.getStart(), CS.getLength());
1674}
1675
Ted Kremenek826a3452010-07-16 02:11:22 +00001676bool CheckScanfHandler::HandleScanfSpecifier(
1677 const analyze_scanf::ScanfSpecifier &FS,
1678 const char *startSpecifier,
1679 unsigned specifierLen) {
1680
1681 using namespace analyze_scanf;
1682 using namespace analyze_format_string;
1683
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001684 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001685
Ted Kremenekbaa40062010-07-19 22:01:06 +00001686 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1687 // be used to decide if we are using positional arguments consistently.
1688 if (FS.consumesDataArgument()) {
1689 if (atFirstArg) {
1690 atFirstArg = false;
1691 usesPositionalArgs = FS.usesPositionalArg();
1692 }
1693 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1694 // Cannot mix-and-match positional and non-positional arguments.
1695 S.Diag(getLocationOfByte(CS.getStart()),
1696 diag::warn_format_mix_positional_nonpositional_args)
1697 << getSpecifierRange(startSpecifier, specifierLen);
1698 return false;
1699 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001700 }
1701
1702 // Check if the field with is non-zero.
1703 const OptionalAmount &Amt = FS.getFieldWidth();
1704 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1705 if (Amt.getConstantAmount() == 0) {
1706 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1707 Amt.getConstantLength());
1708 S.Diag(getLocationOfByte(Amt.getStart()),
1709 diag::warn_scanf_nonzero_width)
1710 << R << FixItHint::CreateRemoval(R);
1711 }
1712 }
1713
1714 if (!FS.consumesDataArgument()) {
1715 // FIXME: Technically specifying a precision or field width here
1716 // makes no sense. Worth issuing a warning at some point.
1717 return true;
1718 }
1719
1720 // Consume the argument.
1721 unsigned argIndex = FS.getArgIndex();
1722 if (argIndex < NumDataArgs) {
1723 // The check to see if the argIndex is valid will come later.
1724 // We set the bit here because we may exit early from this
1725 // function if we encounter some other error.
1726 CoveredArgs.set(argIndex);
1727 }
1728
Ted Kremenek1e51c202010-07-20 20:04:47 +00001729 // Check the length modifier is valid with the given conversion specifier.
1730 const LengthModifier &LM = FS.getLengthModifier();
1731 if (!FS.hasValidLengthModifier()) {
1732 S.Diag(getLocationOfByte(LM.getStart()),
1733 diag::warn_format_nonsensical_length)
1734 << LM.toString() << CS.toString()
1735 << getSpecifierRange(startSpecifier, specifierLen)
1736 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1737 LM.getLength()));
1738 }
1739
Ted Kremenek826a3452010-07-16 02:11:22 +00001740 // The remaining checks depend on the data arguments.
1741 if (HasVAListArg)
1742 return true;
1743
Ted Kremenek666a1972010-07-26 19:45:42 +00001744 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001745 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001746
1747 // FIXME: Check that the argument type matches the format specifier.
1748
1749 return true;
1750}
1751
1752void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001753 const Expr *OrigFormatExpr,
1754 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001755 unsigned format_idx, unsigned firstDataArg,
1756 bool isPrintf) {
1757
Ted Kremeneke0e53132010-01-28 23:39:18 +00001758 // CHECK: is the format string a wide literal?
1759 if (FExpr->isWide()) {
1760 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001761 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001762 << OrigFormatExpr->getSourceRange();
1763 return;
1764 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001765
Ted Kremeneke0e53132010-01-28 23:39:18 +00001766 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001767 llvm::StringRef StrRef = FExpr->getString();
1768 const char *Str = StrRef.data();
1769 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001770
Ted Kremeneke0e53132010-01-28 23:39:18 +00001771 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001772 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001773 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001774 << OrigFormatExpr->getSourceRange();
1775 return;
1776 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001777
1778 if (isPrintf) {
1779 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1780 TheCall->getNumArgs() - firstDataArg,
1781 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1782 HasVAListArg, TheCall, format_idx);
1783
1784 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1785 H.DoneProcessing();
1786 }
1787 else {
1788 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1789 TheCall->getNumArgs() - firstDataArg,
1790 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1791 HasVAListArg, TheCall, format_idx);
1792
1793 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1794 H.DoneProcessing();
1795 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001796}
1797
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001798//===--- CHECK: Standard memory functions ---------------------------------===//
1799
1800/// \brief Check for dangerous or invalid arguments to memset().
1801///
1802/// This issues warnings on known problematic or dangerous or unspecified
1803/// arguments to the standard 'memset' function call.
1804///
1805/// \param Call The call expression to diagnose.
1806void Sema::CheckMemsetArguments(const CallExpr *Call) {
1807 assert(Call->getNumArgs() == 3 && "Unexpected number of arguments to memset");
1808 const Expr *Dest = Call->getArg(0)->IgnoreParenImpCasts();
1809
1810 QualType DestTy = Dest->getType();
1811 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1812 QualType PointeeTy = DestPtrTy->getPointeeType();
1813 if (!PointeeTy->isPODType()) {
1814 DiagRuntimeBehavior(
1815 Dest->getExprLoc(), Dest,
1816 PDiag(diag::warn_non_pod_memset)
1817 << PointeeTy << Call->getCallee()->getSourceRange());
1818
1819 SourceRange ArgRange = Call->getArg(0)->getSourceRange();
1820 DiagRuntimeBehavior(
1821 Dest->getExprLoc(), Dest,
1822 PDiag(diag::note_non_pod_memset_silence)
1823 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
1824 }
1825 }
1826}
1827
Ted Kremenek06de2762007-08-17 16:46:58 +00001828//===--- CHECK: Return Address of Stack Variable --------------------------===//
1829
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001830static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1831static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001832
1833/// CheckReturnStackAddr - Check if a return statement returns the address
1834/// of a stack variable.
1835void
1836Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1837 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001838
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001839 Expr *stackE = 0;
1840 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1841
1842 // Perform checking for returned stack addresses, local blocks,
1843 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001844 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001845 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001846 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001847 stackE = EvalVal(RetValExp, refVars);
1848 }
1849
1850 if (stackE == 0)
1851 return; // Nothing suspicious was found.
1852
1853 SourceLocation diagLoc;
1854 SourceRange diagRange;
1855 if (refVars.empty()) {
1856 diagLoc = stackE->getLocStart();
1857 diagRange = stackE->getSourceRange();
1858 } else {
1859 // We followed through a reference variable. 'stackE' contains the
1860 // problematic expression but we will warn at the return statement pointing
1861 // at the reference variable. We will later display the "trail" of
1862 // reference variables using notes.
1863 diagLoc = refVars[0]->getLocStart();
1864 diagRange = refVars[0]->getSourceRange();
1865 }
1866
1867 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1868 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1869 : diag::warn_ret_stack_addr)
1870 << DR->getDecl()->getDeclName() << diagRange;
1871 } else if (isa<BlockExpr>(stackE)) { // local block.
1872 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1873 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1874 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1875 } else { // local temporary.
1876 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1877 : diag::warn_ret_local_temp_addr)
1878 << diagRange;
1879 }
1880
1881 // Display the "trail" of reference variables that we followed until we
1882 // found the problematic expression using notes.
1883 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1884 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1885 // If this var binds to another reference var, show the range of the next
1886 // var, otherwise the var binds to the problematic expression, in which case
1887 // show the range of the expression.
1888 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1889 : stackE->getSourceRange();
1890 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1891 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001892 }
1893}
1894
1895/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1896/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001897/// to a location on the stack, a local block, an address of a label, or a
1898/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001899/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001900/// encounter a subexpression that (1) clearly does not lead to one of the
1901/// above problematic expressions (2) is something we cannot determine leads to
1902/// a problematic expression based on such local checking.
1903///
1904/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1905/// the expression that they point to. Such variables are added to the
1906/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001907///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001908/// EvalAddr processes expressions that are pointers that are used as
1909/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001910/// At the base case of the recursion is a check for the above problematic
1911/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001912///
1913/// This implementation handles:
1914///
1915/// * pointer-to-pointer casts
1916/// * implicit conversions from array references to pointers
1917/// * taking the address of fields
1918/// * arbitrary interplay between "&" and "*" operators
1919/// * pointer arithmetic from an address of a stack variable
1920/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001921static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1922 if (E->isTypeDependent())
1923 return NULL;
1924
Ted Kremenek06de2762007-08-17 16:46:58 +00001925 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001926 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001927 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001928 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001929 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001930
Peter Collingbournef111d932011-04-15 00:35:48 +00001931 E = E->IgnoreParens();
1932
Ted Kremenek06de2762007-08-17 16:46:58 +00001933 // Our "symbolic interpreter" is just a dispatch off the currently
1934 // viewed AST node. We then recursively traverse the AST by calling
1935 // EvalAddr and EvalVal appropriately.
1936 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001937 case Stmt::DeclRefExprClass: {
1938 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1939
1940 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1941 // If this is a reference variable, follow through to the expression that
1942 // it points to.
1943 if (V->hasLocalStorage() &&
1944 V->getType()->isReferenceType() && V->hasInit()) {
1945 // Add the reference variable to the "trail".
1946 refVars.push_back(DR);
1947 return EvalAddr(V->getInit(), refVars);
1948 }
1949
1950 return NULL;
1951 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001952
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001953 case Stmt::UnaryOperatorClass: {
1954 // The only unary operator that make sense to handle here
1955 // is AddrOf. All others don't make sense as pointers.
1956 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001957
John McCall2de56d12010-08-25 11:45:40 +00001958 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001959 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001960 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001961 return NULL;
1962 }
Mike Stump1eb44332009-09-09 15:08:12 +00001963
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001964 case Stmt::BinaryOperatorClass: {
1965 // Handle pointer arithmetic. All other binary operators are not valid
1966 // in this context.
1967 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001968 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001969
John McCall2de56d12010-08-25 11:45:40 +00001970 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001971 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001972
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001973 Expr *Base = B->getLHS();
1974
1975 // Determine which argument is the real pointer base. It could be
1976 // the RHS argument instead of the LHS.
1977 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001979 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001980 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001981 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001982
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001983 // For conditional operators we need to see if either the LHS or RHS are
1984 // valid DeclRefExpr*s. If one of them is valid, we return it.
1985 case Stmt::ConditionalOperatorClass: {
1986 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001988 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001989 if (Expr *lhsExpr = C->getLHS()) {
1990 // In C++, we can have a throw-expression, which has 'void' type.
1991 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001992 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001993 return LHS;
1994 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001995
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001996 // In C++, we can have a throw-expression, which has 'void' type.
1997 if (C->getRHS()->getType()->isVoidType())
1998 return NULL;
1999
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002000 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002001 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002002
2003 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002004 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002005 return E; // local block.
2006 return NULL;
2007
2008 case Stmt::AddrLabelExprClass:
2009 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenek54b52742008-08-07 00:49:01 +00002011 // For casts, we need to handle conversions from arrays to
2012 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002013 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002014 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002015 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002016 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002017 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002018
Steve Naroffdd972f22008-09-05 22:11:13 +00002019 if (SubExpr->getType()->isPointerType() ||
2020 SubExpr->getType()->isBlockPointerType() ||
2021 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002022 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002023 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002024 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002025 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002026 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002029 // C++ casts. For dynamic casts, static casts, and const casts, we
2030 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002031 // through the cast. In the case the dynamic cast doesn't fail (and
2032 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002033 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002034 // FIXME: The comment about is wrong; we're not always converting
2035 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002036 // handle references to objects.
2037 case Stmt::CXXStaticCastExprClass:
2038 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002039 case Stmt::CXXConstCastExprClass:
2040 case Stmt::CXXReinterpretCastExprClass: {
2041 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002042 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002043 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002044 else
2045 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002046 }
Mike Stump1eb44332009-09-09 15:08:12 +00002047
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002048 // Everything else: we simply don't reason about them.
2049 default:
2050 return NULL;
2051 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002052}
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Ted Kremenek06de2762007-08-17 16:46:58 +00002054
2055/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2056/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002057static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002058do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002059 // We should only be called for evaluating non-pointer expressions, or
2060 // expressions with a pointer type that are not used as references but instead
2061 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002062
Ted Kremenek06de2762007-08-17 16:46:58 +00002063 // Our "symbolic interpreter" is just a dispatch off the currently
2064 // viewed AST node. We then recursively traverse the AST by calling
2065 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002066
2067 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002068 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002069 case Stmt::ImplicitCastExprClass: {
2070 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002071 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002072 E = IE->getSubExpr();
2073 continue;
2074 }
2075 return NULL;
2076 }
2077
Douglas Gregora2813ce2009-10-23 18:54:35 +00002078 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002079 // When we hit a DeclRefExpr we are looking at code that refers to a
2080 // variable's name. If it's not a reference variable we check if it has
2081 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002082 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenek06de2762007-08-17 16:46:58 +00002084 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002085 if (V->hasLocalStorage()) {
2086 if (!V->getType()->isReferenceType())
2087 return DR;
2088
2089 // Reference variable, follow through to the expression that
2090 // it points to.
2091 if (V->hasInit()) {
2092 // Add the reference variable to the "trail".
2093 refVars.push_back(DR);
2094 return EvalVal(V->getInit(), refVars);
2095 }
2096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Ted Kremenek06de2762007-08-17 16:46:58 +00002098 return NULL;
2099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Ted Kremenek06de2762007-08-17 16:46:58 +00002101 case Stmt::UnaryOperatorClass: {
2102 // The only unary operator that make sense to handle here
2103 // is Deref. All others don't resolve to a "name." This includes
2104 // handling all sorts of rvalues passed to a unary operator.
2105 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002106
John McCall2de56d12010-08-25 11:45:40 +00002107 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002108 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002109
2110 return NULL;
2111 }
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Ted Kremenek06de2762007-08-17 16:46:58 +00002113 case Stmt::ArraySubscriptExprClass: {
2114 // Array subscripts are potential references to data on the stack. We
2115 // retrieve the DeclRefExpr* for the array variable if it indeed
2116 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002117 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002118 }
Mike Stump1eb44332009-09-09 15:08:12 +00002119
Ted Kremenek06de2762007-08-17 16:46:58 +00002120 case Stmt::ConditionalOperatorClass: {
2121 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002122 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002123 ConditionalOperator *C = cast<ConditionalOperator>(E);
2124
Anders Carlsson39073232007-11-30 19:04:31 +00002125 // Handle the GNU extension for missing LHS.
2126 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002127 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002128 return LHS;
2129
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002130 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002131 }
Mike Stump1eb44332009-09-09 15:08:12 +00002132
Ted Kremenek06de2762007-08-17 16:46:58 +00002133 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002134 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002135 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Ted Kremenek06de2762007-08-17 16:46:58 +00002137 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002138 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002139 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002140
2141 // Check whether the member type is itself a reference, in which case
2142 // we're not going to refer to the member, but to what the member refers to.
2143 if (M->getMemberDecl()->getType()->isReferenceType())
2144 return NULL;
2145
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002146 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002147 }
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Ted Kremenek06de2762007-08-17 16:46:58 +00002149 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002150 // Check that we don't return or take the address of a reference to a
2151 // temporary. This is only useful in C++.
2152 if (!E->isTypeDependent() && E->isRValue())
2153 return E;
2154
2155 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002156 return NULL;
2157 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002158} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002159}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002160
2161//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2162
2163/// Check for comparisons of floating point operands using != and ==.
2164/// Issue a warning if these are no self-comparisons, as they are not likely
2165/// to do what the programmer intended.
2166void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2167 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002168
John McCallf6a16482010-12-04 03:47:34 +00002169 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2170 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002171
2172 // Special case: check for x == x (which is OK).
2173 // Do not emit warnings for such cases.
2174 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2175 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2176 if (DRL->getDecl() == DRR->getDecl())
2177 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002178
2179
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002180 // Special case: check for comparisons against literals that can be exactly
2181 // represented by APFloat. In such cases, do not emit a warning. This
2182 // is a heuristic: often comparison against such literals are used to
2183 // detect if a value in a variable has not changed. This clearly can
2184 // lead to false negatives.
2185 if (EmitWarning) {
2186 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2187 if (FLL->isExact())
2188 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002189 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002190 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2191 if (FLR->isExact())
2192 EmitWarning = false;
2193 }
2194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002196 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002197 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002198 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002199 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002200 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Sebastian Redl0eb23302009-01-19 00:08:26 +00002202 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002203 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002204 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002205 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002207 // Emit the diagnostic.
2208 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002209 Diag(loc, diag::warn_floatingpoint_eq)
2210 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002211}
John McCallba26e582010-01-04 23:21:16 +00002212
John McCallf2370c92010-01-06 05:24:50 +00002213//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2214//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002215
John McCallf2370c92010-01-06 05:24:50 +00002216namespace {
John McCallba26e582010-01-04 23:21:16 +00002217
John McCallf2370c92010-01-06 05:24:50 +00002218/// Structure recording the 'active' range of an integer-valued
2219/// expression.
2220struct IntRange {
2221 /// The number of bits active in the int.
2222 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002223
John McCallf2370c92010-01-06 05:24:50 +00002224 /// True if the int is known not to have negative values.
2225 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002226
John McCallf2370c92010-01-06 05:24:50 +00002227 IntRange(unsigned Width, bool NonNegative)
2228 : Width(Width), NonNegative(NonNegative)
2229 {}
John McCallba26e582010-01-04 23:21:16 +00002230
John McCall1844a6e2010-11-10 23:38:19 +00002231 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002232 static IntRange forBoolType() {
2233 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002234 }
2235
John McCall1844a6e2010-11-10 23:38:19 +00002236 /// Returns the range of an opaque value of the given integral type.
2237 static IntRange forValueOfType(ASTContext &C, QualType T) {
2238 return forValueOfCanonicalType(C,
2239 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002240 }
2241
John McCall1844a6e2010-11-10 23:38:19 +00002242 /// Returns the range of an opaque value of a canonical integral type.
2243 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002244 assert(T->isCanonicalUnqualified());
2245
2246 if (const VectorType *VT = dyn_cast<VectorType>(T))
2247 T = VT->getElementType().getTypePtr();
2248 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2249 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002250
John McCall091f23f2010-11-09 22:22:12 +00002251 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002252 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2253 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002254 if (!Enum->isDefinition())
2255 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2256
John McCall323ed742010-05-06 08:58:33 +00002257 unsigned NumPositive = Enum->getNumPositiveBits();
2258 unsigned NumNegative = Enum->getNumNegativeBits();
2259
2260 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2261 }
John McCallf2370c92010-01-06 05:24:50 +00002262
2263 const BuiltinType *BT = cast<BuiltinType>(T);
2264 assert(BT->isInteger());
2265
2266 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2267 }
2268
John McCall1844a6e2010-11-10 23:38:19 +00002269 /// Returns the "target" range of a canonical integral type, i.e.
2270 /// the range of values expressible in the type.
2271 ///
2272 /// This matches forValueOfCanonicalType except that enums have the
2273 /// full range of their type, not the range of their enumerators.
2274 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2275 assert(T->isCanonicalUnqualified());
2276
2277 if (const VectorType *VT = dyn_cast<VectorType>(T))
2278 T = VT->getElementType().getTypePtr();
2279 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2280 T = CT->getElementType().getTypePtr();
2281 if (const EnumType *ET = dyn_cast<EnumType>(T))
2282 T = ET->getDecl()->getIntegerType().getTypePtr();
2283
2284 const BuiltinType *BT = cast<BuiltinType>(T);
2285 assert(BT->isInteger());
2286
2287 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2288 }
2289
2290 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002291 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002292 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002293 L.NonNegative && R.NonNegative);
2294 }
2295
John McCall1844a6e2010-11-10 23:38:19 +00002296 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002297 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002298 return IntRange(std::min(L.Width, R.Width),
2299 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002300 }
2301};
2302
2303IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2304 if (value.isSigned() && value.isNegative())
2305 return IntRange(value.getMinSignedBits(), false);
2306
2307 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002308 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002309
2310 // isNonNegative() just checks the sign bit without considering
2311 // signedness.
2312 return IntRange(value.getActiveBits(), true);
2313}
2314
John McCall0acc3112010-01-06 22:57:21 +00002315IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002316 unsigned MaxWidth) {
2317 if (result.isInt())
2318 return GetValueRange(C, result.getInt(), MaxWidth);
2319
2320 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002321 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2322 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2323 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2324 R = IntRange::join(R, El);
2325 }
John McCallf2370c92010-01-06 05:24:50 +00002326 return R;
2327 }
2328
2329 if (result.isComplexInt()) {
2330 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2331 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2332 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002333 }
2334
2335 // This can happen with lossless casts to intptr_t of "based" lvalues.
2336 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002337 // FIXME: The only reason we need to pass the type in here is to get
2338 // the sign right on this one case. It would be nice if APValue
2339 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002340 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002341 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002342}
John McCallf2370c92010-01-06 05:24:50 +00002343
2344/// Pseudo-evaluate the given integer expression, estimating the
2345/// range of values it might take.
2346///
2347/// \param MaxWidth - the width to which the value will be truncated
2348IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2349 E = E->IgnoreParens();
2350
2351 // Try a full evaluation first.
2352 Expr::EvalResult result;
2353 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002354 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002355
2356 // I think we only want to look through implicit casts here; if the
2357 // user has an explicit widening cast, we should treat the value as
2358 // being of the new, wider type.
2359 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002360 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002361 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2362
John McCall1844a6e2010-11-10 23:38:19 +00002363 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002364
John McCall2de56d12010-08-25 11:45:40 +00002365 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002366
John McCallf2370c92010-01-06 05:24:50 +00002367 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002368 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002369 return OutputTypeRange;
2370
2371 IntRange SubRange
2372 = GetExprRange(C, CE->getSubExpr(),
2373 std::min(MaxWidth, OutputTypeRange.Width));
2374
2375 // Bail out if the subexpr's range is as wide as the cast type.
2376 if (SubRange.Width >= OutputTypeRange.Width)
2377 return OutputTypeRange;
2378
2379 // Otherwise, we take the smaller width, and we're non-negative if
2380 // either the output type or the subexpr is.
2381 return IntRange(SubRange.Width,
2382 SubRange.NonNegative || OutputTypeRange.NonNegative);
2383 }
2384
2385 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2386 // If we can fold the condition, just take that operand.
2387 bool CondResult;
2388 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2389 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2390 : CO->getFalseExpr(),
2391 MaxWidth);
2392
2393 // Otherwise, conservatively merge.
2394 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2395 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2396 return IntRange::join(L, R);
2397 }
2398
2399 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2400 switch (BO->getOpcode()) {
2401
2402 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002403 case BO_LAnd:
2404 case BO_LOr:
2405 case BO_LT:
2406 case BO_GT:
2407 case BO_LE:
2408 case BO_GE:
2409 case BO_EQ:
2410 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002411 return IntRange::forBoolType();
2412
John McCallc0cd21d2010-02-23 19:22:29 +00002413 // The type of these compound assignments is the type of the LHS,
2414 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002415 case BO_MulAssign:
2416 case BO_DivAssign:
2417 case BO_RemAssign:
2418 case BO_AddAssign:
2419 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002420 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002421
John McCallf2370c92010-01-06 05:24:50 +00002422 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002423 case BO_PtrMemD:
2424 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002425 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002426
John McCall60fad452010-01-06 22:07:33 +00002427 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002428 case BO_And:
2429 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002430 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2431 GetExprRange(C, BO->getRHS(), MaxWidth));
2432
John McCallf2370c92010-01-06 05:24:50 +00002433 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002434 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002435 // ...except that we want to treat '1 << (blah)' as logically
2436 // positive. It's an important idiom.
2437 if (IntegerLiteral *I
2438 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2439 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002440 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002441 return IntRange(R.Width, /*NonNegative*/ true);
2442 }
2443 }
2444 // fallthrough
2445
John McCall2de56d12010-08-25 11:45:40 +00002446 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002447 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002448
John McCall60fad452010-01-06 22:07:33 +00002449 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002450 case BO_Shr:
2451 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002452 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2453
2454 // If the shift amount is a positive constant, drop the width by
2455 // that much.
2456 llvm::APSInt shift;
2457 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2458 shift.isNonNegative()) {
2459 unsigned zext = shift.getZExtValue();
2460 if (zext >= L.Width)
2461 L.Width = (L.NonNegative ? 0 : 1);
2462 else
2463 L.Width -= zext;
2464 }
2465
2466 return L;
2467 }
2468
2469 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002470 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002471 return GetExprRange(C, BO->getRHS(), MaxWidth);
2472
John McCall60fad452010-01-06 22:07:33 +00002473 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002474 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002475 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002476 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002477 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002478
John McCallf2370c92010-01-06 05:24:50 +00002479 default:
2480 break;
2481 }
2482
2483 // Treat every other operator as if it were closed on the
2484 // narrowest type that encompasses both operands.
2485 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2486 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2487 return IntRange::join(L, R);
2488 }
2489
2490 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2491 switch (UO->getOpcode()) {
2492 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002493 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002494 return IntRange::forBoolType();
2495
2496 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002497 case UO_Deref:
2498 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002499 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002500
2501 default:
2502 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2503 }
2504 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002505
2506 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002507 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002508 }
John McCallf2370c92010-01-06 05:24:50 +00002509
2510 FieldDecl *BitField = E->getBitField();
2511 if (BitField) {
2512 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2513 unsigned BitWidth = BitWidthAP.getZExtValue();
2514
2515 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2516 }
2517
John McCall1844a6e2010-11-10 23:38:19 +00002518 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002519}
John McCall51313c32010-01-04 23:31:57 +00002520
John McCall323ed742010-05-06 08:58:33 +00002521IntRange GetExprRange(ASTContext &C, Expr *E) {
2522 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2523}
2524
John McCall51313c32010-01-04 23:31:57 +00002525/// Checks whether the given value, which currently has the given
2526/// source semantics, has the same value when coerced through the
2527/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002528bool IsSameFloatAfterCast(const llvm::APFloat &value,
2529 const llvm::fltSemantics &Src,
2530 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002531 llvm::APFloat truncated = value;
2532
2533 bool ignored;
2534 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2535 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2536
2537 return truncated.bitwiseIsEqual(value);
2538}
2539
2540/// Checks whether the given value, which currently has the given
2541/// source semantics, has the same value when coerced through the
2542/// target semantics.
2543///
2544/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002545bool IsSameFloatAfterCast(const APValue &value,
2546 const llvm::fltSemantics &Src,
2547 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002548 if (value.isFloat())
2549 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2550
2551 if (value.isVector()) {
2552 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2553 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2554 return false;
2555 return true;
2556 }
2557
2558 assert(value.isComplexFloat());
2559 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2560 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2561}
2562
John McCallb4eb64d2010-10-08 02:01:28 +00002563void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002564
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002565static bool IsZero(Sema &S, Expr *E) {
2566 // Suppress cases where we are comparing against an enum constant.
2567 if (const DeclRefExpr *DR =
2568 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2569 if (isa<EnumConstantDecl>(DR->getDecl()))
2570 return false;
2571
2572 // Suppress cases where the '0' value is expanded from a macro.
2573 if (E->getLocStart().isMacroID())
2574 return false;
2575
John McCall323ed742010-05-06 08:58:33 +00002576 llvm::APSInt Value;
2577 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2578}
2579
John McCall372e1032010-10-06 00:25:24 +00002580static bool HasEnumType(Expr *E) {
2581 // Strip off implicit integral promotions.
2582 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002583 if (ICE->getCastKind() != CK_IntegralCast &&
2584 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002585 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002586 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002587 }
2588
2589 return E->getType()->isEnumeralType();
2590}
2591
John McCall323ed742010-05-06 08:58:33 +00002592void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002593 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002594 if (E->isValueDependent())
2595 return;
2596
John McCall2de56d12010-08-25 11:45:40 +00002597 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002598 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002599 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002600 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002601 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002602 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002603 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002604 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002605 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002606 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002607 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002608 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002609 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002610 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002611 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002612 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2613 }
2614}
2615
2616/// Analyze the operands of the given comparison. Implements the
2617/// fallback case from AnalyzeComparison.
2618void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002619 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2620 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002621}
John McCall51313c32010-01-04 23:31:57 +00002622
John McCallba26e582010-01-04 23:21:16 +00002623/// \brief Implements -Wsign-compare.
2624///
2625/// \param lex the left-hand expression
2626/// \param rex the right-hand expression
2627/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002628/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002629void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2630 // The type the comparison is being performed in.
2631 QualType T = E->getLHS()->getType();
2632 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2633 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002634
John McCall323ed742010-05-06 08:58:33 +00002635 // We don't do anything special if this isn't an unsigned integral
2636 // comparison: we're only interested in integral comparisons, and
2637 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002638 //
2639 // We also don't care about value-dependent expressions or expressions
2640 // whose result is a constant.
2641 if (!T->hasUnsignedIntegerRepresentation()
2642 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002643 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002644
John McCall323ed742010-05-06 08:58:33 +00002645 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2646 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002647
John McCall323ed742010-05-06 08:58:33 +00002648 // Check to see if one of the (unmodified) operands is of different
2649 // signedness.
2650 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002651 if (lex->getType()->hasSignedIntegerRepresentation()) {
2652 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002653 "unsigned comparison between two signed integer expressions?");
2654 signedOperand = lex;
2655 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002656 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002657 signedOperand = rex;
2658 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002659 } else {
John McCall323ed742010-05-06 08:58:33 +00002660 CheckTrivialUnsignedComparison(S, E);
2661 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002662 }
2663
John McCall323ed742010-05-06 08:58:33 +00002664 // Otherwise, calculate the effective range of the signed operand.
2665 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002666
John McCall323ed742010-05-06 08:58:33 +00002667 // Go ahead and analyze implicit conversions in the operands. Note
2668 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002669 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2670 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002671
John McCall323ed742010-05-06 08:58:33 +00002672 // If the signed range is non-negative, -Wsign-compare won't fire,
2673 // but we should still check for comparisons which are always true
2674 // or false.
2675 if (signedRange.NonNegative)
2676 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002677
2678 // For (in)equality comparisons, if the unsigned operand is a
2679 // constant which cannot collide with a overflowed signed operand,
2680 // then reinterpreting the signed operand as unsigned will not
2681 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002682 if (E->isEqualityOp()) {
2683 unsigned comparisonWidth = S.Context.getIntWidth(T);
2684 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002685
John McCall323ed742010-05-06 08:58:33 +00002686 // We should never be unable to prove that the unsigned operand is
2687 // non-negative.
2688 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2689
2690 if (unsignedRange.Width < comparisonWidth)
2691 return;
2692 }
2693
2694 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2695 << lex->getType() << rex->getType()
2696 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002697}
2698
John McCall15d7d122010-11-11 03:21:53 +00002699/// Analyzes an attempt to assign the given value to a bitfield.
2700///
2701/// Returns true if there was something fishy about the attempt.
2702bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2703 SourceLocation InitLoc) {
2704 assert(Bitfield->isBitField());
2705 if (Bitfield->isInvalidDecl())
2706 return false;
2707
John McCall91b60142010-11-11 05:33:51 +00002708 // White-list bool bitfields.
2709 if (Bitfield->getType()->isBooleanType())
2710 return false;
2711
Douglas Gregor46ff3032011-02-04 13:09:01 +00002712 // Ignore value- or type-dependent expressions.
2713 if (Bitfield->getBitWidth()->isValueDependent() ||
2714 Bitfield->getBitWidth()->isTypeDependent() ||
2715 Init->isValueDependent() ||
2716 Init->isTypeDependent())
2717 return false;
2718
John McCall15d7d122010-11-11 03:21:53 +00002719 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2720
2721 llvm::APSInt Width(32);
2722 Expr::EvalResult InitValue;
2723 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002724 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002725 !InitValue.Val.isInt())
2726 return false;
2727
2728 const llvm::APSInt &Value = InitValue.Val.getInt();
2729 unsigned OriginalWidth = Value.getBitWidth();
2730 unsigned FieldWidth = Width.getZExtValue();
2731
2732 if (OriginalWidth <= FieldWidth)
2733 return false;
2734
Jay Foad9f71a8f2010-12-07 08:25:34 +00002735 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002736
2737 // It's fairly common to write values into signed bitfields
2738 // that, if sign-extended, would end up becoming a different
2739 // value. We don't want to warn about that.
2740 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002741 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002742 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002743 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002744
2745 if (Value == TruncatedValue)
2746 return false;
2747
2748 std::string PrettyValue = Value.toString(10);
2749 std::string PrettyTrunc = TruncatedValue.toString(10);
2750
2751 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2752 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2753 << Init->getSourceRange();
2754
2755 return true;
2756}
2757
John McCallbeb22aa2010-11-09 23:24:47 +00002758/// Analyze the given simple or compound assignment for warning-worthy
2759/// operations.
2760void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2761 // Just recurse on the LHS.
2762 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2763
2764 // We want to recurse on the RHS as normal unless we're assigning to
2765 // a bitfield.
2766 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002767 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2768 E->getOperatorLoc())) {
2769 // Recurse, ignoring any implicit conversions on the RHS.
2770 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2771 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002772 }
2773 }
2774
2775 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2776}
2777
John McCall51313c32010-01-04 23:31:57 +00002778/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002779void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2780 SourceLocation CContext, unsigned diag) {
2781 S.Diag(E->getExprLoc(), diag)
2782 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2783}
2784
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002785/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2786void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2787 unsigned diag) {
2788 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2789}
2790
Chandler Carruthf65076e2011-04-10 08:36:24 +00002791/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2792/// fixit hints when the cast wouldn't lose information to simply write the
2793/// expression with the expected type.
2794void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2795 SourceLocation CContext) {
2796 // Emit the primary warning first, then try to emit a fixit hint note if
2797 // reasonable.
2798 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2799 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2800
2801 const llvm::APFloat &Value = FL->getValue();
2802
2803 // Don't attempt to fix PPC double double literals.
2804 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2805 return;
2806
2807 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2808 // nice to support arbitrarily large integers here.
2809 bool isExact = false;
2810 uint64_t IntegerPart;
2811 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2812 llvm::APFloat::rmTowardZero, &isExact)
2813 != llvm::APFloat::opOK || !isExact)
2814 return;
2815
2816 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2817
2818 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2819 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2820 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2821}
2822
John McCall091f23f2010-11-09 22:22:12 +00002823std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2824 if (!Range.Width) return "0";
2825
2826 llvm::APSInt ValueInRange = Value;
2827 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002828 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002829 return ValueInRange.toString(10);
2830}
2831
Ted Kremenekef9ff882011-03-10 20:03:42 +00002832static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2833 SourceManager &smgr = S.Context.getSourceManager();
2834 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2835}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002836
John McCall323ed742010-05-06 08:58:33 +00002837void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002838 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002839 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002840
John McCall323ed742010-05-06 08:58:33 +00002841 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2842 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2843 if (Source == Target) return;
2844 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002845
Ted Kremenekef9ff882011-03-10 20:03:42 +00002846 // If the conversion context location is invalid don't complain.
2847 // We also don't want to emit a warning if the issue occurs from the
2848 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2849 // is slow, so we delay this check as long as possible. Once we detect
2850 // we are in that scenario, we just return.
2851 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002852 return;
2853
John McCall51313c32010-01-04 23:31:57 +00002854 // Never diagnose implicit casts to bool.
2855 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2856 return;
2857
2858 // Strip vector types.
2859 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002860 if (!isa<VectorType>(Target)) {
2861 if (isFromSystemMacro(S, CC))
2862 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002863 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002864 }
John McCall51313c32010-01-04 23:31:57 +00002865
2866 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2867 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2868 }
2869
2870 // Strip complex types.
2871 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002872 if (!isa<ComplexType>(Target)) {
2873 if (isFromSystemMacro(S, CC))
2874 return;
2875
John McCallb4eb64d2010-10-08 02:01:28 +00002876 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002877 }
John McCall51313c32010-01-04 23:31:57 +00002878
2879 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2880 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2881 }
2882
2883 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2884 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2885
2886 // If the source is floating point...
2887 if (SourceBT && SourceBT->isFloatingPoint()) {
2888 // ...and the target is floating point...
2889 if (TargetBT && TargetBT->isFloatingPoint()) {
2890 // ...then warn if we're dropping FP rank.
2891
2892 // Builtin FP kinds are ordered by increasing FP rank.
2893 if (SourceBT->getKind() > TargetBT->getKind()) {
2894 // Don't warn about float constants that are precisely
2895 // representable in the target type.
2896 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002897 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002898 // Value might be a float, a float vector, or a float complex.
2899 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002900 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2901 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002902 return;
2903 }
2904
Ted Kremenekef9ff882011-03-10 20:03:42 +00002905 if (isFromSystemMacro(S, CC))
2906 return;
2907
John McCallb4eb64d2010-10-08 02:01:28 +00002908 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002909 }
2910 return;
2911 }
2912
Ted Kremenekef9ff882011-03-10 20:03:42 +00002913 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002914 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002915 if (isFromSystemMacro(S, CC))
2916 return;
2917
Chandler Carrutha5b93322011-02-17 11:05:49 +00002918 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00002919 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
2920 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00002921 } else {
2922 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2923 }
2924 }
John McCall51313c32010-01-04 23:31:57 +00002925
2926 return;
2927 }
2928
John McCallf2370c92010-01-06 05:24:50 +00002929 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002930 return;
2931
John McCall323ed742010-05-06 08:58:33 +00002932 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002933 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002934
2935 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002936 // If the source is a constant, use a default-on diagnostic.
2937 // TODO: this should happen for bitfield stores, too.
2938 llvm::APSInt Value(32);
2939 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002940 if (isFromSystemMacro(S, CC))
2941 return;
2942
John McCall091f23f2010-11-09 22:22:12 +00002943 std::string PrettySourceValue = Value.toString(10);
2944 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2945
2946 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2947 << PrettySourceValue << PrettyTargetValue
2948 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2949 return;
2950 }
2951
John McCall51313c32010-01-04 23:31:57 +00002952 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2953 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002954
2955 if (isFromSystemMacro(S, CC))
2956 return;
2957
John McCallf2370c92010-01-06 05:24:50 +00002958 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002959 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2960 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002961 }
2962
2963 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2964 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2965 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002966
2967 if (isFromSystemMacro(S, CC))
2968 return;
2969
John McCall323ed742010-05-06 08:58:33 +00002970 unsigned DiagID = diag::warn_impcast_integer_sign;
2971
2972 // Traditionally, gcc has warned about this under -Wsign-compare.
2973 // We also want to warn about it in -Wconversion.
2974 // So if -Wconversion is off, use a completely identical diagnostic
2975 // in the sign-compare group.
2976 // The conditional-checking code will
2977 if (ICContext) {
2978 DiagID = diag::warn_impcast_integer_sign_conditional;
2979 *ICContext = true;
2980 }
2981
John McCallb4eb64d2010-10-08 02:01:28 +00002982 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002983 }
2984
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002985 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002986 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2987 // type, to give us better diagnostics.
2988 QualType SourceType = E->getType();
2989 if (!S.getLangOptions().CPlusPlus) {
2990 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2991 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2992 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2993 SourceType = S.Context.getTypeDeclType(Enum);
2994 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2995 }
2996 }
2997
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002998 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2999 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3000 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003001 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003002 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003003 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003004 SourceEnum != TargetEnum) {
3005 if (isFromSystemMacro(S, CC))
3006 return;
3007
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003008 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003009 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003010 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003011
John McCall51313c32010-01-04 23:31:57 +00003012 return;
3013}
3014
John McCall323ed742010-05-06 08:58:33 +00003015void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3016
3017void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003018 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003019 E = E->IgnoreParenImpCasts();
3020
3021 if (isa<ConditionalOperator>(E))
3022 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3023
John McCallb4eb64d2010-10-08 02:01:28 +00003024 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003025 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003026 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003027 return;
3028}
3029
3030void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003031 SourceLocation CC = E->getQuestionLoc();
3032
3033 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003034
3035 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003036 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3037 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003038
3039 // If -Wconversion would have warned about either of the candidates
3040 // for a signedness conversion to the context type...
3041 if (!Suspicious) return;
3042
3043 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003044 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3045 CC))
John McCall323ed742010-05-06 08:58:33 +00003046 return;
3047
3048 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003049 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003050 return;
3051
3052 // ...then check whether it would have warned about either of the
3053 // candidates for a signedness conversion to the condition type.
3054 if (E->getType() != T) {
3055 Suspicious = false;
3056 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003057 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003058 if (!Suspicious)
3059 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003060 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003061 if (!Suspicious)
3062 return;
3063 }
3064
3065 // If so, emit a diagnostic under -Wsign-compare.
3066 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3067 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3068 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3069 << lex->getType() << rex->getType()
3070 << lex->getSourceRange() << rex->getSourceRange();
3071}
3072
3073/// AnalyzeImplicitConversions - Find and report any interesting
3074/// implicit conversions in the given expression. There are a couple
3075/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003076void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003077 QualType T = OrigE->getType();
3078 Expr *E = OrigE->IgnoreParenImpCasts();
3079
3080 // For conditional operators, we analyze the arguments as if they
3081 // were being fed directly into the output.
3082 if (isa<ConditionalOperator>(E)) {
3083 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3084 CheckConditionalOperator(S, CO, T);
3085 return;
3086 }
3087
3088 // Go ahead and check any implicit conversions we might have skipped.
3089 // The non-canonical typecheck is just an optimization;
3090 // CheckImplicitConversion will filter out dead implicit conversions.
3091 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003092 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003093
3094 // Now continue drilling into this expression.
3095
3096 // Skip past explicit casts.
3097 if (isa<ExplicitCastExpr>(E)) {
3098 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003099 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003100 }
3101
John McCallbeb22aa2010-11-09 23:24:47 +00003102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3103 // Do a somewhat different check with comparison operators.
3104 if (BO->isComparisonOp())
3105 return AnalyzeComparison(S, BO);
3106
3107 // And with assignments and compound assignments.
3108 if (BO->isAssignmentOp())
3109 return AnalyzeAssignment(S, BO);
3110 }
John McCall323ed742010-05-06 08:58:33 +00003111
3112 // These break the otherwise-useful invariant below. Fortunately,
3113 // we don't really need to recurse into them, because any internal
3114 // expressions should have been analyzed already when they were
3115 // built into statements.
3116 if (isa<StmtExpr>(E)) return;
3117
3118 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003119 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003120
3121 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003122 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003123 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003124 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003125}
3126
3127} // end anonymous namespace
3128
3129/// Diagnoses "dangerous" implicit conversions within the given
3130/// expression (which is a full expression). Implements -Wconversion
3131/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003132///
3133/// \param CC the "context" location of the implicit conversion, i.e.
3134/// the most location of the syntactic entity requiring the implicit
3135/// conversion
3136void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003137 // Don't diagnose in unevaluated contexts.
3138 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3139 return;
3140
3141 // Don't diagnose for value- or type-dependent expressions.
3142 if (E->isTypeDependent() || E->isValueDependent())
3143 return;
3144
John McCallb4eb64d2010-10-08 02:01:28 +00003145 // This is not the right CC for (e.g.) a variable initialization.
3146 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003147}
3148
John McCall15d7d122010-11-11 03:21:53 +00003149void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3150 FieldDecl *BitField,
3151 Expr *Init) {
3152 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3153}
3154
Mike Stumpf8c49212010-01-21 03:59:47 +00003155/// CheckParmsForFunctionDef - Check that the parameters of the given
3156/// function are appropriate for the definition of a function. This
3157/// takes care of any checks that cannot be performed on the
3158/// declaration itself, e.g., that the types of each of the function
3159/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003160bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3161 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003162 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003163 for (; P != PEnd; ++P) {
3164 ParmVarDecl *Param = *P;
3165
Mike Stumpf8c49212010-01-21 03:59:47 +00003166 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3167 // function declarator that is part of a function definition of
3168 // that function shall not have incomplete type.
3169 //
3170 // This is also C++ [dcl.fct]p6.
3171 if (!Param->isInvalidDecl() &&
3172 RequireCompleteType(Param->getLocation(), Param->getType(),
3173 diag::err_typecheck_decl_incomplete_type)) {
3174 Param->setInvalidDecl();
3175 HasInvalidParm = true;
3176 }
3177
3178 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3179 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003180 if (CheckParameterNames &&
3181 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003182 !Param->isImplicit() &&
3183 !getLangOptions().CPlusPlus)
3184 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003185
3186 // C99 6.7.5.3p12:
3187 // If the function declarator is not part of a definition of that
3188 // function, parameters may have incomplete type and may use the [*]
3189 // notation in their sequences of declarator specifiers to specify
3190 // variable length array types.
3191 QualType PType = Param->getOriginalType();
3192 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3193 if (AT->getSizeModifier() == ArrayType::Star) {
3194 // FIXME: This diagnosic should point the the '[*]' if source-location
3195 // information is added for it.
3196 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3197 }
3198 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003199 }
3200
3201 return HasInvalidParm;
3202}
John McCallb7f4ffe2010-08-12 21:44:57 +00003203
3204/// CheckCastAlign - Implements -Wcast-align, which warns when a
3205/// pointer cast increases the alignment requirements.
3206void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3207 // This is actually a lot of work to potentially be doing on every
3208 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003209 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3210 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003211 == Diagnostic::Ignored)
3212 return;
3213
3214 // Ignore dependent types.
3215 if (T->isDependentType() || Op->getType()->isDependentType())
3216 return;
3217
3218 // Require that the destination be a pointer type.
3219 const PointerType *DestPtr = T->getAs<PointerType>();
3220 if (!DestPtr) return;
3221
3222 // If the destination has alignment 1, we're done.
3223 QualType DestPointee = DestPtr->getPointeeType();
3224 if (DestPointee->isIncompleteType()) return;
3225 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3226 if (DestAlign.isOne()) return;
3227
3228 // Require that the source be a pointer type.
3229 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3230 if (!SrcPtr) return;
3231 QualType SrcPointee = SrcPtr->getPointeeType();
3232
3233 // Whitelist casts from cv void*. We already implicitly
3234 // whitelisted casts to cv void*, since they have alignment 1.
3235 // Also whitelist casts involving incomplete types, which implicitly
3236 // includes 'void'.
3237 if (SrcPointee->isIncompleteType()) return;
3238
3239 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3240 if (SrcAlign >= DestAlign) return;
3241
3242 Diag(TRange.getBegin(), diag::warn_cast_align)
3243 << Op->getType() << T
3244 << static_cast<unsigned>(SrcAlign.getQuantity())
3245 << static_cast<unsigned>(DestAlign.getQuantity())
3246 << TRange << Op->getSourceRange();
3247}
3248
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003249static void CheckArrayAccess_Check(Sema &S,
3250 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003251 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003252 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003253 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003254 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003255 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003256
Chandler Carruth34064582011-02-17 20:55:08 +00003257 const Expr *IndexExpr = E->getIdx();
3258 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003259 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003260 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003261 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003262 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003263
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003264 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003265 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003266 if (!size.isStrictlyPositive())
3267 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003268 if (size.getBitWidth() > index.getBitWidth())
3269 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003270 else if (size.getBitWidth() < index.getBitWidth())
3271 size = size.sext(index.getBitWidth());
3272
Chandler Carruth34064582011-02-17 20:55:08 +00003273 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003274 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003275
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003276 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3277 S.PDiag(diag::warn_array_index_exceeds_bounds)
3278 << index.toString(10, true)
3279 << size.toString(10, true)
3280 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003281 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003282 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3283 S.PDiag(diag::warn_array_index_precedes_bounds)
3284 << index.toString(10, true)
3285 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003286 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003287
3288 const NamedDecl *ND = NULL;
3289 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3290 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3291 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3292 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3293 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003294 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3295 S.PDiag(diag::note_array_index_out_of_bounds)
3296 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003297}
3298
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003299void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003300 while (true) {
3301 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003302 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003303 case Stmt::ArraySubscriptExprClass:
3304 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3305 return;
3306 case Stmt::ConditionalOperatorClass: {
3307 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3308 if (const Expr *lhs = cond->getLHS())
3309 CheckArrayAccess(lhs);
3310 if (const Expr *rhs = cond->getRHS())
3311 CheckArrayAccess(rhs);
3312 return;
3313 }
3314 default:
3315 return;
3316 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003317 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003318}