blob: 76f20ce530c28bece4d8b5ed32418f45f9e13ee7 [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
Douglas Gregore452c782011-05-03 18:11:37 +0000322 if (FnInfo->isStr("memset") &&
323 FDecl->getLinkage() == ExternalLinkage &&
324 (!getLangOptions().CPlusPlus || FDecl->isExternC()))
Chandler Carruth7ccc95b2011-04-27 07:05:31 +0000325 CheckMemsetArguments(TheCall);
326
Anders Carlssond406bf02009-08-16 01:56:34 +0000327 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000328}
329
Anders Carlssond406bf02009-08-16 01:56:34 +0000330bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000331 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000332 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000333 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000334 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000336 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
337 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000338 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000340 QualType Ty = V->getType();
341 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000342 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Ted Kremenek826a3452010-07-16 02:11:22 +0000344 const bool b = Format->getType() == "scanf";
345 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000346 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Anders Carlssond406bf02009-08-16 01:56:34 +0000348 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000349 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
350 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000351
352 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000353}
354
Chris Lattner5caa3702009-05-08 06:58:22 +0000355/// SemaBuiltinAtomicOverloaded - We have a call to a function like
356/// __sync_fetch_and_add, which is an overloaded function based on the pointer
357/// type of its first argument. The main ActOnCallExpr routines have already
358/// promoted the types of arguments because all of these calls are prototyped as
359/// void(...).
360///
361/// This function goes through and does final semantic checking for these
362/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000363ExprResult
364Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000365 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000366 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
367 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
368
369 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000370 if (TheCall->getNumArgs() < 1) {
371 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
372 << 0 << 1 << TheCall->getNumArgs()
373 << TheCall->getCallee()->getSourceRange();
374 return ExprError();
375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Chris Lattner5caa3702009-05-08 06:58:22 +0000377 // Inspect the first argument of the atomic builtin. This should always be
378 // a pointer type, whose element is an integral scalar or pointer type.
379 // Because it is a pointer type, we don't have to worry about any implicit
380 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000381 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000382 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000383 if (!FirstArg->getType()->isPointerType()) {
384 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
385 << FirstArg->getType() << FirstArg->getSourceRange();
386 return ExprError();
387 }
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chandler Carruthd2014572010-07-09 18:59:35 +0000389 QualType ValType =
390 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000391 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000392 !ValType->isBlockPointerType()) {
393 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
394 << FirstArg->getType() << FirstArg->getSourceRange();
395 return ExprError();
396 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000397
Chandler Carruth8d13d222010-07-18 20:54:12 +0000398 // The majority of builtins return a value, but a few have special return
399 // types, so allow them to override appropriately below.
400 QualType ResultType = ValType;
401
Chris Lattner5caa3702009-05-08 06:58:22 +0000402 // We need to figure out which concrete builtin this maps onto. For example,
403 // __sync_fetch_and_add with a 2 byte object turns into
404 // __sync_fetch_and_add_2.
405#define BUILTIN_ROW(x) \
406 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
407 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000408
Chris Lattner5caa3702009-05-08 06:58:22 +0000409 static const unsigned BuiltinIndices[][5] = {
410 BUILTIN_ROW(__sync_fetch_and_add),
411 BUILTIN_ROW(__sync_fetch_and_sub),
412 BUILTIN_ROW(__sync_fetch_and_or),
413 BUILTIN_ROW(__sync_fetch_and_and),
414 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 BUILTIN_ROW(__sync_add_and_fetch),
417 BUILTIN_ROW(__sync_sub_and_fetch),
418 BUILTIN_ROW(__sync_and_and_fetch),
419 BUILTIN_ROW(__sync_or_and_fetch),
420 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000421
Chris Lattner5caa3702009-05-08 06:58:22 +0000422 BUILTIN_ROW(__sync_val_compare_and_swap),
423 BUILTIN_ROW(__sync_bool_compare_and_swap),
424 BUILTIN_ROW(__sync_lock_test_and_set),
Chris Lattner23aa9c82011-04-09 03:57:26 +0000425 BUILTIN_ROW(__sync_lock_release),
426 BUILTIN_ROW(__sync_swap)
Chris Lattner5caa3702009-05-08 06:58:22 +0000427 };
Mike Stump1eb44332009-09-09 15:08:12 +0000428#undef BUILTIN_ROW
429
Chris Lattner5caa3702009-05-08 06:58:22 +0000430 // Determine the index of the size.
431 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000432 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000433 case 1: SizeIndex = 0; break;
434 case 2: SizeIndex = 1; break;
435 case 4: SizeIndex = 2; break;
436 case 8: SizeIndex = 3; break;
437 case 16: SizeIndex = 4; break;
438 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000439 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
440 << FirstArg->getType() << FirstArg->getSourceRange();
441 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 // Each of these builtins has one pointer argument, followed by some number of
445 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
446 // that we ignore. Find out which row of BuiltinIndices to read from as well
447 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000448 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000449 unsigned BuiltinIndex, NumFixed = 1;
450 switch (BuiltinID) {
451 default: assert(0 && "Unknown overloaded atomic builtin!");
452 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
453 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
454 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
455 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
456 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000458 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
459 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
460 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
461 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
462 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner5caa3702009-05-08 06:58:22 +0000464 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000465 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000466 NumFixed = 2;
467 break;
468 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000469 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000470 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000471 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000472 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000473 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000475 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000477 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000478 break;
Chris Lattner23aa9c82011-04-09 03:57:26 +0000479 case Builtin::BI__sync_swap: BuiltinIndex = 14; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Chris Lattner5caa3702009-05-08 06:58:22 +0000482 // Now that we know how many fixed arguments we expect, first check that we
483 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000484 if (TheCall->getNumArgs() < 1+NumFixed) {
485 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
486 << 0 << 1+NumFixed << TheCall->getNumArgs()
487 << TheCall->getCallee()->getSourceRange();
488 return ExprError();
489 }
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000491 // Get the decl for the concrete builtin from this, we can tell what the
492 // concrete integer type we should convert to is.
493 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
494 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
495 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000496 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000497 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
498 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000499
John McCallf871d0c2010-08-07 06:22:56 +0000500 // The first argument --- the pointer --- has a fixed type; we
501 // deduce the types of the rest of the arguments accordingly. Walk
502 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000503 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley429bb272011-04-08 18:41:53 +0000504 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Chris Lattner5caa3702009-05-08 06:58:22 +0000506 // If the argument is an implicit cast, then there was a promotion due to
507 // "...", just remove it now.
John Wiegley429bb272011-04-08 18:41:53 +0000508 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000509 Arg = ICE->getSubExpr();
510 ICE->setSubExpr(0);
John Wiegley429bb272011-04-08 18:41:53 +0000511 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000512 }
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chris Lattner5caa3702009-05-08 06:58:22 +0000514 // GCC does an implicit conversion to the pointer or integer ValType. This
515 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000516 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000517 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000518 CXXCastPath BasePath;
John Wiegley429bb272011-04-08 18:41:53 +0000519 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath);
520 if (Arg.isInvalid())
Chandler Carruthd2014572010-07-09 18:59:35 +0000521 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Chris Lattner5caa3702009-05-08 06:58:22 +0000523 // Okay, we have something that *can* be converted to the right type. Check
524 // to see if there is a potentially weird extension going on here. This can
525 // happen when you do an atomic operation on something like an char* and
526 // pass in 42. The 42 gets converted to char. This is even more strange
527 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000528 // FIXME: Do this check.
John Wiegley429bb272011-04-08 18:41:53 +0000529 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
530 TheCall->setArg(i+1, Arg.get());
Chris Lattner5caa3702009-05-08 06:58:22 +0000531 }
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Chris Lattner5caa3702009-05-08 06:58:22 +0000533 // Switch the DeclRefExpr to refer to the new decl.
534 DRE->setDecl(NewBuiltinDecl);
535 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Chris Lattner5caa3702009-05-08 06:58:22 +0000537 // Set the callee in the CallExpr.
538 // FIXME: This leaks the original parens and implicit casts.
John Wiegley429bb272011-04-08 18:41:53 +0000539 ExprResult PromotedCall = UsualUnaryConversions(DRE);
540 if (PromotedCall.isInvalid())
541 return ExprError();
542 TheCall->setCallee(PromotedCall.take());
Mike Stump1eb44332009-09-09 15:08:12 +0000543
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000544 // Change the result type of the call to match the original value type. This
545 // is arbitrary, but the codegen for these builtins ins design to handle it
546 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000547 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000548
549 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000550}
551
552
Chris Lattner69039812009-02-18 06:01:06 +0000553/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000554/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000555/// Note: It might also make sense to do the UTF-16 conversion here (would
556/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000557bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000558 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000559 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
560
561 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000562 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
563 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000564 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000565 }
Mike Stump1eb44332009-09-09 15:08:12 +0000566
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000567 if (Literal->containsNonAsciiOrNull()) {
568 llvm::StringRef String = Literal->getString();
569 unsigned NumBytes = String.size();
570 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
571 const UTF8 *FromPtr = (UTF8 *)String.data();
572 UTF16 *ToPtr = &ToBuf[0];
573
574 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
575 &ToPtr, ToPtr + NumBytes,
576 strictConversion);
577 // Check for conversion failure.
578 if (Result != conversionOK)
579 Diag(Arg->getLocStart(),
580 diag::warn_cfstring_truncated) << Arg->getSourceRange();
581 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000582 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000583}
584
Chris Lattnerc27c6652007-12-20 00:05:45 +0000585/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
586/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000587bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
588 Expr *Fn = TheCall->getCallee();
589 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000590 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000591 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000592 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
593 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000594 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000595 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000596 return true;
597 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000598
599 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000600 return Diag(TheCall->getLocEnd(),
601 diag::err_typecheck_call_too_few_args_at_least)
602 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000603 }
604
Chris Lattnerc27c6652007-12-20 00:05:45 +0000605 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000606 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000607 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000608 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000609 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000610 else if (FunctionDecl *FD = getCurFunctionDecl())
611 isVariadic = FD->isVariadic();
612 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000613 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattnerc27c6652007-12-20 00:05:45 +0000615 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000616 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
617 return true;
618 }
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattner30ce3442007-12-19 23:59:04 +0000620 // Verify that the second argument to the builtin is the last argument of the
621 // current function or method.
622 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000623 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Anders Carlsson88cf2262008-02-11 04:20:54 +0000625 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
626 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000627 // FIXME: This isn't correct for methods (results in bogus warning).
628 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000629 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000630 if (CurBlock)
631 LastArg = *(CurBlock->TheDecl->param_end()-1);
632 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000633 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000634 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000635 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000636 SecondArgIsLastNamedArgument = PV == LastArg;
637 }
638 }
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Chris Lattner30ce3442007-12-19 23:59:04 +0000640 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000641 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000642 diag::warn_second_parameter_of_va_start_not_last_named_argument);
643 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000644}
Chris Lattner30ce3442007-12-19 23:59:04 +0000645
Chris Lattner1b9a0792007-12-20 00:26:33 +0000646/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
647/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000648bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
649 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000650 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000651 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000652 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000653 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000655 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000656 << SourceRange(TheCall->getArg(2)->getLocStart(),
657 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000658
John Wiegley429bb272011-04-08 18:41:53 +0000659 ExprResult OrigArg0 = TheCall->getArg(0);
660 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000661
Chris Lattner1b9a0792007-12-20 00:26:33 +0000662 // Do standard promotions between the two arguments, returning their common
663 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000664 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley429bb272011-04-08 18:41:53 +0000665 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
666 return true;
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000667
668 // Make sure any conversions are pushed back into the call; this is
669 // type safe since unordered compare builtins are declared as "_Bool
670 // foo(...)".
John Wiegley429bb272011-04-08 18:41:53 +0000671 TheCall->setArg(0, OrigArg0.get());
672 TheCall->setArg(1, OrigArg1.get());
Mike Stump1eb44332009-09-09 15:08:12 +0000673
John Wiegley429bb272011-04-08 18:41:53 +0000674 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorcde01732009-05-19 22:10:17 +0000675 return false;
676
Chris Lattner1b9a0792007-12-20 00:26:33 +0000677 // If the common type isn't a real floating type, then the arguments were
678 // invalid for this operation.
679 if (!Res->isRealFloatingType())
John Wiegley429bb272011-04-08 18:41:53 +0000680 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000681 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley429bb272011-04-08 18:41:53 +0000682 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
683 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000684
Chris Lattner1b9a0792007-12-20 00:26:33 +0000685 return false;
686}
687
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000688/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
689/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000690/// to check everything. We expect the last argument to be a floating point
691/// value.
692bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
693 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000694 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000695 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000696 if (TheCall->getNumArgs() > NumArgs)
697 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000698 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000699 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000700 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000701 (*(TheCall->arg_end()-1))->getLocEnd());
702
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000703 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Eli Friedman9ac6f622009-08-31 20:06:00 +0000705 if (OrigArg->isTypeDependent())
706 return false;
707
Chris Lattner81368fb2010-05-06 05:50:07 +0000708 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000709 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000710 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000711 diag::err_typecheck_call_invalid_unary_fp)
712 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Chris Lattner81368fb2010-05-06 05:50:07 +0000714 // If this is an implicit conversion from float -> double, remove it.
715 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
716 Expr *CastArg = Cast->getSubExpr();
717 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
718 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
719 "promotion from float to double is the only expected cast here");
720 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000721 TheCall->setArg(NumArgs-1, CastArg);
722 OrigArg = CastArg;
723 }
724 }
725
Eli Friedman9ac6f622009-08-31 20:06:00 +0000726 return false;
727}
728
Eli Friedmand38617c2008-05-14 19:38:39 +0000729/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
730// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000731ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000732 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000733 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000734 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000735 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000736 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000737
Nate Begeman37b6a572010-06-08 00:16:34 +0000738 // Determine which of the following types of shufflevector we're checking:
739 // 1) unary, vector mask: (lhs, mask)
740 // 2) binary, vector mask: (lhs, rhs, mask)
741 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
742 QualType resType = TheCall->getArg(0)->getType();
743 unsigned numElements = 0;
744
Douglas Gregorcde01732009-05-19 22:10:17 +0000745 if (!TheCall->getArg(0)->isTypeDependent() &&
746 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000747 QualType LHSType = TheCall->getArg(0)->getType();
748 QualType RHSType = TheCall->getArg(1)->getType();
749
750 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000751 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000752 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000753 TheCall->getArg(1)->getLocEnd());
754 return ExprError();
755 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000756
757 numElements = LHSType->getAs<VectorType>()->getNumElements();
758 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Nate Begeman37b6a572010-06-08 00:16:34 +0000760 // Check to see if we have a call with 2 vector arguments, the unary shuffle
761 // with mask. If so, verify that RHS is an integer vector type with the
762 // same number of elts as lhs.
763 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000764 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000765 RHSType->getAs<VectorType>()->getNumElements() != numElements)
766 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
767 << SourceRange(TheCall->getArg(1)->getLocStart(),
768 TheCall->getArg(1)->getLocEnd());
769 numResElements = numElements;
770 }
771 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000772 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000773 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000774 TheCall->getArg(1)->getLocEnd());
775 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000776 } else if (numElements != numResElements) {
777 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000778 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000779 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000780 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000781 }
782
783 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000784 if (TheCall->getArg(i)->isTypeDependent() ||
785 TheCall->getArg(i)->isValueDependent())
786 continue;
787
Nate Begeman37b6a572010-06-08 00:16:34 +0000788 llvm::APSInt Result(32);
789 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
790 return ExprError(Diag(TheCall->getLocStart(),
791 diag::err_shufflevector_nonconstant_argument)
792 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000793
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000794 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000795 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000796 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000797 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000798 }
799
800 llvm::SmallVector<Expr*, 32> exprs;
801
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000802 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000803 exprs.push_back(TheCall->getArg(i));
804 TheCall->setArg(i, 0);
805 }
806
Nate Begemana88dc302009-08-12 02:10:25 +0000807 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000808 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000809 TheCall->getCallee()->getLocStart(),
810 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000811}
Chris Lattner30ce3442007-12-19 23:59:04 +0000812
Daniel Dunbar4493f792008-07-21 22:59:13 +0000813/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
814// This is declared to take (const void*, ...) and can take two
815// optional constant int args.
816bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000817 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000818
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000819 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000820 return Diag(TheCall->getLocEnd(),
821 diag::err_typecheck_call_too_many_args_at_most)
822 << 0 /*function call*/ << 3 << NumArgs
823 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000824
825 // Argument 0 is checked for us and the remaining arguments must be
826 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000827 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000828 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000829
Eli Friedman9aef7262009-12-04 00:30:06 +0000830 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000831 if (SemaBuiltinConstantArg(TheCall, i, Result))
832 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Daniel Dunbar4493f792008-07-21 22:59:13 +0000834 // FIXME: gcc issues a warning and rewrites these to 0. These
835 // seems especially odd for the third argument since the default
836 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000837 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000838 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000839 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000840 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000841 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000842 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000843 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000844 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000845 }
846 }
847
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000848 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000849}
850
Eric Christopher691ebc32010-04-17 02:26:23 +0000851/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
852/// TheCall is a constant expression.
853bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
854 llvm::APSInt &Result) {
855 Expr *Arg = TheCall->getArg(ArgNum);
856 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
857 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
858
859 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
860
861 if (!Arg->isIntegerConstantExpr(Result, Context))
862 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000863 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000864
Chris Lattner21fb98e2009-09-23 06:06:36 +0000865 return false;
866}
867
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000868/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
869/// int type). This simply type checks that type is one of the defined
870/// constants (0-3).
Chris Lattnerfc8f0e12011-04-15 05:22:18 +0000871// For compatibility check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000872bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000873 llvm::APSInt Result;
874
875 // Check constant-ness first.
876 if (SemaBuiltinConstantArg(TheCall, 1, Result))
877 return true;
878
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000879 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000880 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000881 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
882 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000883 }
884
885 return false;
886}
887
Eli Friedman586d6a82009-05-03 06:04:26 +0000888/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000889/// This checks that val is a constant 1.
890bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
891 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000892 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000893
Eric Christopher691ebc32010-04-17 02:26:23 +0000894 // TODO: This is less than ideal. Overload this to take a value.
895 if (SemaBuiltinConstantArg(TheCall, 1, Result))
896 return true;
897
898 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000899 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
900 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
901
902 return false;
903}
904
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000905// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000906bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
907 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000908 unsigned format_idx, unsigned firstDataArg,
909 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000910 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000911 if (E->isTypeDependent() || E->isValueDependent())
912 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000913
Peter Collingbournef111d932011-04-15 00:35:48 +0000914 E = E->IgnoreParens();
915
Ted Kremenekd30ef872009-01-12 23:09:09 +0000916 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000917 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000918 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000919 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000920 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
921 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000922 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000923 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000924 }
925
Ted Kremenek95355bb2010-09-09 03:51:42 +0000926 case Stmt::IntegerLiteralClass:
927 // Technically -Wformat-nonliteral does not warn about this case.
928 // The behavior of printf and friends in this case is implementation
929 // dependent. Ideally if the format string cannot be null then
930 // it should have a 'nonnull' attribute in the function prototype.
931 return true;
932
Ted Kremenekd30ef872009-01-12 23:09:09 +0000933 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000934 E = cast<ImplicitCastExpr>(E)->getSubExpr();
935 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000936 }
937
John McCall56ca35d2011-02-17 10:25:35 +0000938 case Stmt::OpaqueValueExprClass:
939 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
940 E = src;
941 goto tryAgain;
942 }
943 return false;
944
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000945 case Stmt::PredefinedExprClass:
946 // While __func__, etc., are technically not string literals, they
947 // cannot contain format specifiers and thus are not a security
948 // liability.
949 return true;
950
Ted Kremenek082d9362009-03-20 21:35:28 +0000951 case Stmt::DeclRefExprClass: {
952 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Ted Kremenek082d9362009-03-20 21:35:28 +0000954 // As an exception, do not flag errors for variables binding to
955 // const string literals.
956 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
957 bool isConstant = false;
958 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000959
Ted Kremenek082d9362009-03-20 21:35:28 +0000960 if (const ArrayType *AT = Context.getAsArrayType(T)) {
961 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000962 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000963 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000964 PT->getPointeeType().isConstant(Context);
965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Ted Kremenek082d9362009-03-20 21:35:28 +0000967 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000968 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000969 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000970 HasVAListArg, format_idx, firstDataArg,
971 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000972 }
Mike Stump1eb44332009-09-09 15:08:12 +0000973
Anders Carlssond966a552009-06-28 19:55:58 +0000974 // For vprintf* functions (i.e., HasVAListArg==true), we add a
975 // special check to see if the format string is a function parameter
976 // of the function calling the printf function. If the function
977 // has an attribute indicating it is a printf-like function, then we
978 // should suppress warnings concerning non-literals being used in a call
979 // to a vprintf function. For example:
980 //
981 // void
982 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
983 // va_list ap;
984 // va_start(ap, fmt);
985 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
986 // ...
987 //
988 //
989 // FIXME: We don't have full attribute support yet, so just check to see
990 // if the argument is a DeclRefExpr that references a parameter. We'll
991 // add proper support for checking the attribute later.
992 if (HasVAListArg)
993 if (isa<ParmVarDecl>(VD))
994 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Ted Kremenek082d9362009-03-20 21:35:28 +0000997 return false;
998 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000999
Anders Carlsson8f031b32009-06-27 04:05:33 +00001000 case Stmt::CallExprClass: {
1001 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001002 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +00001003 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
1004 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
1005 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001006 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +00001007 unsigned ArgIndex = FA->getFormatIdx();
1008 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +00001009
1010 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001011 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +00001012 }
1013 }
1014 }
1015 }
Mike Stump1eb44332009-09-09 15:08:12 +00001016
Anders Carlsson8f031b32009-06-27 04:05:33 +00001017 return false;
1018 }
Ted Kremenek082d9362009-03-20 21:35:28 +00001019 case Stmt::ObjCStringLiteralClass:
1020 case Stmt::StringLiteralClass: {
1021 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Ted Kremenek082d9362009-03-20 21:35:28 +00001023 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001024 StrE = ObjCFExpr->getString();
1025 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001026 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Ted Kremenekd30ef872009-01-12 23:09:09 +00001028 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001029 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1030 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001031 return true;
1032 }
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Ted Kremenekd30ef872009-01-12 23:09:09 +00001034 return false;
1035 }
Mike Stump1eb44332009-09-09 15:08:12 +00001036
Ted Kremenek082d9362009-03-20 21:35:28 +00001037 default:
1038 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001039 }
1040}
1041
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001042void
Mike Stump1eb44332009-09-09 15:08:12 +00001043Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewycky909a70d2011-03-25 01:44:32 +00001044 const Expr * const *ExprArgs,
1045 SourceLocation CallSiteLoc) {
Sean Huntcf807c42010-08-18 23:23:40 +00001046 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1047 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001048 i != e; ++i) {
Nick Lewycky909a70d2011-03-25 01:44:32 +00001049 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001050 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001051 Expr::NPC_ValueDependentIsNotNull))
Nick Lewycky909a70d2011-03-25 01:44:32 +00001052 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001053 }
1054}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001055
Ted Kremenek826a3452010-07-16 02:11:22 +00001056/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1057/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001058void
Ted Kremenek826a3452010-07-16 02:11:22 +00001059Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1060 unsigned format_idx, unsigned firstDataArg,
1061 bool isPrintf) {
1062
Ted Kremenek082d9362009-03-20 21:35:28 +00001063 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001064
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001065 // The way the format attribute works in GCC, the implicit this argument
1066 // of member functions is counted. However, it doesn't appear in our own
1067 // lists, so decrement format_idx in that case.
1068 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001069 const CXXMethodDecl *method_decl =
1070 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1071 if (method_decl && method_decl->isInstance()) {
1072 // Catch a format attribute mistakenly referring to the object argument.
1073 if (format_idx == 0)
1074 return;
1075 --format_idx;
1076 if(firstDataArg != 0)
1077 --firstDataArg;
1078 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001079 }
1080
Ted Kremenek826a3452010-07-16 02:11:22 +00001081 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001082 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001083 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001084 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001085 return;
1086 }
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Ted Kremenek082d9362009-03-20 21:35:28 +00001088 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Chris Lattner59907c42007-08-10 20:18:51 +00001090 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001091 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001092 // Dynamically generated format strings are difficult to
1093 // automatically vet at compile time. Requiring that format strings
1094 // are string literals: (1) permits the checking of format strings by
1095 // the compiler and thereby (2) can practically remove the source of
1096 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001097
Mike Stump1eb44332009-09-09 15:08:12 +00001098 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001099 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001100 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001101 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001102 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001103 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001104 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001105
Chris Lattner655f1412009-04-29 04:59:47 +00001106 // If there are no arguments specified, warn with -Wformat-security, otherwise
1107 // warn only with -Wformat-nonliteral.
1108 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001109 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001110 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001111 << OrigFormatExpr->getSourceRange();
1112 else
Mike Stump1eb44332009-09-09 15:08:12 +00001113 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001114 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001115 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001116}
Ted Kremenek71895b92007-08-14 17:39:48 +00001117
Ted Kremeneke0e53132010-01-28 23:39:18 +00001118namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001119class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1120protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001121 Sema &S;
1122 const StringLiteral *FExpr;
1123 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001124 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001125 const unsigned NumDataArgs;
1126 const bool IsObjCLiteral;
1127 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001128 const bool HasVAListArg;
1129 const CallExpr *TheCall;
1130 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001131 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001132 bool usesPositionalArgs;
1133 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001134public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001135 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001136 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001137 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001138 const char *beg, bool hasVAListArg,
1139 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001140 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001141 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001142 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001143 IsObjCLiteral(isObjCLiteral), Beg(beg),
1144 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001145 TheCall(theCall), FormatIdx(formatIdx),
1146 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001147 CoveredArgs.resize(numDataArgs);
1148 CoveredArgs.reset();
1149 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001150
Ted Kremenek07d161f2010-01-29 01:50:07 +00001151 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001152
Ted Kremenek826a3452010-07-16 02:11:22 +00001153 void HandleIncompleteSpecifier(const char *startSpecifier,
1154 unsigned specifierLen);
1155
Ted Kremenekefaff192010-02-27 01:41:03 +00001156 virtual void HandleInvalidPosition(const char *startSpecifier,
1157 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001158 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001159
1160 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1161
Ted Kremeneke0e53132010-01-28 23:39:18 +00001162 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001163
Ted Kremenek826a3452010-07-16 02:11:22 +00001164protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001165 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1166 const char *startSpec,
1167 unsigned specifierLen,
1168 const char *csStart, unsigned csLen);
1169
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001170 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001171 CharSourceRange getSpecifierRange(const char *startSpecifier,
1172 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001173 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001174
Ted Kremenek0d277352010-01-29 01:06:55 +00001175 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001176
1177 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1178 const analyze_format_string::ConversionSpecifier &CS,
1179 const char *startSpecifier, unsigned specifierLen,
1180 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001181};
1182}
1183
Ted Kremenek826a3452010-07-16 02:11:22 +00001184SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001185 return OrigFormatExpr->getSourceRange();
1186}
1187
Ted Kremenek826a3452010-07-16 02:11:22 +00001188CharSourceRange CheckFormatHandler::
1189getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001190 SourceLocation Start = getLocationOfByte(startSpecifier);
1191 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1192
1193 // Advance the end SourceLocation by one due to half-open ranges.
1194 End = End.getFileLocWithOffset(1);
1195
1196 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001197}
1198
Ted Kremenek826a3452010-07-16 02:11:22 +00001199SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001200 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001201}
1202
Ted Kremenek826a3452010-07-16 02:11:22 +00001203void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1204 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001205 SourceLocation Loc = getLocationOfByte(startSpecifier);
1206 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001207 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001208}
1209
Ted Kremenekefaff192010-02-27 01:41:03 +00001210void
Ted Kremenek826a3452010-07-16 02:11:22 +00001211CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1212 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001213 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001214 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1215 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001216}
1217
Ted Kremenek826a3452010-07-16 02:11:22 +00001218void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001219 unsigned posLen) {
1220 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001221 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1222 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001223}
1224
Ted Kremenek826a3452010-07-16 02:11:22 +00001225void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0c069442011-03-15 21:18:48 +00001226 if (!IsObjCLiteral) {
1227 // The presence of a null character is likely an error.
1228 S.Diag(getLocationOfByte(nullCharacter),
1229 diag::warn_printf_format_string_contains_null_char)
1230 << getFormatStringRange();
1231 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001232}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001233
Ted Kremenek826a3452010-07-16 02:11:22 +00001234const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1235 return TheCall->getArg(FirstDataArg + i);
1236}
1237
1238void CheckFormatHandler::DoneProcessing() {
1239 // Does the number of data arguments exceed the number of
1240 // format conversions in the format string?
1241 if (!HasVAListArg) {
1242 // Find any arguments that weren't covered.
1243 CoveredArgs.flip();
1244 signed notCoveredArg = CoveredArgs.find_first();
1245 if (notCoveredArg >= 0) {
1246 assert((unsigned)notCoveredArg < NumDataArgs);
1247 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1248 diag::warn_printf_data_arg_not_used)
1249 << getFormatStringRange();
1250 }
1251 }
1252}
1253
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001254bool
1255CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1256 SourceLocation Loc,
1257 const char *startSpec,
1258 unsigned specifierLen,
1259 const char *csStart,
1260 unsigned csLen) {
1261
1262 bool keepGoing = true;
1263 if (argIndex < NumDataArgs) {
1264 // Consider the argument coverered, even though the specifier doesn't
1265 // make sense.
1266 CoveredArgs.set(argIndex);
1267 }
1268 else {
1269 // If argIndex exceeds the number of data arguments we
1270 // don't issue a warning because that is just a cascade of warnings (and
1271 // they may have intended '%%' anyway). We don't want to continue processing
1272 // the format string after this point, however, as we will like just get
1273 // gibberish when trying to match arguments.
1274 keepGoing = false;
1275 }
1276
1277 S.Diag(Loc, diag::warn_format_invalid_conversion)
1278 << llvm::StringRef(csStart, csLen)
1279 << getSpecifierRange(startSpec, specifierLen);
1280
1281 return keepGoing;
1282}
1283
Ted Kremenek666a1972010-07-26 19:45:42 +00001284bool
1285CheckFormatHandler::CheckNumArgs(
1286 const analyze_format_string::FormatSpecifier &FS,
1287 const analyze_format_string::ConversionSpecifier &CS,
1288 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1289
1290 if (argIndex >= NumDataArgs) {
1291 if (FS.usesPositionalArg()) {
1292 S.Diag(getLocationOfByte(CS.getStart()),
1293 diag::warn_printf_positional_arg_exceeds_data_args)
1294 << (argIndex+1) << NumDataArgs
1295 << getSpecifierRange(startSpecifier, specifierLen);
1296 }
1297 else {
1298 S.Diag(getLocationOfByte(CS.getStart()),
1299 diag::warn_printf_insufficient_data_args)
1300 << getSpecifierRange(startSpecifier, specifierLen);
1301 }
1302
1303 return false;
1304 }
1305 return true;
1306}
1307
Ted Kremenek826a3452010-07-16 02:11:22 +00001308//===--- CHECK: Printf format string checking ------------------------------===//
1309
1310namespace {
1311class CheckPrintfHandler : public CheckFormatHandler {
1312public:
1313 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1314 const Expr *origFormatExpr, unsigned firstDataArg,
1315 unsigned numDataArgs, bool isObjCLiteral,
1316 const char *beg, bool hasVAListArg,
1317 const CallExpr *theCall, unsigned formatIdx)
1318 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1319 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1320 theCall, formatIdx) {}
1321
1322
1323 bool HandleInvalidPrintfConversionSpecifier(
1324 const analyze_printf::PrintfSpecifier &FS,
1325 const char *startSpecifier,
1326 unsigned specifierLen);
1327
1328 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1329 const char *startSpecifier,
1330 unsigned specifierLen);
1331
1332 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1333 const char *startSpecifier, unsigned specifierLen);
1334 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1335 const analyze_printf::OptionalAmount &Amt,
1336 unsigned type,
1337 const char *startSpecifier, unsigned specifierLen);
1338 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1339 const analyze_printf::OptionalFlag &flag,
1340 const char *startSpecifier, unsigned specifierLen);
1341 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1342 const analyze_printf::OptionalFlag &ignoredFlag,
1343 const analyze_printf::OptionalFlag &flag,
1344 const char *startSpecifier, unsigned specifierLen);
1345};
1346}
1347
1348bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1349 const analyze_printf::PrintfSpecifier &FS,
1350 const char *startSpecifier,
1351 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001352 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001353 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001354
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001355 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1356 getLocationOfByte(CS.getStart()),
1357 startSpecifier, specifierLen,
1358 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001359}
1360
Ted Kremenek826a3452010-07-16 02:11:22 +00001361bool CheckPrintfHandler::HandleAmount(
1362 const analyze_format_string::OptionalAmount &Amt,
1363 unsigned k, const char *startSpecifier,
1364 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001365
1366 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001367 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001368 unsigned argIndex = Amt.getArgIndex();
1369 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001370 S.Diag(getLocationOfByte(Amt.getStart()),
1371 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001372 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001373 // Don't do any more checking. We will just emit
1374 // spurious errors.
1375 return false;
1376 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001377
Ted Kremenek0d277352010-01-29 01:06:55 +00001378 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001379 // Although not in conformance with C99, we also allow the argument to be
1380 // an 'unsigned int' as that is a reasonably safe case. GCC also
1381 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001382 CoveredArgs.set(argIndex);
1383 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001384 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001385
1386 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1387 assert(ATR.isValid());
1388
1389 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001390 S.Diag(getLocationOfByte(Amt.getStart()),
1391 diag::warn_printf_asterisk_wrong_type)
1392 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001393 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001394 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001395 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001396 // Don't do any more checking. We will just emit
1397 // spurious errors.
1398 return false;
1399 }
1400 }
1401 }
1402 return true;
1403}
Ted Kremenek0d277352010-01-29 01:06:55 +00001404
Tom Caree4ee9662010-06-17 19:00:27 +00001405void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001406 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001407 const analyze_printf::OptionalAmount &Amt,
1408 unsigned type,
1409 const char *startSpecifier,
1410 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001411 const analyze_printf::PrintfConversionSpecifier &CS =
1412 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001413 switch (Amt.getHowSpecified()) {
1414 case analyze_printf::OptionalAmount::Constant:
1415 S.Diag(getLocationOfByte(Amt.getStart()),
1416 diag::warn_printf_nonsensical_optional_amount)
1417 << type
1418 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 << getSpecifierRange(startSpecifier, specifierLen)
1420 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001421 Amt.getConstantLength()));
1422 break;
1423
1424 default:
1425 S.Diag(getLocationOfByte(Amt.getStart()),
1426 diag::warn_printf_nonsensical_optional_amount)
1427 << type
1428 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001429 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001430 break;
1431 }
1432}
1433
Ted Kremenek826a3452010-07-16 02:11:22 +00001434void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001435 const analyze_printf::OptionalFlag &flag,
1436 const char *startSpecifier,
1437 unsigned specifierLen) {
1438 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001439 const analyze_printf::PrintfConversionSpecifier &CS =
1440 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001441 S.Diag(getLocationOfByte(flag.getPosition()),
1442 diag::warn_printf_nonsensical_flag)
1443 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001444 << getSpecifierRange(startSpecifier, specifierLen)
1445 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001446}
1447
1448void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001449 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001450 const analyze_printf::OptionalFlag &ignoredFlag,
1451 const analyze_printf::OptionalFlag &flag,
1452 const char *startSpecifier,
1453 unsigned specifierLen) {
1454 // Warn about ignored flag with a fixit removal.
1455 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1456 diag::warn_printf_ignored_flag)
1457 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001458 << getSpecifierRange(startSpecifier, specifierLen)
1459 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001460 ignoredFlag.getPosition(), 1));
1461}
1462
Ted Kremeneke0e53132010-01-28 23:39:18 +00001463bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001464CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001465 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001466 const char *startSpecifier,
1467 unsigned specifierLen) {
1468
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001469 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001470 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001471 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001472
Ted Kremenekbaa40062010-07-19 22:01:06 +00001473 if (FS.consumesDataArgument()) {
1474 if (atFirstArg) {
1475 atFirstArg = false;
1476 usesPositionalArgs = FS.usesPositionalArg();
1477 }
1478 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1479 // Cannot mix-and-match positional and non-positional arguments.
1480 S.Diag(getLocationOfByte(CS.getStart()),
1481 diag::warn_format_mix_positional_nonpositional_args)
1482 << getSpecifierRange(startSpecifier, specifierLen);
1483 return false;
1484 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001485 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001486
Ted Kremenekefaff192010-02-27 01:41:03 +00001487 // First check if the field width, precision, and conversion specifier
1488 // have matching data arguments.
1489 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1490 startSpecifier, specifierLen)) {
1491 return false;
1492 }
1493
1494 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1495 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001496 return false;
1497 }
1498
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001499 if (!CS.consumesDataArgument()) {
1500 // FIXME: Technically specifying a precision or field width here
1501 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001502 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001503 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001504
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001505 // Consume the argument.
1506 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001507 if (argIndex < NumDataArgs) {
1508 // The check to see if the argIndex is valid will come later.
1509 // We set the bit here because we may exit early from this
1510 // function if we encounter some other error.
1511 CoveredArgs.set(argIndex);
1512 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001513
1514 // Check for using an Objective-C specific conversion specifier
1515 // in a non-ObjC literal.
1516 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001517 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1518 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001519 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001520
Tom Caree4ee9662010-06-17 19:00:27 +00001521 // Check for invalid use of field width
1522 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001523 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001524 startSpecifier, specifierLen);
1525 }
1526
1527 // Check for invalid use of precision
1528 if (!FS.hasValidPrecision()) {
1529 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1530 startSpecifier, specifierLen);
1531 }
1532
1533 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001534 if (!FS.hasValidThousandsGroupingPrefix())
1535 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001536 if (!FS.hasValidLeadingZeros())
1537 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1538 if (!FS.hasValidPlusPrefix())
1539 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001540 if (!FS.hasValidSpacePrefix())
1541 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001542 if (!FS.hasValidAlternativeForm())
1543 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1544 if (!FS.hasValidLeftJustified())
1545 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1546
1547 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001548 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1549 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1550 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001551 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1552 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1553 startSpecifier, specifierLen);
1554
1555 // Check the length modifier is valid with the given conversion specifier.
1556 const LengthModifier &LM = FS.getLengthModifier();
1557 if (!FS.hasValidLengthModifier())
1558 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001559 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001560 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001561 << getSpecifierRange(startSpecifier, specifierLen)
1562 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001563 LM.getLength()));
1564
1565 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001566 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001567 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001568 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001569 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001570 // Continue checking the other format specifiers.
1571 return true;
1572 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001573
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001574 // The remaining checks depend on the data arguments.
1575 if (HasVAListArg)
1576 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001577
Ted Kremenek666a1972010-07-26 19:45:42 +00001578 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001579 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001580
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001581 // Now type check the data expression that matches the
1582 // format specifier.
1583 const Expr *Ex = getDataArg(argIndex);
1584 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1585 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1586 // Check if we didn't match because of an implicit cast from a 'char'
1587 // or 'short' to an 'int'. This is done because printf is a varargs
1588 // function.
1589 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001590 if (ICE->getType() == S.Context.IntTy) {
1591 // All further checking is done on the subexpression.
1592 Ex = ICE->getSubExpr();
1593 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001594 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001595 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001596
1597 // We may be able to offer a FixItHint if it is a supported type.
1598 PrintfSpecifier fixedFS = FS;
1599 bool success = fixedFS.fixType(Ex->getType());
1600
1601 if (success) {
1602 // Get the fix string from the fixed format specifier
1603 llvm::SmallString<128> buf;
1604 llvm::raw_svector_ostream os(buf);
1605 fixedFS.toString(os);
1606
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001607 // FIXME: getRepresentativeType() perhaps should return a string
1608 // instead of a QualType to better handle when the representative
1609 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001610 S.Diag(getLocationOfByte(CS.getStart()),
1611 diag::warn_printf_conversion_argument_type_mismatch)
1612 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1613 << getSpecifierRange(startSpecifier, specifierLen)
1614 << Ex->getSourceRange()
1615 << FixItHint::CreateReplacement(
1616 getSpecifierRange(startSpecifier, specifierLen),
1617 os.str());
1618 }
1619 else {
1620 S.Diag(getLocationOfByte(CS.getStart()),
1621 diag::warn_printf_conversion_argument_type_mismatch)
1622 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1623 << getSpecifierRange(startSpecifier, specifierLen)
1624 << Ex->getSourceRange();
1625 }
1626 }
1627
Ted Kremeneke0e53132010-01-28 23:39:18 +00001628 return true;
1629}
1630
Ted Kremenek826a3452010-07-16 02:11:22 +00001631//===--- CHECK: Scanf format string checking ------------------------------===//
1632
1633namespace {
1634class CheckScanfHandler : public CheckFormatHandler {
1635public:
1636 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1637 const Expr *origFormatExpr, unsigned firstDataArg,
1638 unsigned numDataArgs, bool isObjCLiteral,
1639 const char *beg, bool hasVAListArg,
1640 const CallExpr *theCall, unsigned formatIdx)
1641 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1642 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1643 theCall, formatIdx) {}
1644
1645 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1646 const char *startSpecifier,
1647 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001648
1649 bool HandleInvalidScanfConversionSpecifier(
1650 const analyze_scanf::ScanfSpecifier &FS,
1651 const char *startSpecifier,
1652 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001653
1654 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001655};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001656}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001657
Ted Kremenekb7c21012010-07-16 18:28:03 +00001658void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1659 const char *end) {
1660 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1661 << getSpecifierRange(start, end - start);
1662}
1663
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001664bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1665 const analyze_scanf::ScanfSpecifier &FS,
1666 const char *startSpecifier,
1667 unsigned specifierLen) {
1668
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001669 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001670 FS.getConversionSpecifier();
1671
1672 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1673 getLocationOfByte(CS.getStart()),
1674 startSpecifier, specifierLen,
1675 CS.getStart(), CS.getLength());
1676}
1677
Ted Kremenek826a3452010-07-16 02:11:22 +00001678bool CheckScanfHandler::HandleScanfSpecifier(
1679 const analyze_scanf::ScanfSpecifier &FS,
1680 const char *startSpecifier,
1681 unsigned specifierLen) {
1682
1683 using namespace analyze_scanf;
1684 using namespace analyze_format_string;
1685
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001686 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001687
Ted Kremenekbaa40062010-07-19 22:01:06 +00001688 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1689 // be used to decide if we are using positional arguments consistently.
1690 if (FS.consumesDataArgument()) {
1691 if (atFirstArg) {
1692 atFirstArg = false;
1693 usesPositionalArgs = FS.usesPositionalArg();
1694 }
1695 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1696 // Cannot mix-and-match positional and non-positional arguments.
1697 S.Diag(getLocationOfByte(CS.getStart()),
1698 diag::warn_format_mix_positional_nonpositional_args)
1699 << getSpecifierRange(startSpecifier, specifierLen);
1700 return false;
1701 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001702 }
1703
1704 // Check if the field with is non-zero.
1705 const OptionalAmount &Amt = FS.getFieldWidth();
1706 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1707 if (Amt.getConstantAmount() == 0) {
1708 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1709 Amt.getConstantLength());
1710 S.Diag(getLocationOfByte(Amt.getStart()),
1711 diag::warn_scanf_nonzero_width)
1712 << R << FixItHint::CreateRemoval(R);
1713 }
1714 }
1715
1716 if (!FS.consumesDataArgument()) {
1717 // FIXME: Technically specifying a precision or field width here
1718 // makes no sense. Worth issuing a warning at some point.
1719 return true;
1720 }
1721
1722 // Consume the argument.
1723 unsigned argIndex = FS.getArgIndex();
1724 if (argIndex < NumDataArgs) {
1725 // The check to see if the argIndex is valid will come later.
1726 // We set the bit here because we may exit early from this
1727 // function if we encounter some other error.
1728 CoveredArgs.set(argIndex);
1729 }
1730
Ted Kremenek1e51c202010-07-20 20:04:47 +00001731 // Check the length modifier is valid with the given conversion specifier.
1732 const LengthModifier &LM = FS.getLengthModifier();
1733 if (!FS.hasValidLengthModifier()) {
1734 S.Diag(getLocationOfByte(LM.getStart()),
1735 diag::warn_format_nonsensical_length)
1736 << LM.toString() << CS.toString()
1737 << getSpecifierRange(startSpecifier, specifierLen)
1738 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1739 LM.getLength()));
1740 }
1741
Ted Kremenek826a3452010-07-16 02:11:22 +00001742 // The remaining checks depend on the data arguments.
1743 if (HasVAListArg)
1744 return true;
1745
Ted Kremenek666a1972010-07-26 19:45:42 +00001746 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001747 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001748
1749 // FIXME: Check that the argument type matches the format specifier.
1750
1751 return true;
1752}
1753
1754void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001755 const Expr *OrigFormatExpr,
1756 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001757 unsigned format_idx, unsigned firstDataArg,
1758 bool isPrintf) {
1759
Ted Kremeneke0e53132010-01-28 23:39:18 +00001760 // CHECK: is the format string a wide literal?
1761 if (FExpr->isWide()) {
1762 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001763 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001764 << OrigFormatExpr->getSourceRange();
1765 return;
1766 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001767
Ted Kremeneke0e53132010-01-28 23:39:18 +00001768 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001769 llvm::StringRef StrRef = FExpr->getString();
1770 const char *Str = StrRef.data();
1771 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001772
Ted Kremeneke0e53132010-01-28 23:39:18 +00001773 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001774 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001775 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001776 << OrigFormatExpr->getSourceRange();
1777 return;
1778 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001779
1780 if (isPrintf) {
1781 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1782 TheCall->getNumArgs() - firstDataArg,
1783 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1784 HasVAListArg, TheCall, format_idx);
1785
1786 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1787 H.DoneProcessing();
1788 }
1789 else {
1790 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1791 TheCall->getNumArgs() - firstDataArg,
1792 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1793 HasVAListArg, TheCall, format_idx);
1794
1795 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1796 H.DoneProcessing();
1797 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001798}
1799
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001800//===--- CHECK: Standard memory functions ---------------------------------===//
1801
Douglas Gregor2a053a32011-05-03 20:05:22 +00001802/// \brief Determine whether the given type is a dynamic class type (e.g.,
1803/// whether it has a vtable).
1804static bool isDynamicClassType(QualType T) {
1805 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
1806 if (CXXRecordDecl *Definition = Record->getDefinition())
1807 if (Definition->isDynamicClass())
1808 return true;
1809
1810 return false;
1811}
1812
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001813/// \brief Check for dangerous or invalid arguments to memset().
1814///
1815/// This issues warnings on known problematic or dangerous or unspecified
1816/// arguments to the standard 'memset' function call.
1817///
1818/// \param Call The call expression to diagnose.
1819void Sema::CheckMemsetArguments(const CallExpr *Call) {
Ted Kremenek1d59f7f2011-04-28 01:38:02 +00001820 // It is possible to have a non-standard definition of memset. Validate
1821 // we have the proper number of arguments, and if not, abort further
1822 // checking.
1823 if (Call->getNumArgs() != 3)
1824 return;
1825
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001826 const Expr *Dest = Call->getArg(0)->IgnoreParenImpCasts();
1827
1828 QualType DestTy = Dest->getType();
1829 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
1830 QualType PointeeTy = DestPtrTy->getPointeeType();
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001831 if (PointeeTy->isVoidType())
1832 return;
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001833
Douglas Gregor2a053a32011-05-03 20:05:22 +00001834 unsigned DiagID = 0;
1835 // Always complain about dynamic classes.
1836 if (isDynamicClassType(PointeeTy))
1837 DiagID = diag::warn_dyn_class_memset;
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001838 // Check the C++11 POD definition regardless of language mode; it is more
Douglas Gregor2a053a32011-05-03 20:05:22 +00001839 // relaxed than earlier definitions and we don't want spurious warnings.
1840 else if (!PointeeTy->isCXX11PODType())
1841 DiagID = diag::warn_non_pod_memset;
1842 else
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001843 return;
1844
1845 DiagRuntimeBehavior(
1846 Dest->getExprLoc(), Dest,
Douglas Gregor2a053a32011-05-03 20:05:22 +00001847 PDiag(DiagID)
Chandler Carruth43fa33b2011-04-29 09:46:08 +00001848 << PointeeTy << Call->getCallee()->getSourceRange());
1849
1850 SourceRange ArgRange = Call->getArg(0)->getSourceRange();
1851 DiagRuntimeBehavior(
1852 Dest->getExprLoc(), Dest,
1853 PDiag(diag::note_non_pod_memset_silence)
1854 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
Chandler Carruth7ccc95b2011-04-27 07:05:31 +00001855 }
1856}
1857
Ted Kremenek06de2762007-08-17 16:46:58 +00001858//===--- CHECK: Return Address of Stack Variable --------------------------===//
1859
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001860static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1861static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001862
1863/// CheckReturnStackAddr - Check if a return statement returns the address
1864/// of a stack variable.
1865void
1866Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1867 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001869 Expr *stackE = 0;
1870 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1871
1872 // Perform checking for returned stack addresses, local blocks,
1873 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001874 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001875 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001876 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001877 stackE = EvalVal(RetValExp, refVars);
1878 }
1879
1880 if (stackE == 0)
1881 return; // Nothing suspicious was found.
1882
1883 SourceLocation diagLoc;
1884 SourceRange diagRange;
1885 if (refVars.empty()) {
1886 diagLoc = stackE->getLocStart();
1887 diagRange = stackE->getSourceRange();
1888 } else {
1889 // We followed through a reference variable. 'stackE' contains the
1890 // problematic expression but we will warn at the return statement pointing
1891 // at the reference variable. We will later display the "trail" of
1892 // reference variables using notes.
1893 diagLoc = refVars[0]->getLocStart();
1894 diagRange = refVars[0]->getSourceRange();
1895 }
1896
1897 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1898 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1899 : diag::warn_ret_stack_addr)
1900 << DR->getDecl()->getDeclName() << diagRange;
1901 } else if (isa<BlockExpr>(stackE)) { // local block.
1902 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1903 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1904 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1905 } else { // local temporary.
1906 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1907 : diag::warn_ret_local_temp_addr)
1908 << diagRange;
1909 }
1910
1911 // Display the "trail" of reference variables that we followed until we
1912 // found the problematic expression using notes.
1913 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1914 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1915 // If this var binds to another reference var, show the range of the next
1916 // var, otherwise the var binds to the problematic expression, in which case
1917 // show the range of the expression.
1918 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1919 : stackE->getSourceRange();
1920 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1921 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001922 }
1923}
1924
1925/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1926/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001927/// to a location on the stack, a local block, an address of a label, or a
1928/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001929/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001930/// encounter a subexpression that (1) clearly does not lead to one of the
1931/// above problematic expressions (2) is something we cannot determine leads to
1932/// a problematic expression based on such local checking.
1933///
1934/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1935/// the expression that they point to. Such variables are added to the
1936/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001937///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001938/// EvalAddr processes expressions that are pointers that are used as
1939/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001940/// At the base case of the recursion is a check for the above problematic
1941/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001942///
1943/// This implementation handles:
1944///
1945/// * pointer-to-pointer casts
1946/// * implicit conversions from array references to pointers
1947/// * taking the address of fields
1948/// * arbitrary interplay between "&" and "*" operators
1949/// * pointer arithmetic from an address of a stack variable
1950/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001951static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1952 if (E->isTypeDependent())
1953 return NULL;
1954
Ted Kremenek06de2762007-08-17 16:46:58 +00001955 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001956 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001957 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001958 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001959 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Peter Collingbournef111d932011-04-15 00:35:48 +00001961 E = E->IgnoreParens();
1962
Ted Kremenek06de2762007-08-17 16:46:58 +00001963 // Our "symbolic interpreter" is just a dispatch off the currently
1964 // viewed AST node. We then recursively traverse the AST by calling
1965 // EvalAddr and EvalVal appropriately.
1966 switch (E->getStmtClass()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001967 case Stmt::DeclRefExprClass: {
1968 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1969
1970 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1971 // If this is a reference variable, follow through to the expression that
1972 // it points to.
1973 if (V->hasLocalStorage() &&
1974 V->getType()->isReferenceType() && V->hasInit()) {
1975 // Add the reference variable to the "trail".
1976 refVars.push_back(DR);
1977 return EvalAddr(V->getInit(), refVars);
1978 }
1979
1980 return NULL;
1981 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001982
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001983 case Stmt::UnaryOperatorClass: {
1984 // The only unary operator that make sense to handle here
1985 // is AddrOf. All others don't make sense as pointers.
1986 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001987
John McCall2de56d12010-08-25 11:45:40 +00001988 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001989 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001990 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001991 return NULL;
1992 }
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001994 case Stmt::BinaryOperatorClass: {
1995 // Handle pointer arithmetic. All other binary operators are not valid
1996 // in this context.
1997 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001998 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001999
John McCall2de56d12010-08-25 11:45:40 +00002000 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002001 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002003 Expr *Base = B->getLHS();
2004
2005 // Determine which argument is the real pointer base. It could be
2006 // the RHS argument instead of the LHS.
2007 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002009 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002010 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002011 }
Steve Naroff61f40a22008-09-10 19:17:48 +00002012
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002013 // For conditional operators we need to see if either the LHS or RHS are
2014 // valid DeclRefExpr*s. If one of them is valid, we return it.
2015 case Stmt::ConditionalOperatorClass: {
2016 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002018 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002019 if (Expr *lhsExpr = C->getLHS()) {
2020 // In C++, we can have a throw-expression, which has 'void' type.
2021 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002022 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002023 return LHS;
2024 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002025
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00002026 // In C++, we can have a throw-expression, which has 'void' type.
2027 if (C->getRHS()->getType()->isVoidType())
2028 return NULL;
2029
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002030 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002031 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002032
2033 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00002034 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002035 return E; // local block.
2036 return NULL;
2037
2038 case Stmt::AddrLabelExprClass:
2039 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Ted Kremenek54b52742008-08-07 00:49:01 +00002041 // For casts, we need to handle conversions from arrays to
2042 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00002043 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002044 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002045 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002046 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00002047 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Steve Naroffdd972f22008-09-05 22:11:13 +00002049 if (SubExpr->getType()->isPointerType() ||
2050 SubExpr->getType()->isBlockPointerType() ||
2051 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002052 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00002053 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002054 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002055 else
Ted Kremenek54b52742008-08-07 00:49:01 +00002056 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002059 // C++ casts. For dynamic casts, static casts, and const casts, we
2060 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00002061 // through the cast. In the case the dynamic cast doesn't fail (and
2062 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002063 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00002064 // FIXME: The comment about is wrong; we're not always converting
2065 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00002066 // handle references to objects.
2067 case Stmt::CXXStaticCastExprClass:
2068 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00002069 case Stmt::CXXConstCastExprClass:
2070 case Stmt::CXXReinterpretCastExprClass: {
2071 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00002072 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002073 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002074 else
2075 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002076 }
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00002078 // Everything else: we simply don't reason about them.
2079 default:
2080 return NULL;
2081 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002082}
Mike Stump1eb44332009-09-09 15:08:12 +00002083
Ted Kremenek06de2762007-08-17 16:46:58 +00002084
2085/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2086/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002087static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002088do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002089 // We should only be called for evaluating non-pointer expressions, or
2090 // expressions with a pointer type that are not used as references but instead
2091 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Ted Kremenek06de2762007-08-17 16:46:58 +00002093 // Our "symbolic interpreter" is just a dispatch off the currently
2094 // viewed AST node. We then recursively traverse the AST by calling
2095 // EvalAddr and EvalVal appropriately.
Peter Collingbournef111d932011-04-15 00:35:48 +00002096
2097 E = E->IgnoreParens();
Ted Kremenek06de2762007-08-17 16:46:58 +00002098 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002099 case Stmt::ImplicitCastExprClass: {
2100 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002101 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002102 E = IE->getSubExpr();
2103 continue;
2104 }
2105 return NULL;
2106 }
2107
Douglas Gregora2813ce2009-10-23 18:54:35 +00002108 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002109 // When we hit a DeclRefExpr we are looking at code that refers to a
2110 // variable's name. If it's not a reference variable we check if it has
2111 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002112 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002113
Ted Kremenek06de2762007-08-17 16:46:58 +00002114 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002115 if (V->hasLocalStorage()) {
2116 if (!V->getType()->isReferenceType())
2117 return DR;
2118
2119 // Reference variable, follow through to the expression that
2120 // it points to.
2121 if (V->hasInit()) {
2122 // Add the reference variable to the "trail".
2123 refVars.push_back(DR);
2124 return EvalVal(V->getInit(), refVars);
2125 }
2126 }
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Ted Kremenek06de2762007-08-17 16:46:58 +00002128 return NULL;
2129 }
Mike Stump1eb44332009-09-09 15:08:12 +00002130
Ted Kremenek06de2762007-08-17 16:46:58 +00002131 case Stmt::UnaryOperatorClass: {
2132 // The only unary operator that make sense to handle here
2133 // is Deref. All others don't resolve to a "name." This includes
2134 // handling all sorts of rvalues passed to a unary operator.
2135 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
John McCall2de56d12010-08-25 11:45:40 +00002137 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002138 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002139
2140 return NULL;
2141 }
Mike Stump1eb44332009-09-09 15:08:12 +00002142
Ted Kremenek06de2762007-08-17 16:46:58 +00002143 case Stmt::ArraySubscriptExprClass: {
2144 // Array subscripts are potential references to data on the stack. We
2145 // retrieve the DeclRefExpr* for the array variable if it indeed
2146 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002147 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002148 }
Mike Stump1eb44332009-09-09 15:08:12 +00002149
Ted Kremenek06de2762007-08-17 16:46:58 +00002150 case Stmt::ConditionalOperatorClass: {
2151 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002152 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002153 ConditionalOperator *C = cast<ConditionalOperator>(E);
2154
Anders Carlsson39073232007-11-30 19:04:31 +00002155 // Handle the GNU extension for missing LHS.
2156 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002157 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002158 return LHS;
2159
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002160 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002161 }
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Ted Kremenek06de2762007-08-17 16:46:58 +00002163 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002164 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002165 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Ted Kremenek06de2762007-08-17 16:46:58 +00002167 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002168 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002169 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002170
2171 // Check whether the member type is itself a reference, in which case
2172 // we're not going to refer to the member, but to what the member refers to.
2173 if (M->getMemberDecl()->getType()->isReferenceType())
2174 return NULL;
2175
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002176 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002177 }
Mike Stump1eb44332009-09-09 15:08:12 +00002178
Ted Kremenek06de2762007-08-17 16:46:58 +00002179 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002180 // Check that we don't return or take the address of a reference to a
2181 // temporary. This is only useful in C++.
2182 if (!E->isTypeDependent() && E->isRValue())
2183 return E;
2184
2185 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002186 return NULL;
2187 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002188} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002189}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002190
2191//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2192
2193/// Check for comparisons of floating point operands using != and ==.
2194/// Issue a warning if these are no self-comparisons, as they are not likely
2195/// to do what the programmer intended.
2196void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2197 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002198
John McCallf6a16482010-12-04 03:47:34 +00002199 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2200 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002201
2202 // Special case: check for x == x (which is OK).
2203 // Do not emit warnings for such cases.
2204 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2205 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2206 if (DRL->getDecl() == DRR->getDecl())
2207 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002208
2209
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002210 // Special case: check for comparisons against literals that can be exactly
2211 // represented by APFloat. In such cases, do not emit a warning. This
2212 // is a heuristic: often comparison against such literals are used to
2213 // detect if a value in a variable has not changed. This clearly can
2214 // lead to false negatives.
2215 if (EmitWarning) {
2216 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2217 if (FLL->isExact())
2218 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002219 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002220 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2221 if (FLR->isExact())
2222 EmitWarning = false;
2223 }
2224 }
Mike Stump1eb44332009-09-09 15:08:12 +00002225
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002226 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002227 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002228 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002229 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002230 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002231
Sebastian Redl0eb23302009-01-19 00:08:26 +00002232 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002233 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002234 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002235 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002236
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002237 // Emit the diagnostic.
2238 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002239 Diag(loc, diag::warn_floatingpoint_eq)
2240 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002241}
John McCallba26e582010-01-04 23:21:16 +00002242
John McCallf2370c92010-01-06 05:24:50 +00002243//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2244//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002245
John McCallf2370c92010-01-06 05:24:50 +00002246namespace {
John McCallba26e582010-01-04 23:21:16 +00002247
John McCallf2370c92010-01-06 05:24:50 +00002248/// Structure recording the 'active' range of an integer-valued
2249/// expression.
2250struct IntRange {
2251 /// The number of bits active in the int.
2252 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002253
John McCallf2370c92010-01-06 05:24:50 +00002254 /// True if the int is known not to have negative values.
2255 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002256
John McCallf2370c92010-01-06 05:24:50 +00002257 IntRange(unsigned Width, bool NonNegative)
2258 : Width(Width), NonNegative(NonNegative)
2259 {}
John McCallba26e582010-01-04 23:21:16 +00002260
John McCall1844a6e2010-11-10 23:38:19 +00002261 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002262 static IntRange forBoolType() {
2263 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002264 }
2265
John McCall1844a6e2010-11-10 23:38:19 +00002266 /// Returns the range of an opaque value of the given integral type.
2267 static IntRange forValueOfType(ASTContext &C, QualType T) {
2268 return forValueOfCanonicalType(C,
2269 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002270 }
2271
John McCall1844a6e2010-11-10 23:38:19 +00002272 /// Returns the range of an opaque value of a canonical integral type.
2273 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002274 assert(T->isCanonicalUnqualified());
2275
2276 if (const VectorType *VT = dyn_cast<VectorType>(T))
2277 T = VT->getElementType().getTypePtr();
2278 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2279 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002280
John McCall091f23f2010-11-09 22:22:12 +00002281 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002282 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2283 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002284 if (!Enum->isDefinition())
2285 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2286
John McCall323ed742010-05-06 08:58:33 +00002287 unsigned NumPositive = Enum->getNumPositiveBits();
2288 unsigned NumNegative = Enum->getNumNegativeBits();
2289
2290 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2291 }
John McCallf2370c92010-01-06 05:24:50 +00002292
2293 const BuiltinType *BT = cast<BuiltinType>(T);
2294 assert(BT->isInteger());
2295
2296 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2297 }
2298
John McCall1844a6e2010-11-10 23:38:19 +00002299 /// Returns the "target" range of a canonical integral type, i.e.
2300 /// the range of values expressible in the type.
2301 ///
2302 /// This matches forValueOfCanonicalType except that enums have the
2303 /// full range of their type, not the range of their enumerators.
2304 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2305 assert(T->isCanonicalUnqualified());
2306
2307 if (const VectorType *VT = dyn_cast<VectorType>(T))
2308 T = VT->getElementType().getTypePtr();
2309 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2310 T = CT->getElementType().getTypePtr();
2311 if (const EnumType *ET = dyn_cast<EnumType>(T))
2312 T = ET->getDecl()->getIntegerType().getTypePtr();
2313
2314 const BuiltinType *BT = cast<BuiltinType>(T);
2315 assert(BT->isInteger());
2316
2317 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2318 }
2319
2320 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002321 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002322 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002323 L.NonNegative && R.NonNegative);
2324 }
2325
John McCall1844a6e2010-11-10 23:38:19 +00002326 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002327 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002328 return IntRange(std::min(L.Width, R.Width),
2329 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002330 }
2331};
2332
2333IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2334 if (value.isSigned() && value.isNegative())
2335 return IntRange(value.getMinSignedBits(), false);
2336
2337 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002338 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002339
2340 // isNonNegative() just checks the sign bit without considering
2341 // signedness.
2342 return IntRange(value.getActiveBits(), true);
2343}
2344
John McCall0acc3112010-01-06 22:57:21 +00002345IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002346 unsigned MaxWidth) {
2347 if (result.isInt())
2348 return GetValueRange(C, result.getInt(), MaxWidth);
2349
2350 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002351 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2352 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2353 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2354 R = IntRange::join(R, El);
2355 }
John McCallf2370c92010-01-06 05:24:50 +00002356 return R;
2357 }
2358
2359 if (result.isComplexInt()) {
2360 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2361 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2362 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002363 }
2364
2365 // This can happen with lossless casts to intptr_t of "based" lvalues.
2366 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002367 // FIXME: The only reason we need to pass the type in here is to get
2368 // the sign right on this one case. It would be nice if APValue
2369 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002370 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002371 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002372}
John McCallf2370c92010-01-06 05:24:50 +00002373
2374/// Pseudo-evaluate the given integer expression, estimating the
2375/// range of values it might take.
2376///
2377/// \param MaxWidth - the width to which the value will be truncated
2378IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2379 E = E->IgnoreParens();
2380
2381 // Try a full evaluation first.
2382 Expr::EvalResult result;
2383 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002384 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002385
2386 // I think we only want to look through implicit casts here; if the
2387 // user has an explicit widening cast, we should treat the value as
2388 // being of the new, wider type.
2389 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002390 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002391 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2392
John McCall1844a6e2010-11-10 23:38:19 +00002393 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002394
John McCall2de56d12010-08-25 11:45:40 +00002395 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002396
John McCallf2370c92010-01-06 05:24:50 +00002397 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002398 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002399 return OutputTypeRange;
2400
2401 IntRange SubRange
2402 = GetExprRange(C, CE->getSubExpr(),
2403 std::min(MaxWidth, OutputTypeRange.Width));
2404
2405 // Bail out if the subexpr's range is as wide as the cast type.
2406 if (SubRange.Width >= OutputTypeRange.Width)
2407 return OutputTypeRange;
2408
2409 // Otherwise, we take the smaller width, and we're non-negative if
2410 // either the output type or the subexpr is.
2411 return IntRange(SubRange.Width,
2412 SubRange.NonNegative || OutputTypeRange.NonNegative);
2413 }
2414
2415 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2416 // If we can fold the condition, just take that operand.
2417 bool CondResult;
2418 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2419 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2420 : CO->getFalseExpr(),
2421 MaxWidth);
2422
2423 // Otherwise, conservatively merge.
2424 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2425 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2426 return IntRange::join(L, R);
2427 }
2428
2429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2430 switch (BO->getOpcode()) {
2431
2432 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002433 case BO_LAnd:
2434 case BO_LOr:
2435 case BO_LT:
2436 case BO_GT:
2437 case BO_LE:
2438 case BO_GE:
2439 case BO_EQ:
2440 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002441 return IntRange::forBoolType();
2442
John McCallc0cd21d2010-02-23 19:22:29 +00002443 // The type of these compound assignments is the type of the LHS,
2444 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002445 case BO_MulAssign:
2446 case BO_DivAssign:
2447 case BO_RemAssign:
2448 case BO_AddAssign:
2449 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002450 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002451
John McCallf2370c92010-01-06 05:24:50 +00002452 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002453 case BO_PtrMemD:
2454 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002455 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002456
John McCall60fad452010-01-06 22:07:33 +00002457 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002458 case BO_And:
2459 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002460 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2461 GetExprRange(C, BO->getRHS(), MaxWidth));
2462
John McCallf2370c92010-01-06 05:24:50 +00002463 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002464 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002465 // ...except that we want to treat '1 << (blah)' as logically
2466 // positive. It's an important idiom.
2467 if (IntegerLiteral *I
2468 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2469 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002470 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002471 return IntRange(R.Width, /*NonNegative*/ true);
2472 }
2473 }
2474 // fallthrough
2475
John McCall2de56d12010-08-25 11:45:40 +00002476 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002477 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002478
John McCall60fad452010-01-06 22:07:33 +00002479 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002480 case BO_Shr:
2481 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002482 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2483
2484 // If the shift amount is a positive constant, drop the width by
2485 // that much.
2486 llvm::APSInt shift;
2487 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2488 shift.isNonNegative()) {
2489 unsigned zext = shift.getZExtValue();
2490 if (zext >= L.Width)
2491 L.Width = (L.NonNegative ? 0 : 1);
2492 else
2493 L.Width -= zext;
2494 }
2495
2496 return L;
2497 }
2498
2499 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002500 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002501 return GetExprRange(C, BO->getRHS(), MaxWidth);
2502
John McCall60fad452010-01-06 22:07:33 +00002503 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002504 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002505 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002506 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002507 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002508
John McCallf2370c92010-01-06 05:24:50 +00002509 default:
2510 break;
2511 }
2512
2513 // Treat every other operator as if it were closed on the
2514 // narrowest type that encompasses both operands.
2515 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2516 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2517 return IntRange::join(L, R);
2518 }
2519
2520 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2521 switch (UO->getOpcode()) {
2522 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002523 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002524 return IntRange::forBoolType();
2525
2526 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002527 case UO_Deref:
2528 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002529 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002530
2531 default:
2532 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2533 }
2534 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002535
2536 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002537 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002538 }
John McCallf2370c92010-01-06 05:24:50 +00002539
2540 FieldDecl *BitField = E->getBitField();
2541 if (BitField) {
2542 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2543 unsigned BitWidth = BitWidthAP.getZExtValue();
2544
2545 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2546 }
2547
John McCall1844a6e2010-11-10 23:38:19 +00002548 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002549}
John McCall51313c32010-01-04 23:31:57 +00002550
John McCall323ed742010-05-06 08:58:33 +00002551IntRange GetExprRange(ASTContext &C, Expr *E) {
2552 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2553}
2554
John McCall51313c32010-01-04 23:31:57 +00002555/// Checks whether the given value, which currently has the given
2556/// source semantics, has the same value when coerced through the
2557/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002558bool IsSameFloatAfterCast(const llvm::APFloat &value,
2559 const llvm::fltSemantics &Src,
2560 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002561 llvm::APFloat truncated = value;
2562
2563 bool ignored;
2564 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2565 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2566
2567 return truncated.bitwiseIsEqual(value);
2568}
2569
2570/// Checks whether the given value, which currently has the given
2571/// source semantics, has the same value when coerced through the
2572/// target semantics.
2573///
2574/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002575bool IsSameFloatAfterCast(const APValue &value,
2576 const llvm::fltSemantics &Src,
2577 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002578 if (value.isFloat())
2579 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2580
2581 if (value.isVector()) {
2582 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2583 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2584 return false;
2585 return true;
2586 }
2587
2588 assert(value.isComplexFloat());
2589 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2590 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2591}
2592
John McCallb4eb64d2010-10-08 02:01:28 +00002593void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002594
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002595static bool IsZero(Sema &S, Expr *E) {
2596 // Suppress cases where we are comparing against an enum constant.
2597 if (const DeclRefExpr *DR =
2598 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2599 if (isa<EnumConstantDecl>(DR->getDecl()))
2600 return false;
2601
2602 // Suppress cases where the '0' value is expanded from a macro.
2603 if (E->getLocStart().isMacroID())
2604 return false;
2605
John McCall323ed742010-05-06 08:58:33 +00002606 llvm::APSInt Value;
2607 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2608}
2609
John McCall372e1032010-10-06 00:25:24 +00002610static bool HasEnumType(Expr *E) {
2611 // Strip off implicit integral promotions.
2612 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002613 if (ICE->getCastKind() != CK_IntegralCast &&
2614 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002615 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002616 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002617 }
2618
2619 return E->getType()->isEnumeralType();
2620}
2621
John McCall323ed742010-05-06 08:58:33 +00002622void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002623 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002624 if (E->isValueDependent())
2625 return;
2626
John McCall2de56d12010-08-25 11:45:40 +00002627 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002628 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002629 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002630 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002631 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002632 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002633 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002634 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002635 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002636 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002637 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002638 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002639 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002640 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002641 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002642 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2643 }
2644}
2645
2646/// Analyze the operands of the given comparison. Implements the
2647/// fallback case from AnalyzeComparison.
2648void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002649 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2650 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002651}
John McCall51313c32010-01-04 23:31:57 +00002652
John McCallba26e582010-01-04 23:21:16 +00002653/// \brief Implements -Wsign-compare.
2654///
2655/// \param lex the left-hand expression
2656/// \param rex the right-hand expression
2657/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002658/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002659void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2660 // The type the comparison is being performed in.
2661 QualType T = E->getLHS()->getType();
2662 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2663 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002664
John McCall323ed742010-05-06 08:58:33 +00002665 // We don't do anything special if this isn't an unsigned integral
2666 // comparison: we're only interested in integral comparisons, and
2667 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002668 //
2669 // We also don't care about value-dependent expressions or expressions
2670 // whose result is a constant.
2671 if (!T->hasUnsignedIntegerRepresentation()
2672 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002673 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002674
John McCall323ed742010-05-06 08:58:33 +00002675 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2676 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002677
John McCall323ed742010-05-06 08:58:33 +00002678 // Check to see if one of the (unmodified) operands is of different
2679 // signedness.
2680 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002681 if (lex->getType()->hasSignedIntegerRepresentation()) {
2682 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002683 "unsigned comparison between two signed integer expressions?");
2684 signedOperand = lex;
2685 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002686 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002687 signedOperand = rex;
2688 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002689 } else {
John McCall323ed742010-05-06 08:58:33 +00002690 CheckTrivialUnsignedComparison(S, E);
2691 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002692 }
2693
John McCall323ed742010-05-06 08:58:33 +00002694 // Otherwise, calculate the effective range of the signed operand.
2695 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002696
John McCall323ed742010-05-06 08:58:33 +00002697 // Go ahead and analyze implicit conversions in the operands. Note
2698 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002699 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2700 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002701
John McCall323ed742010-05-06 08:58:33 +00002702 // If the signed range is non-negative, -Wsign-compare won't fire,
2703 // but we should still check for comparisons which are always true
2704 // or false.
2705 if (signedRange.NonNegative)
2706 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002707
2708 // For (in)equality comparisons, if the unsigned operand is a
2709 // constant which cannot collide with a overflowed signed operand,
2710 // then reinterpreting the signed operand as unsigned will not
2711 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002712 if (E->isEqualityOp()) {
2713 unsigned comparisonWidth = S.Context.getIntWidth(T);
2714 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002715
John McCall323ed742010-05-06 08:58:33 +00002716 // We should never be unable to prove that the unsigned operand is
2717 // non-negative.
2718 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2719
2720 if (unsignedRange.Width < comparisonWidth)
2721 return;
2722 }
2723
2724 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2725 << lex->getType() << rex->getType()
2726 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002727}
2728
John McCall15d7d122010-11-11 03:21:53 +00002729/// Analyzes an attempt to assign the given value to a bitfield.
2730///
2731/// Returns true if there was something fishy about the attempt.
2732bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2733 SourceLocation InitLoc) {
2734 assert(Bitfield->isBitField());
2735 if (Bitfield->isInvalidDecl())
2736 return false;
2737
John McCall91b60142010-11-11 05:33:51 +00002738 // White-list bool bitfields.
2739 if (Bitfield->getType()->isBooleanType())
2740 return false;
2741
Douglas Gregor46ff3032011-02-04 13:09:01 +00002742 // Ignore value- or type-dependent expressions.
2743 if (Bitfield->getBitWidth()->isValueDependent() ||
2744 Bitfield->getBitWidth()->isTypeDependent() ||
2745 Init->isValueDependent() ||
2746 Init->isTypeDependent())
2747 return false;
2748
John McCall15d7d122010-11-11 03:21:53 +00002749 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2750
2751 llvm::APSInt Width(32);
2752 Expr::EvalResult InitValue;
2753 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002754 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002755 !InitValue.Val.isInt())
2756 return false;
2757
2758 const llvm::APSInt &Value = InitValue.Val.getInt();
2759 unsigned OriginalWidth = Value.getBitWidth();
2760 unsigned FieldWidth = Width.getZExtValue();
2761
2762 if (OriginalWidth <= FieldWidth)
2763 return false;
2764
Jay Foad9f71a8f2010-12-07 08:25:34 +00002765 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002766
2767 // It's fairly common to write values into signed bitfields
2768 // that, if sign-extended, would end up becoming a different
2769 // value. We don't want to warn about that.
2770 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002771 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002772 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002773 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002774
2775 if (Value == TruncatedValue)
2776 return false;
2777
2778 std::string PrettyValue = Value.toString(10);
2779 std::string PrettyTrunc = TruncatedValue.toString(10);
2780
2781 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2782 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2783 << Init->getSourceRange();
2784
2785 return true;
2786}
2787
John McCallbeb22aa2010-11-09 23:24:47 +00002788/// Analyze the given simple or compound assignment for warning-worthy
2789/// operations.
2790void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2791 // Just recurse on the LHS.
2792 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2793
2794 // We want to recurse on the RHS as normal unless we're assigning to
2795 // a bitfield.
2796 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002797 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2798 E->getOperatorLoc())) {
2799 // Recurse, ignoring any implicit conversions on the RHS.
2800 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2801 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002802 }
2803 }
2804
2805 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2806}
2807
John McCall51313c32010-01-04 23:31:57 +00002808/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00002809void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2810 SourceLocation CContext, unsigned diag) {
2811 S.Diag(E->getExprLoc(), diag)
2812 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2813}
2814
Chandler Carruthe1b02e02011-04-05 06:47:57 +00002815/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2816void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2817 unsigned diag) {
2818 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2819}
2820
Chandler Carruthf65076e2011-04-10 08:36:24 +00002821/// Diagnose an implicit cast from a literal expression. Also attemps to supply
2822/// fixit hints when the cast wouldn't lose information to simply write the
2823/// expression with the expected type.
2824void DiagnoseFloatingLiteralImpCast(Sema &S, FloatingLiteral *FL, QualType T,
2825 SourceLocation CContext) {
2826 // Emit the primary warning first, then try to emit a fixit hint note if
2827 // reasonable.
2828 S.Diag(FL->getExprLoc(), diag::warn_impcast_literal_float_to_integer)
2829 << FL->getType() << T << FL->getSourceRange() << SourceRange(CContext);
2830
2831 const llvm::APFloat &Value = FL->getValue();
2832
2833 // Don't attempt to fix PPC double double literals.
2834 if (&Value.getSemantics() == &llvm::APFloat::PPCDoubleDouble)
2835 return;
2836
2837 // Try to convert this exactly to an 64-bit integer. FIXME: It would be
2838 // nice to support arbitrarily large integers here.
2839 bool isExact = false;
2840 uint64_t IntegerPart;
2841 if (Value.convertToInteger(&IntegerPart, 64, /*isSigned=*/true,
2842 llvm::APFloat::rmTowardZero, &isExact)
2843 != llvm::APFloat::opOK || !isExact)
2844 return;
2845
2846 llvm::APInt IntegerValue(64, IntegerPart, /*isSigned=*/true);
2847
2848 std::string LiteralValue = IntegerValue.toString(10, /*isSigned=*/true);
2849 S.Diag(FL->getExprLoc(), diag::note_fix_integral_float_as_integer)
2850 << FixItHint::CreateReplacement(FL->getSourceRange(), LiteralValue);
2851}
2852
John McCall091f23f2010-11-09 22:22:12 +00002853std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2854 if (!Range.Width) return "0";
2855
2856 llvm::APSInt ValueInRange = Value;
2857 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002858 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002859 return ValueInRange.toString(10);
2860}
2861
Ted Kremenekef9ff882011-03-10 20:03:42 +00002862static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2863 SourceManager &smgr = S.Context.getSourceManager();
2864 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2865}
Chandler Carruthf65076e2011-04-10 08:36:24 +00002866
John McCall323ed742010-05-06 08:58:33 +00002867void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002868 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002869 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002870
John McCall323ed742010-05-06 08:58:33 +00002871 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2872 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2873 if (Source == Target) return;
2874 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002875
Ted Kremenekef9ff882011-03-10 20:03:42 +00002876 // If the conversion context location is invalid don't complain.
2877 // We also don't want to emit a warning if the issue occurs from the
2878 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2879 // is slow, so we delay this check as long as possible. Once we detect
2880 // we are in that scenario, we just return.
2881 if (CC.isInvalid())
John McCallb4eb64d2010-10-08 02:01:28 +00002882 return;
2883
John McCall51313c32010-01-04 23:31:57 +00002884 // Never diagnose implicit casts to bool.
2885 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2886 return;
2887
2888 // Strip vector types.
2889 if (isa<VectorType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002890 if (!isa<VectorType>(Target)) {
2891 if (isFromSystemMacro(S, CC))
2892 return;
John McCallb4eb64d2010-10-08 02:01:28 +00002893 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002894 }
John McCall51313c32010-01-04 23:31:57 +00002895
2896 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2897 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2898 }
2899
2900 // Strip complex types.
2901 if (isa<ComplexType>(Source)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002902 if (!isa<ComplexType>(Target)) {
2903 if (isFromSystemMacro(S, CC))
2904 return;
2905
John McCallb4eb64d2010-10-08 02:01:28 +00002906 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenekef9ff882011-03-10 20:03:42 +00002907 }
John McCall51313c32010-01-04 23:31:57 +00002908
2909 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2910 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2911 }
2912
2913 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2914 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2915
2916 // If the source is floating point...
2917 if (SourceBT && SourceBT->isFloatingPoint()) {
2918 // ...and the target is floating point...
2919 if (TargetBT && TargetBT->isFloatingPoint()) {
2920 // ...then warn if we're dropping FP rank.
2921
2922 // Builtin FP kinds are ordered by increasing FP rank.
2923 if (SourceBT->getKind() > TargetBT->getKind()) {
2924 // Don't warn about float constants that are precisely
2925 // representable in the target type.
2926 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002927 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002928 // Value might be a float, a float vector, or a float complex.
2929 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002930 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2931 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002932 return;
2933 }
2934
Ted Kremenekef9ff882011-03-10 20:03:42 +00002935 if (isFromSystemMacro(S, CC))
2936 return;
2937
John McCallb4eb64d2010-10-08 02:01:28 +00002938 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002939 }
2940 return;
2941 }
2942
Ted Kremenekef9ff882011-03-10 20:03:42 +00002943 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002944 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002945 if (isFromSystemMacro(S, CC))
2946 return;
2947
Chandler Carrutha5b93322011-02-17 11:05:49 +00002948 Expr *InnerE = E->IgnoreParenImpCasts();
Chandler Carruthf65076e2011-04-10 08:36:24 +00002949 if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(InnerE)) {
2950 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
Chandler Carrutha5b93322011-02-17 11:05:49 +00002951 } else {
2952 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2953 }
2954 }
John McCall51313c32010-01-04 23:31:57 +00002955
2956 return;
2957 }
2958
John McCallf2370c92010-01-06 05:24:50 +00002959 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002960 return;
2961
John McCall323ed742010-05-06 08:58:33 +00002962 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002963 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002964
2965 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002966 // If the source is a constant, use a default-on diagnostic.
2967 // TODO: this should happen for bitfield stores, too.
2968 llvm::APSInt Value(32);
2969 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002970 if (isFromSystemMacro(S, CC))
2971 return;
2972
John McCall091f23f2010-11-09 22:22:12 +00002973 std::string PrettySourceValue = Value.toString(10);
2974 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2975
2976 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2977 << PrettySourceValue << PrettyTargetValue
2978 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2979 return;
2980 }
2981
John McCall51313c32010-01-04 23:31:57 +00002982 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2983 // and by god we'll let them.
Ted Kremenekef9ff882011-03-10 20:03:42 +00002984
2985 if (isFromSystemMacro(S, CC))
2986 return;
2987
John McCallf2370c92010-01-06 05:24:50 +00002988 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002989 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2990 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002991 }
2992
2993 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2994 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2995 SourceRange.Width == TargetRange.Width)) {
Ted Kremenekef9ff882011-03-10 20:03:42 +00002996
2997 if (isFromSystemMacro(S, CC))
2998 return;
2999
John McCall323ed742010-05-06 08:58:33 +00003000 unsigned DiagID = diag::warn_impcast_integer_sign;
3001
3002 // Traditionally, gcc has warned about this under -Wsign-compare.
3003 // We also want to warn about it in -Wconversion.
3004 // So if -Wconversion is off, use a completely identical diagnostic
3005 // in the sign-compare group.
3006 // The conditional-checking code will
3007 if (ICContext) {
3008 DiagID = diag::warn_impcast_integer_sign_conditional;
3009 *ICContext = true;
3010 }
3011
John McCallb4eb64d2010-10-08 02:01:28 +00003012 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00003013 }
3014
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003015 // Diagnose conversions between different enumeration types.
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003016 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
3017 // type, to give us better diagnostics.
3018 QualType SourceType = E->getType();
3019 if (!S.getLangOptions().CPlusPlus) {
3020 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
3021 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
3022 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
3023 SourceType = S.Context.getTypeDeclType(Enum);
3024 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
3025 }
3026 }
3027
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003028 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
3029 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
3030 if ((SourceEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003031 SourceEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003032 (TargetEnum->getDecl()->getIdentifier() ||
Richard Smith162e1c12011-04-15 14:24:37 +00003033 TargetEnum->getDecl()->getTypedefNameForAnonDecl()) &&
Ted Kremenekef9ff882011-03-10 20:03:42 +00003034 SourceEnum != TargetEnum) {
3035 if (isFromSystemMacro(S, CC))
3036 return;
3037
Douglas Gregor5a5b38f2011-03-12 00:14:31 +00003038 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003039 diag::warn_impcast_different_enum_types);
Ted Kremenekef9ff882011-03-10 20:03:42 +00003040 }
Douglas Gregor284cc8d2011-02-22 02:45:07 +00003041
John McCall51313c32010-01-04 23:31:57 +00003042 return;
3043}
3044
John McCall323ed742010-05-06 08:58:33 +00003045void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
3046
3047void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00003048 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00003049 E = E->IgnoreParenImpCasts();
3050
3051 if (isa<ConditionalOperator>(E))
3052 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
3053
John McCallb4eb64d2010-10-08 02:01:28 +00003054 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003055 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003056 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00003057 return;
3058}
3059
3060void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00003061 SourceLocation CC = E->getQuestionLoc();
3062
3063 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00003064
3065 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00003066 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
3067 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003068
3069 // If -Wconversion would have warned about either of the candidates
3070 // for a signedness conversion to the context type...
3071 if (!Suspicious) return;
3072
3073 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003074 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
3075 CC))
John McCall323ed742010-05-06 08:58:33 +00003076 return;
3077
3078 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003079 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00003080 return;
3081
3082 // ...then check whether it would have warned about either of the
3083 // candidates for a signedness conversion to the condition type.
3084 if (E->getType() != T) {
3085 Suspicious = false;
3086 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003087 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003088 if (!Suspicious)
3089 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00003090 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00003091 if (!Suspicious)
3092 return;
3093 }
3094
3095 // If so, emit a diagnostic under -Wsign-compare.
3096 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3097 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3098 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3099 << lex->getType() << rex->getType()
3100 << lex->getSourceRange() << rex->getSourceRange();
3101}
3102
3103/// AnalyzeImplicitConversions - Find and report any interesting
3104/// implicit conversions in the given expression. There are a couple
3105/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003106void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003107 QualType T = OrigE->getType();
3108 Expr *E = OrigE->IgnoreParenImpCasts();
3109
3110 // For conditional operators, we analyze the arguments as if they
3111 // were being fed directly into the output.
3112 if (isa<ConditionalOperator>(E)) {
3113 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3114 CheckConditionalOperator(S, CO, T);
3115 return;
3116 }
3117
3118 // Go ahead and check any implicit conversions we might have skipped.
3119 // The non-canonical typecheck is just an optimization;
3120 // CheckImplicitConversion will filter out dead implicit conversions.
3121 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00003122 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00003123
3124 // Now continue drilling into this expression.
3125
3126 // Skip past explicit casts.
3127 if (isa<ExplicitCastExpr>(E)) {
3128 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00003129 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003130 }
3131
John McCallbeb22aa2010-11-09 23:24:47 +00003132 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3133 // Do a somewhat different check with comparison operators.
3134 if (BO->isComparisonOp())
3135 return AnalyzeComparison(S, BO);
3136
3137 // And with assignments and compound assignments.
3138 if (BO->isAssignmentOp())
3139 return AnalyzeAssignment(S, BO);
3140 }
John McCall323ed742010-05-06 08:58:33 +00003141
3142 // These break the otherwise-useful invariant below. Fortunately,
3143 // we don't really need to recurse into them, because any internal
3144 // expressions should have been analyzed already when they were
3145 // built into statements.
3146 if (isa<StmtExpr>(E)) return;
3147
3148 // Don't descend into unevaluated contexts.
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003149 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCall323ed742010-05-06 08:58:33 +00003150
3151 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00003152 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00003153 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00003154 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00003155}
3156
3157} // end anonymous namespace
3158
3159/// Diagnoses "dangerous" implicit conversions within the given
3160/// expression (which is a full expression). Implements -Wconversion
3161/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003162///
3163/// \param CC the "context" location of the implicit conversion, i.e.
3164/// the most location of the syntactic entity requiring the implicit
3165/// conversion
3166void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003167 // Don't diagnose in unevaluated contexts.
3168 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3169 return;
3170
3171 // Don't diagnose for value- or type-dependent expressions.
3172 if (E->isTypeDependent() || E->isValueDependent())
3173 return;
3174
John McCallb4eb64d2010-10-08 02:01:28 +00003175 // This is not the right CC for (e.g.) a variable initialization.
3176 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003177}
3178
John McCall15d7d122010-11-11 03:21:53 +00003179void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3180 FieldDecl *BitField,
3181 Expr *Init) {
3182 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3183}
3184
Mike Stumpf8c49212010-01-21 03:59:47 +00003185/// CheckParmsForFunctionDef - Check that the parameters of the given
3186/// function are appropriate for the definition of a function. This
3187/// takes care of any checks that cannot be performed on the
3188/// declaration itself, e.g., that the types of each of the function
3189/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003190bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3191 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003192 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003193 for (; P != PEnd; ++P) {
3194 ParmVarDecl *Param = *P;
3195
Mike Stumpf8c49212010-01-21 03:59:47 +00003196 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3197 // function declarator that is part of a function definition of
3198 // that function shall not have incomplete type.
3199 //
3200 // This is also C++ [dcl.fct]p6.
3201 if (!Param->isInvalidDecl() &&
3202 RequireCompleteType(Param->getLocation(), Param->getType(),
3203 diag::err_typecheck_decl_incomplete_type)) {
3204 Param->setInvalidDecl();
3205 HasInvalidParm = true;
3206 }
3207
3208 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3209 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003210 if (CheckParameterNames &&
3211 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003212 !Param->isImplicit() &&
3213 !getLangOptions().CPlusPlus)
3214 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003215
3216 // C99 6.7.5.3p12:
3217 // If the function declarator is not part of a definition of that
3218 // function, parameters may have incomplete type and may use the [*]
3219 // notation in their sequences of declarator specifiers to specify
3220 // variable length array types.
3221 QualType PType = Param->getOriginalType();
3222 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3223 if (AT->getSizeModifier() == ArrayType::Star) {
3224 // FIXME: This diagnosic should point the the '[*]' if source-location
3225 // information is added for it.
3226 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3227 }
3228 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003229 }
3230
3231 return HasInvalidParm;
3232}
John McCallb7f4ffe2010-08-12 21:44:57 +00003233
3234/// CheckCastAlign - Implements -Wcast-align, which warns when a
3235/// pointer cast increases the alignment requirements.
3236void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3237 // This is actually a lot of work to potentially be doing on every
3238 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003239 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3240 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003241 == Diagnostic::Ignored)
3242 return;
3243
3244 // Ignore dependent types.
3245 if (T->isDependentType() || Op->getType()->isDependentType())
3246 return;
3247
3248 // Require that the destination be a pointer type.
3249 const PointerType *DestPtr = T->getAs<PointerType>();
3250 if (!DestPtr) return;
3251
3252 // If the destination has alignment 1, we're done.
3253 QualType DestPointee = DestPtr->getPointeeType();
3254 if (DestPointee->isIncompleteType()) return;
3255 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3256 if (DestAlign.isOne()) return;
3257
3258 // Require that the source be a pointer type.
3259 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3260 if (!SrcPtr) return;
3261 QualType SrcPointee = SrcPtr->getPointeeType();
3262
3263 // Whitelist casts from cv void*. We already implicitly
3264 // whitelisted casts to cv void*, since they have alignment 1.
3265 // Also whitelist casts involving incomplete types, which implicitly
3266 // includes 'void'.
3267 if (SrcPointee->isIncompleteType()) return;
3268
3269 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3270 if (SrcAlign >= DestAlign) return;
3271
3272 Diag(TRange.getBegin(), diag::warn_cast_align)
3273 << Op->getType() << T
3274 << static_cast<unsigned>(SrcAlign.getQuantity())
3275 << static_cast<unsigned>(DestAlign.getQuantity())
3276 << TRange << Op->getSourceRange();
3277}
3278
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003279static void CheckArrayAccess_Check(Sema &S,
3280 const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003281 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003282 const ConstantArrayType *ArrayTy =
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003283 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003284 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003285 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003286
Chandler Carruth34064582011-02-17 20:55:08 +00003287 const Expr *IndexExpr = E->getIdx();
3288 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003289 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003290 llvm::APSInt index;
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003291 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003292 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003293
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003294 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003295 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003296 if (!size.isStrictlyPositive())
3297 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003298 if (size.getBitWidth() > index.getBitWidth())
3299 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003300 else if (size.getBitWidth() < index.getBitWidth())
3301 size = size.sext(index.getBitWidth());
3302
Chandler Carruth34064582011-02-17 20:55:08 +00003303 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003304 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003305
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003306 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3307 S.PDiag(diag::warn_array_index_exceeds_bounds)
3308 << index.toString(10, true)
3309 << size.toString(10, true)
3310 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003311 } else {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003312 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3313 S.PDiag(diag::warn_array_index_precedes_bounds)
3314 << index.toString(10, true)
3315 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003316 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003317
3318 const NamedDecl *ND = NULL;
3319 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3320 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3321 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3322 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3323 if (ND)
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003324 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3325 S.PDiag(diag::note_array_index_out_of_bounds)
3326 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003327}
3328
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003329void Sema::CheckArrayAccess(const Expr *expr) {
Peter Collingbournef111d932011-04-15 00:35:48 +00003330 while (true) {
3331 expr = expr->IgnoreParens();
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003332 switch (expr->getStmtClass()) {
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003333 case Stmt::ArraySubscriptExprClass:
3334 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3335 return;
3336 case Stmt::ConditionalOperatorClass: {
3337 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3338 if (const Expr *lhs = cond->getLHS())
3339 CheckArrayAccess(lhs);
3340 if (const Expr *rhs = cond->getRHS())
3341 CheckArrayAccess(rhs);
3342 return;
3343 }
3344 default:
3345 return;
3346 }
Peter Collingbournef111d932011-04-15 00:35:48 +00003347 }
Ted Kremenek3aea4da2011-03-01 18:41:00 +00003348}