blob: 97cc44e7372f4411ccd28d00f1ad22fbb5c15306 [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 McCall60d7b3a2010-08-24 06:29:42 +000069ExprResult
Anders Carlssond406bf02009-08-16 01:56:34 +000070Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCall60d7b3a2010-08-24 06:29:42 +000071 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregor2def4832008-11-17 20:34:05 +000072
Chris Lattner946928f2010-10-01 23:23:24 +000073 // Find out if any arguments are required to be integer constant expressions.
74 unsigned ICEArguments = 0;
75 ASTContext::GetBuiltinTypeError Error;
76 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
77 if (Error != ASTContext::GE_None)
78 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
79
80 // If any arguments are required to be ICE's, check and diagnose.
81 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
82 // Skip arguments not required to be ICE's.
83 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
84
85 llvm::APSInt Result;
86 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
87 return true;
88 ICEArguments &= ~(1 << ArgNo);
89 }
90
Anders Carlssond406bf02009-08-16 01:56:34 +000091 switch (BuiltinID) {
Chris Lattner30ce3442007-12-19 23:59:04 +000092 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner925e60d2007-12-28 05:29:59 +000093 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner1b9a0792007-12-20 00:26:33 +000094 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner69039812009-02-18 06:01:06 +000095 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redl0eb23302009-01-19 00:08:26 +000096 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +000097 break;
Ted Kremenek49ff7a12008-07-09 17:58:53 +000098 case Builtin::BI__builtin_stdarg_start:
Chris Lattner30ce3442007-12-19 23:59:04 +000099 case Builtin::BI__builtin_va_start:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000100 if (SemaBuiltinVAStart(TheCall))
101 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000102 break;
Chris Lattner1b9a0792007-12-20 00:26:33 +0000103 case Builtin::BI__builtin_isgreater:
104 case Builtin::BI__builtin_isgreaterequal:
105 case Builtin::BI__builtin_isless:
106 case Builtin::BI__builtin_islessequal:
107 case Builtin::BI__builtin_islessgreater:
108 case Builtin::BI__builtin_isunordered:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000109 if (SemaBuiltinUnorderedCompare(TheCall))
110 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000111 break;
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000112 case Builtin::BI__builtin_fpclassify:
113 if (SemaBuiltinFPClassification(TheCall, 6))
114 return ExprError();
115 break;
Eli Friedman9ac6f622009-08-31 20:06:00 +0000116 case Builtin::BI__builtin_isfinite:
117 case Builtin::BI__builtin_isinf:
118 case Builtin::BI__builtin_isinf_sign:
119 case Builtin::BI__builtin_isnan:
120 case Builtin::BI__builtin_isnormal:
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000121 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman9ac6f622009-08-31 20:06:00 +0000122 return ExprError();
123 break;
Eli Friedmand38617c2008-05-14 19:38:39 +0000124 case Builtin::BI__builtin_shufflevector:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000125 return SemaBuiltinShuffleVector(TheCall);
126 // TheCall will be freed by the smart pointer here, but that's fine, since
127 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbar4493f792008-07-21 22:59:13 +0000128 case Builtin::BI__builtin_prefetch:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000129 if (SemaBuiltinPrefetch(TheCall))
130 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000131 break;
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000132 case Builtin::BI__builtin_object_size:
Sebastian Redl0eb23302009-01-19 00:08:26 +0000133 if (SemaBuiltinObjectSize(TheCall))
134 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000135 break;
Eli Friedmand875fed2009-05-03 04:46:36 +0000136 case Builtin::BI__builtin_longjmp:
137 if (SemaBuiltinLongjmp(TheCall))
138 return ExprError();
Anders Carlssond406bf02009-08-16 01:56:34 +0000139 break;
Chris Lattner75c29a02010-10-12 17:47:42 +0000140 case Builtin::BI__builtin_constant_p:
141 if (TheCall->getNumArgs() == 0)
142 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
143 << 0 /*function call*/ << 1 << 0 << TheCall->getSourceRange();
144 if (TheCall->getNumArgs() > 1)
145 return Diag(TheCall->getArg(1)->getLocStart(),
146 diag::err_typecheck_call_too_many_args)
147 << 0 /*function call*/ << 1 << TheCall->getNumArgs()
148 << TheCall->getArg(1)->getSourceRange();
149 break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000150 case Builtin::BI__sync_fetch_and_add:
151 case Builtin::BI__sync_fetch_and_sub:
152 case Builtin::BI__sync_fetch_and_or:
153 case Builtin::BI__sync_fetch_and_and:
154 case Builtin::BI__sync_fetch_and_xor:
155 case Builtin::BI__sync_add_and_fetch:
156 case Builtin::BI__sync_sub_and_fetch:
157 case Builtin::BI__sync_and_and_fetch:
158 case Builtin::BI__sync_or_and_fetch:
159 case Builtin::BI__sync_xor_and_fetch:
160 case Builtin::BI__sync_val_compare_and_swap:
161 case Builtin::BI__sync_bool_compare_and_swap:
162 case Builtin::BI__sync_lock_test_and_set:
163 case Builtin::BI__sync_lock_release:
Chandler Carruthd2014572010-07-09 18:59:35 +0000164 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman26a31422010-06-08 02:47:44 +0000165 }
166
167 // Since the target specific builtins for each arch overlap, only check those
168 // of the arch we are compiling for.
169 if (BuiltinID >= Builtin::FirstTSBuiltin) {
170 switch (Context.Target.getTriple().getArch()) {
171 case llvm::Triple::arm:
172 case llvm::Triple::thumb:
173 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
174 return ExprError();
175 break;
Nate Begeman26a31422010-06-08 02:47:44 +0000176 default:
177 break;
178 }
179 }
180
181 return move(TheCallResult);
182}
183
Nate Begeman61eecf52010-06-14 05:21:25 +0000184// Get the valid immediate range for the specified NEON type code.
185static unsigned RFT(unsigned t, bool shift = false) {
186 bool quad = t & 0x10;
187
188 switch (t & 0x7) {
189 case 0: // i8
Nate Begemand69ec162010-06-17 02:26:59 +0000190 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000191 case 1: // i16
Nate Begemand69ec162010-06-17 02:26:59 +0000192 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000193 case 2: // i32
Nate Begemand69ec162010-06-17 02:26:59 +0000194 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000195 case 3: // i64
Nate Begemand69ec162010-06-17 02:26:59 +0000196 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000197 case 4: // f32
198 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000199 return (2 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000200 case 5: // poly8
Bob Wilson42499f92010-12-10 19:45:06 +0000201 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000202 case 6: // poly16
Bob Wilson42499f92010-12-10 19:45:06 +0000203 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000204 case 7: // float16
205 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000206 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000207 }
208 return 0;
209}
210
Nate Begeman26a31422010-06-08 02:47:44 +0000211bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000212 llvm::APSInt Result;
213
Nate Begeman0d15c532010-06-13 04:47:52 +0000214 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000215 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000216 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000217#define GET_NEON_OVERLOAD_CHECK
218#include "clang/Basic/arm_neon.inc"
219#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000220 }
221
Nate Begeman0d15c532010-06-13 04:47:52 +0000222 // For NEON intrinsics which are overloaded on vector element type, validate
223 // the immediate which specifies which variant to emit.
224 if (mask) {
225 unsigned ArgNo = TheCall->getNumArgs()-1;
226 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
227 return true;
228
Nate Begeman61eecf52010-06-14 05:21:25 +0000229 TV = Result.getLimitedValue(32);
230 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000231 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
232 << TheCall->getArg(ArgNo)->getSourceRange();
233 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000234
Nate Begeman0d15c532010-06-13 04:47:52 +0000235 // For NEON intrinsics which take an immediate value as part of the
236 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000237 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000238 switch (BuiltinID) {
239 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000240 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
241 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000242 case ARM::BI__builtin_arm_vcvtr_f:
243 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000244#define GET_NEON_IMMEDIATE_CHECK
245#include "clang/Basic/arm_neon.inc"
246#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000247 };
248
Nate Begeman61eecf52010-06-14 05:21:25 +0000249 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000250 if (SemaBuiltinConstantArg(TheCall, i, Result))
251 return true;
252
Nate Begeman61eecf52010-06-14 05:21:25 +0000253 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000254 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000255 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000256 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000257 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000258
Nate Begeman99c40bb2010-08-03 21:32:34 +0000259 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000260 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000261}
Daniel Dunbarde454282008-10-02 18:44:07 +0000262
Anders Carlssond406bf02009-08-16 01:56:34 +0000263/// CheckFunctionCall - Check a direct function call for various correctness
264/// and safety properties not strictly enforced by the C type system.
265bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
266 // Get the IdentifierInfo* for the called function.
267 IdentifierInfo *FnInfo = FDecl->getIdentifier();
268
269 // None of the checks below are needed for functions that don't have
270 // simple names (e.g., C++ conversion functions).
271 if (!FnInfo)
272 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000273
Daniel Dunbarde454282008-10-02 18:44:07 +0000274 // FIXME: This mechanism should be abstracted to be less fragile and
275 // more efficient. For example, just map function ids to custom
276 // handlers.
277
Ted Kremenekc82faca2010-09-09 04:33:05 +0000278 // Printf and scanf checking.
279 for (specific_attr_iterator<FormatAttr>
280 i = FDecl->specific_attr_begin<FormatAttr>(),
281 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
282
283 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000284 const bool b = Format->getType() == "scanf";
285 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000286 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000287 CheckPrintfScanfArguments(TheCall, HasVAListArg,
288 Format->getFormatIdx() - 1,
289 HasVAListArg ? 0 : Format->getFirstArg() - 1,
290 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000291 }
Chris Lattner59907c42007-08-10 20:18:51 +0000292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Ted Kremenekc82faca2010-09-09 04:33:05 +0000294 for (specific_attr_iterator<NonNullAttr>
295 i = FDecl->specific_attr_begin<NonNullAttr>(),
296 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Sean Huntcf807c42010-08-18 23:23:40 +0000297 CheckNonNullArguments(*i, TheCall);
Ted Kremenekc82faca2010-09-09 04:33:05 +0000298 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000299
Anders Carlssond406bf02009-08-16 01:56:34 +0000300 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000301}
302
Anders Carlssond406bf02009-08-16 01:56:34 +0000303bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000304 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000305 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000306 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000307 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000309 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
310 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000311 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000313 QualType Ty = V->getType();
314 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000315 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000316
Ted Kremenek826a3452010-07-16 02:11:22 +0000317 const bool b = Format->getType() == "scanf";
318 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000319 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000320
Anders Carlssond406bf02009-08-16 01:56:34 +0000321 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000322 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
323 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000324
325 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000326}
327
Chris Lattner5caa3702009-05-08 06:58:22 +0000328/// SemaBuiltinAtomicOverloaded - We have a call to a function like
329/// __sync_fetch_and_add, which is an overloaded function based on the pointer
330/// type of its first argument. The main ActOnCallExpr routines have already
331/// promoted the types of arguments because all of these calls are prototyped as
332/// void(...).
333///
334/// This function goes through and does final semantic checking for these
335/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000336ExprResult
337Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000338 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000339 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
340 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
341
342 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000343 if (TheCall->getNumArgs() < 1) {
344 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
345 << 0 << 1 << TheCall->getNumArgs()
346 << TheCall->getCallee()->getSourceRange();
347 return ExprError();
348 }
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Chris Lattner5caa3702009-05-08 06:58:22 +0000350 // Inspect the first argument of the atomic builtin. This should always be
351 // a pointer type, whose element is an integral scalar or pointer type.
352 // Because it is a pointer type, we don't have to worry about any implicit
353 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000354 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000355 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000356 if (!FirstArg->getType()->isPointerType()) {
357 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
358 << FirstArg->getType() << FirstArg->getSourceRange();
359 return ExprError();
360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Chandler Carruthd2014572010-07-09 18:59:35 +0000362 QualType ValType =
363 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000364 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000365 !ValType->isBlockPointerType()) {
366 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
367 << FirstArg->getType() << FirstArg->getSourceRange();
368 return ExprError();
369 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000370
Chandler Carruth8d13d222010-07-18 20:54:12 +0000371 // The majority of builtins return a value, but a few have special return
372 // types, so allow them to override appropriately below.
373 QualType ResultType = ValType;
374
Chris Lattner5caa3702009-05-08 06:58:22 +0000375 // We need to figure out which concrete builtin this maps onto. For example,
376 // __sync_fetch_and_add with a 2 byte object turns into
377 // __sync_fetch_and_add_2.
378#define BUILTIN_ROW(x) \
379 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
380 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Chris Lattner5caa3702009-05-08 06:58:22 +0000382 static const unsigned BuiltinIndices[][5] = {
383 BUILTIN_ROW(__sync_fetch_and_add),
384 BUILTIN_ROW(__sync_fetch_and_sub),
385 BUILTIN_ROW(__sync_fetch_and_or),
386 BUILTIN_ROW(__sync_fetch_and_and),
387 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Chris Lattner5caa3702009-05-08 06:58:22 +0000389 BUILTIN_ROW(__sync_add_and_fetch),
390 BUILTIN_ROW(__sync_sub_and_fetch),
391 BUILTIN_ROW(__sync_and_and_fetch),
392 BUILTIN_ROW(__sync_or_and_fetch),
393 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner5caa3702009-05-08 06:58:22 +0000395 BUILTIN_ROW(__sync_val_compare_and_swap),
396 BUILTIN_ROW(__sync_bool_compare_and_swap),
397 BUILTIN_ROW(__sync_lock_test_and_set),
398 BUILTIN_ROW(__sync_lock_release)
399 };
Mike Stump1eb44332009-09-09 15:08:12 +0000400#undef BUILTIN_ROW
401
Chris Lattner5caa3702009-05-08 06:58:22 +0000402 // Determine the index of the size.
403 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000404 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000405 case 1: SizeIndex = 0; break;
406 case 2: SizeIndex = 1; break;
407 case 4: SizeIndex = 2; break;
408 case 8: SizeIndex = 3; break;
409 case 16: SizeIndex = 4; break;
410 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000411 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
412 << FirstArg->getType() << FirstArg->getSourceRange();
413 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000414 }
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 // Each of these builtins has one pointer argument, followed by some number of
417 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
418 // that we ignore. Find out which row of BuiltinIndices to read from as well
419 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000420 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000421 unsigned BuiltinIndex, NumFixed = 1;
422 switch (BuiltinID) {
423 default: assert(0 && "Unknown overloaded atomic builtin!");
424 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
425 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
426 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
427 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
428 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000429
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000430 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
431 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
432 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
433 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
434 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Chris Lattner5caa3702009-05-08 06:58:22 +0000436 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000437 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000438 NumFixed = 2;
439 break;
440 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000441 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000442 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000443 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000445 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000446 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000447 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000448 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000449 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000450 break;
451 }
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattner5caa3702009-05-08 06:58:22 +0000453 // Now that we know how many fixed arguments we expect, first check that we
454 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000455 if (TheCall->getNumArgs() < 1+NumFixed) {
456 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
457 << 0 << 1+NumFixed << TheCall->getNumArgs()
458 << TheCall->getCallee()->getSourceRange();
459 return ExprError();
460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000462 // Get the decl for the concrete builtin from this, we can tell what the
463 // concrete integer type we should convert to is.
464 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
465 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
466 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000467 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000468 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
469 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000470
John McCallf871d0c2010-08-07 06:22:56 +0000471 // The first argument --- the pointer --- has a fixed type; we
472 // deduce the types of the rest of the arguments accordingly. Walk
473 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000474 for (unsigned i = 0; i != NumFixed; ++i) {
475 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Chris Lattner5caa3702009-05-08 06:58:22 +0000477 // If the argument is an implicit cast, then there was a promotion due to
478 // "...", just remove it now.
479 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
480 Arg = ICE->getSubExpr();
481 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000482 TheCall->setArg(i+1, Arg);
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Chris Lattner5caa3702009-05-08 06:58:22 +0000485 // GCC does an implicit conversion to the pointer or integer ValType. This
486 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000487 CastKind Kind = CK_Invalid;
John McCallf89e55a2010-11-18 06:31:45 +0000488 ExprValueKind VK = VK_RValue;
John McCallf871d0c2010-08-07 06:22:56 +0000489 CXXCastPath BasePath;
John McCallf89e55a2010-11-18 06:31:45 +0000490 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000491 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Chris Lattner5caa3702009-05-08 06:58:22 +0000493 // Okay, we have something that *can* be converted to the right type. Check
494 // to see if there is a potentially weird extension going on here. This can
495 // happen when you do an atomic operation on something like an char* and
496 // pass in 42. The 42 gets converted to char. This is even more strange
497 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000498 // FIXME: Do this check.
John McCallf89e55a2010-11-18 06:31:45 +0000499 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000500 TheCall->setArg(i+1, Arg);
501 }
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Chris Lattner5caa3702009-05-08 06:58:22 +0000503 // Switch the DeclRefExpr to refer to the new decl.
504 DRE->setDecl(NewBuiltinDecl);
505 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Chris Lattner5caa3702009-05-08 06:58:22 +0000507 // Set the callee in the CallExpr.
508 // FIXME: This leaks the original parens and implicit casts.
509 Expr *PromotedCall = DRE;
510 UsualUnaryConversions(PromotedCall);
511 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000513 // Change the result type of the call to match the original value type. This
514 // is arbitrary, but the codegen for these builtins ins design to handle it
515 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000516 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000517
518 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000519}
520
521
Chris Lattner69039812009-02-18 06:01:06 +0000522/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000523/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000524/// Note: It might also make sense to do the UTF-16 conversion here (would
525/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000526bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000527 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000528 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
529
530 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000531 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
532 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000533 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000536 size_t NulPos = Literal->getString().find('\0');
537 if (NulPos != llvm::StringRef::npos) {
538 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
539 diag::warn_cfstring_literal_contains_nul_character)
540 << Arg->getSourceRange();
Daniel Dunbarf015b032009-09-22 10:03:52 +0000541 }
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000542 if (Literal->containsNonAsciiOrNull()) {
543 llvm::StringRef String = Literal->getString();
544 unsigned NumBytes = String.size();
545 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
546 const UTF8 *FromPtr = (UTF8 *)String.data();
547 UTF16 *ToPtr = &ToBuf[0];
548
549 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
550 &ToPtr, ToPtr + NumBytes,
551 strictConversion);
552 // Check for conversion failure.
553 if (Result != conversionOK)
554 Diag(Arg->getLocStart(),
555 diag::warn_cfstring_truncated) << Arg->getSourceRange();
556 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000557 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000558}
559
Chris Lattnerc27c6652007-12-20 00:05:45 +0000560/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
561/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000562bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
563 Expr *Fn = TheCall->getCallee();
564 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000565 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000566 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000567 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
568 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000569 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000570 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000571 return true;
572 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000573
574 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000575 return Diag(TheCall->getLocEnd(),
576 diag::err_typecheck_call_too_few_args_at_least)
577 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000578 }
579
Chris Lattnerc27c6652007-12-20 00:05:45 +0000580 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000581 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000582 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000583 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000584 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000585 else if (FunctionDecl *FD = getCurFunctionDecl())
586 isVariadic = FD->isVariadic();
587 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000588 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000589
Chris Lattnerc27c6652007-12-20 00:05:45 +0000590 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000591 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
592 return true;
593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Chris Lattner30ce3442007-12-19 23:59:04 +0000595 // Verify that the second argument to the builtin is the last argument of the
596 // current function or method.
597 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000598 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Anders Carlsson88cf2262008-02-11 04:20:54 +0000600 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
601 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000602 // FIXME: This isn't correct for methods (results in bogus warning).
603 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000604 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000605 if (CurBlock)
606 LastArg = *(CurBlock->TheDecl->param_end()-1);
607 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000608 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000609 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000610 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000611 SecondArgIsLastNamedArgument = PV == LastArg;
612 }
613 }
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Chris Lattner30ce3442007-12-19 23:59:04 +0000615 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000616 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000617 diag::warn_second_parameter_of_va_start_not_last_named_argument);
618 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000619}
Chris Lattner30ce3442007-12-19 23:59:04 +0000620
Chris Lattner1b9a0792007-12-20 00:26:33 +0000621/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
622/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000623bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
624 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000625 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000626 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000627 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000628 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000629 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000630 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000631 << SourceRange(TheCall->getArg(2)->getLocStart(),
632 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000633
Chris Lattner925e60d2007-12-28 05:29:59 +0000634 Expr *OrigArg0 = TheCall->getArg(0);
635 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000636
Chris Lattner1b9a0792007-12-20 00:26:33 +0000637 // Do standard promotions between the two arguments, returning their common
638 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000639 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000640
641 // Make sure any conversions are pushed back into the call; this is
642 // type safe since unordered compare builtins are declared as "_Bool
643 // foo(...)".
644 TheCall->setArg(0, OrigArg0);
645 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000646
Douglas Gregorcde01732009-05-19 22:10:17 +0000647 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
648 return false;
649
Chris Lattner1b9a0792007-12-20 00:26:33 +0000650 // If the common type isn't a real floating type, then the arguments were
651 // invalid for this operation.
652 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000653 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000654 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000655 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000656 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000657
Chris Lattner1b9a0792007-12-20 00:26:33 +0000658 return false;
659}
660
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000661/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
662/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000663/// to check everything. We expect the last argument to be a floating point
664/// value.
665bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
666 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000667 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000668 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000669 if (TheCall->getNumArgs() > NumArgs)
670 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000671 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000672 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000673 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000674 (*(TheCall->arg_end()-1))->getLocEnd());
675
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000676 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000677
Eli Friedman9ac6f622009-08-31 20:06:00 +0000678 if (OrigArg->isTypeDependent())
679 return false;
680
Chris Lattner81368fb2010-05-06 05:50:07 +0000681 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000682 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000683 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000684 diag::err_typecheck_call_invalid_unary_fp)
685 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000686
Chris Lattner81368fb2010-05-06 05:50:07 +0000687 // If this is an implicit conversion from float -> double, remove it.
688 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
689 Expr *CastArg = Cast->getSubExpr();
690 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
691 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
692 "promotion from float to double is the only expected cast here");
693 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000694 TheCall->setArg(NumArgs-1, CastArg);
695 OrigArg = CastArg;
696 }
697 }
698
Eli Friedman9ac6f622009-08-31 20:06:00 +0000699 return false;
700}
701
Eli Friedmand38617c2008-05-14 19:38:39 +0000702/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
703// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000704ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000705 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000706 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000707 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000708 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000709 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000710
Nate Begeman37b6a572010-06-08 00:16:34 +0000711 // Determine which of the following types of shufflevector we're checking:
712 // 1) unary, vector mask: (lhs, mask)
713 // 2) binary, vector mask: (lhs, rhs, mask)
714 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
715 QualType resType = TheCall->getArg(0)->getType();
716 unsigned numElements = 0;
717
Douglas Gregorcde01732009-05-19 22:10:17 +0000718 if (!TheCall->getArg(0)->isTypeDependent() &&
719 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000720 QualType LHSType = TheCall->getArg(0)->getType();
721 QualType RHSType = TheCall->getArg(1)->getType();
722
723 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000724 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000725 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000726 TheCall->getArg(1)->getLocEnd());
727 return ExprError();
728 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000729
730 numElements = LHSType->getAs<VectorType>()->getNumElements();
731 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Nate Begeman37b6a572010-06-08 00:16:34 +0000733 // Check to see if we have a call with 2 vector arguments, the unary shuffle
734 // with mask. If so, verify that RHS is an integer vector type with the
735 // same number of elts as lhs.
736 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000737 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000738 RHSType->getAs<VectorType>()->getNumElements() != numElements)
739 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
740 << SourceRange(TheCall->getArg(1)->getLocStart(),
741 TheCall->getArg(1)->getLocEnd());
742 numResElements = numElements;
743 }
744 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000745 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000746 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000747 TheCall->getArg(1)->getLocEnd());
748 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000749 } else if (numElements != numResElements) {
750 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000751 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000752 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000753 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000754 }
755
756 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000757 if (TheCall->getArg(i)->isTypeDependent() ||
758 TheCall->getArg(i)->isValueDependent())
759 continue;
760
Nate Begeman37b6a572010-06-08 00:16:34 +0000761 llvm::APSInt Result(32);
762 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
763 return ExprError(Diag(TheCall->getLocStart(),
764 diag::err_shufflevector_nonconstant_argument)
765 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000766
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000767 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000768 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000769 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000770 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000771 }
772
773 llvm::SmallVector<Expr*, 32> exprs;
774
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000775 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000776 exprs.push_back(TheCall->getArg(i));
777 TheCall->setArg(i, 0);
778 }
779
Nate Begemana88dc302009-08-12 02:10:25 +0000780 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000781 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000782 TheCall->getCallee()->getLocStart(),
783 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000784}
Chris Lattner30ce3442007-12-19 23:59:04 +0000785
Daniel Dunbar4493f792008-07-21 22:59:13 +0000786/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
787// This is declared to take (const void*, ...) and can take two
788// optional constant int args.
789bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000790 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000791
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000792 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000793 return Diag(TheCall->getLocEnd(),
794 diag::err_typecheck_call_too_many_args_at_most)
795 << 0 /*function call*/ << 3 << NumArgs
796 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000797
798 // Argument 0 is checked for us and the remaining arguments must be
799 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000800 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000801 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000802
Eli Friedman9aef7262009-12-04 00:30:06 +0000803 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000804 if (SemaBuiltinConstantArg(TheCall, i, Result))
805 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Daniel Dunbar4493f792008-07-21 22:59:13 +0000807 // FIXME: gcc issues a warning and rewrites these to 0. These
808 // seems especially odd for the third argument since the default
809 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000810 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000811 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000812 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000813 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000814 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000815 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000816 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000817 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000818 }
819 }
820
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000821 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000822}
823
Eric Christopher691ebc32010-04-17 02:26:23 +0000824/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
825/// TheCall is a constant expression.
826bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
827 llvm::APSInt &Result) {
828 Expr *Arg = TheCall->getArg(ArgNum);
829 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
830 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
831
832 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
833
834 if (!Arg->isIntegerConstantExpr(Result, Context))
835 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000836 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000837
Chris Lattner21fb98e2009-09-23 06:06:36 +0000838 return false;
839}
840
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000841/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
842/// int type). This simply type checks that type is one of the defined
843/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000844// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000845bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000846 llvm::APSInt Result;
847
848 // Check constant-ness first.
849 if (SemaBuiltinConstantArg(TheCall, 1, Result))
850 return true;
851
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000852 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000853 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000854 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
855 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000856 }
857
858 return false;
859}
860
Eli Friedman586d6a82009-05-03 06:04:26 +0000861/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000862/// This checks that val is a constant 1.
863bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
864 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000865 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000866
Eric Christopher691ebc32010-04-17 02:26:23 +0000867 // TODO: This is less than ideal. Overload this to take a value.
868 if (SemaBuiltinConstantArg(TheCall, 1, Result))
869 return true;
870
871 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000872 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
873 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
874
875 return false;
876}
877
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000878// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenek082d9362009-03-20 21:35:28 +0000879bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
880 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000881 unsigned format_idx, unsigned firstDataArg,
882 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000883 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000884 if (E->isTypeDependent() || E->isValueDependent())
885 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000886
887 switch (E->getStmtClass()) {
John McCall56ca35d2011-02-17 10:25:35 +0000888 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenekd30ef872009-01-12 23:09:09 +0000889 case Stmt::ConditionalOperatorClass: {
John McCall56ca35d2011-02-17 10:25:35 +0000890 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000891 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
892 format_idx, firstDataArg, isPrintf)
John McCall56ca35d2011-02-17 10:25:35 +0000893 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000894 format_idx, firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000895 }
896
Ted Kremenek95355bb2010-09-09 03:51:42 +0000897 case Stmt::IntegerLiteralClass:
898 // Technically -Wformat-nonliteral does not warn about this case.
899 // The behavior of printf and friends in this case is implementation
900 // dependent. Ideally if the format string cannot be null then
901 // it should have a 'nonnull' attribute in the function prototype.
902 return true;
903
Ted Kremenekd30ef872009-01-12 23:09:09 +0000904 case Stmt::ImplicitCastExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000905 E = cast<ImplicitCastExpr>(E)->getSubExpr();
906 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000907 }
908
909 case Stmt::ParenExprClass: {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000910 E = cast<ParenExpr>(E)->getSubExpr();
911 goto tryAgain;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
John McCall56ca35d2011-02-17 10:25:35 +0000914 case Stmt::OpaqueValueExprClass:
915 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
916 E = src;
917 goto tryAgain;
918 }
919 return false;
920
Ted Kremenekb43e8ad2011-02-24 23:03:04 +0000921 case Stmt::PredefinedExprClass:
922 // While __func__, etc., are technically not string literals, they
923 // cannot contain format specifiers and thus are not a security
924 // liability.
925 return true;
926
Ted Kremenek082d9362009-03-20 21:35:28 +0000927 case Stmt::DeclRefExprClass: {
928 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Ted Kremenek082d9362009-03-20 21:35:28 +0000930 // As an exception, do not flag errors for variables binding to
931 // const string literals.
932 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
933 bool isConstant = false;
934 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000935
Ted Kremenek082d9362009-03-20 21:35:28 +0000936 if (const ArrayType *AT = Context.getAsArrayType(T)) {
937 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000938 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000939 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000940 PT->getPointeeType().isConstant(Context);
941 }
Mike Stump1eb44332009-09-09 15:08:12 +0000942
Ted Kremenek082d9362009-03-20 21:35:28 +0000943 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000944 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000945 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000946 HasVAListArg, format_idx, firstDataArg,
947 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000948 }
Mike Stump1eb44332009-09-09 15:08:12 +0000949
Anders Carlssond966a552009-06-28 19:55:58 +0000950 // For vprintf* functions (i.e., HasVAListArg==true), we add a
951 // special check to see if the format string is a function parameter
952 // of the function calling the printf function. If the function
953 // has an attribute indicating it is a printf-like function, then we
954 // should suppress warnings concerning non-literals being used in a call
955 // to a vprintf function. For example:
956 //
957 // void
958 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
959 // va_list ap;
960 // va_start(ap, fmt);
961 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
962 // ...
963 //
964 //
965 // FIXME: We don't have full attribute support yet, so just check to see
966 // if the argument is a DeclRefExpr that references a parameter. We'll
967 // add proper support for checking the attribute later.
968 if (HasVAListArg)
969 if (isa<ParmVarDecl>(VD))
970 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000971 }
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Ted Kremenek082d9362009-03-20 21:35:28 +0000973 return false;
974 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000975
Anders Carlsson8f031b32009-06-27 04:05:33 +0000976 case Stmt::CallExprClass: {
977 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000978 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000979 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
980 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
981 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000982 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000983 unsigned ArgIndex = FA->getFormatIdx();
984 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000985
986 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000987 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +0000988 }
989 }
990 }
991 }
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Anders Carlsson8f031b32009-06-27 04:05:33 +0000993 return false;
994 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000995 case Stmt::ObjCStringLiteralClass:
996 case Stmt::StringLiteralClass: {
997 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Ted Kremenek082d9362009-03-20 21:35:28 +0000999 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +00001000 StrE = ObjCFExpr->getString();
1001 else
Ted Kremenek082d9362009-03-20 21:35:28 +00001002 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Ted Kremenekd30ef872009-01-12 23:09:09 +00001004 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001005 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1006 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001007 return true;
1008 }
Mike Stump1eb44332009-09-09 15:08:12 +00001009
Ted Kremenekd30ef872009-01-12 23:09:09 +00001010 return false;
1011 }
Mike Stump1eb44332009-09-09 15:08:12 +00001012
Ted Kremenek082d9362009-03-20 21:35:28 +00001013 default:
1014 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001015 }
1016}
1017
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001018void
Mike Stump1eb44332009-09-09 15:08:12 +00001019Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1020 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001021 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1022 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001023 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001024 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001025 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001026 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001027 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1028 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001029 }
1030}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001031
Ted Kremenek826a3452010-07-16 02:11:22 +00001032/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1033/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001034void
Ted Kremenek826a3452010-07-16 02:11:22 +00001035Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1036 unsigned format_idx, unsigned firstDataArg,
1037 bool isPrintf) {
1038
Ted Kremenek082d9362009-03-20 21:35:28 +00001039 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001040
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001041 // The way the format attribute works in GCC, the implicit this argument
1042 // of member functions is counted. However, it doesn't appear in our own
1043 // lists, so decrement format_idx in that case.
1044 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001045 const CXXMethodDecl *method_decl =
1046 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1047 if (method_decl && method_decl->isInstance()) {
1048 // Catch a format attribute mistakenly referring to the object argument.
1049 if (format_idx == 0)
1050 return;
1051 --format_idx;
1052 if(firstDataArg != 0)
1053 --firstDataArg;
1054 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001055 }
1056
Ted Kremenek826a3452010-07-16 02:11:22 +00001057 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001058 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001059 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001060 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001061 return;
1062 }
Mike Stump1eb44332009-09-09 15:08:12 +00001063
Ted Kremenek082d9362009-03-20 21:35:28 +00001064 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Chris Lattner59907c42007-08-10 20:18:51 +00001066 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001067 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001068 // Dynamically generated format strings are difficult to
1069 // automatically vet at compile time. Requiring that format strings
1070 // are string literals: (1) permits the checking of format strings by
1071 // the compiler and thereby (2) can practically remove the source of
1072 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001073
Mike Stump1eb44332009-09-09 15:08:12 +00001074 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001075 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001076 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001077 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001078 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001079 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001080 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001081
Chris Lattner655f1412009-04-29 04:59:47 +00001082 // If there are no arguments specified, warn with -Wformat-security, otherwise
1083 // warn only with -Wformat-nonliteral.
1084 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001085 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001086 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001087 << OrigFormatExpr->getSourceRange();
1088 else
Mike Stump1eb44332009-09-09 15:08:12 +00001089 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001090 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001091 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001092}
Ted Kremenek71895b92007-08-14 17:39:48 +00001093
Ted Kremeneke0e53132010-01-28 23:39:18 +00001094namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001095class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1096protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001097 Sema &S;
1098 const StringLiteral *FExpr;
1099 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001100 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001101 const unsigned NumDataArgs;
1102 const bool IsObjCLiteral;
1103 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001104 const bool HasVAListArg;
1105 const CallExpr *TheCall;
1106 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001107 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001108 bool usesPositionalArgs;
1109 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001110public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001111 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001112 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001113 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001114 const char *beg, bool hasVAListArg,
1115 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001116 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001117 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001118 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001119 IsObjCLiteral(isObjCLiteral), Beg(beg),
1120 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001121 TheCall(theCall), FormatIdx(formatIdx),
1122 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001123 CoveredArgs.resize(numDataArgs);
1124 CoveredArgs.reset();
1125 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001126
Ted Kremenek07d161f2010-01-29 01:50:07 +00001127 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001128
Ted Kremenek826a3452010-07-16 02:11:22 +00001129 void HandleIncompleteSpecifier(const char *startSpecifier,
1130 unsigned specifierLen);
1131
Ted Kremenekefaff192010-02-27 01:41:03 +00001132 virtual void HandleInvalidPosition(const char *startSpecifier,
1133 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001134 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001135
1136 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1137
Ted Kremeneke0e53132010-01-28 23:39:18 +00001138 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001139
Ted Kremenek826a3452010-07-16 02:11:22 +00001140protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001141 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1142 const char *startSpec,
1143 unsigned specifierLen,
1144 const char *csStart, unsigned csLen);
1145
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001146 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001147 CharSourceRange getSpecifierRange(const char *startSpecifier,
1148 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001149 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001150
Ted Kremenek0d277352010-01-29 01:06:55 +00001151 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001152
1153 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1154 const analyze_format_string::ConversionSpecifier &CS,
1155 const char *startSpecifier, unsigned specifierLen,
1156 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001157};
1158}
1159
Ted Kremenek826a3452010-07-16 02:11:22 +00001160SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001161 return OrigFormatExpr->getSourceRange();
1162}
1163
Ted Kremenek826a3452010-07-16 02:11:22 +00001164CharSourceRange CheckFormatHandler::
1165getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001166 SourceLocation Start = getLocationOfByte(startSpecifier);
1167 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1168
1169 // Advance the end SourceLocation by one due to half-open ranges.
1170 End = End.getFileLocWithOffset(1);
1171
1172 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001173}
1174
Ted Kremenek826a3452010-07-16 02:11:22 +00001175SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001176 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001177}
1178
Ted Kremenek826a3452010-07-16 02:11:22 +00001179void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1180 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001181 SourceLocation Loc = getLocationOfByte(startSpecifier);
1182 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001183 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001184}
1185
Ted Kremenekefaff192010-02-27 01:41:03 +00001186void
Ted Kremenek826a3452010-07-16 02:11:22 +00001187CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1188 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001189 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001190 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1191 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001192}
1193
Ted Kremenek826a3452010-07-16 02:11:22 +00001194void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001195 unsigned posLen) {
1196 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001197 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1198 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001199}
1200
Ted Kremenek826a3452010-07-16 02:11:22 +00001201void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1202 // The presence of a null character is likely an error.
1203 S.Diag(getLocationOfByte(nullCharacter),
1204 diag::warn_printf_format_string_contains_null_char)
1205 << getFormatStringRange();
1206}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001207
Ted Kremenek826a3452010-07-16 02:11:22 +00001208const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1209 return TheCall->getArg(FirstDataArg + i);
1210}
1211
1212void CheckFormatHandler::DoneProcessing() {
1213 // Does the number of data arguments exceed the number of
1214 // format conversions in the format string?
1215 if (!HasVAListArg) {
1216 // Find any arguments that weren't covered.
1217 CoveredArgs.flip();
1218 signed notCoveredArg = CoveredArgs.find_first();
1219 if (notCoveredArg >= 0) {
1220 assert((unsigned)notCoveredArg < NumDataArgs);
1221 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1222 diag::warn_printf_data_arg_not_used)
1223 << getFormatStringRange();
1224 }
1225 }
1226}
1227
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001228bool
1229CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1230 SourceLocation Loc,
1231 const char *startSpec,
1232 unsigned specifierLen,
1233 const char *csStart,
1234 unsigned csLen) {
1235
1236 bool keepGoing = true;
1237 if (argIndex < NumDataArgs) {
1238 // Consider the argument coverered, even though the specifier doesn't
1239 // make sense.
1240 CoveredArgs.set(argIndex);
1241 }
1242 else {
1243 // If argIndex exceeds the number of data arguments we
1244 // don't issue a warning because that is just a cascade of warnings (and
1245 // they may have intended '%%' anyway). We don't want to continue processing
1246 // the format string after this point, however, as we will like just get
1247 // gibberish when trying to match arguments.
1248 keepGoing = false;
1249 }
1250
1251 S.Diag(Loc, diag::warn_format_invalid_conversion)
1252 << llvm::StringRef(csStart, csLen)
1253 << getSpecifierRange(startSpec, specifierLen);
1254
1255 return keepGoing;
1256}
1257
Ted Kremenek666a1972010-07-26 19:45:42 +00001258bool
1259CheckFormatHandler::CheckNumArgs(
1260 const analyze_format_string::FormatSpecifier &FS,
1261 const analyze_format_string::ConversionSpecifier &CS,
1262 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1263
1264 if (argIndex >= NumDataArgs) {
1265 if (FS.usesPositionalArg()) {
1266 S.Diag(getLocationOfByte(CS.getStart()),
1267 diag::warn_printf_positional_arg_exceeds_data_args)
1268 << (argIndex+1) << NumDataArgs
1269 << getSpecifierRange(startSpecifier, specifierLen);
1270 }
1271 else {
1272 S.Diag(getLocationOfByte(CS.getStart()),
1273 diag::warn_printf_insufficient_data_args)
1274 << getSpecifierRange(startSpecifier, specifierLen);
1275 }
1276
1277 return false;
1278 }
1279 return true;
1280}
1281
Ted Kremenek826a3452010-07-16 02:11:22 +00001282//===--- CHECK: Printf format string checking ------------------------------===//
1283
1284namespace {
1285class CheckPrintfHandler : public CheckFormatHandler {
1286public:
1287 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1288 const Expr *origFormatExpr, unsigned firstDataArg,
1289 unsigned numDataArgs, bool isObjCLiteral,
1290 const char *beg, bool hasVAListArg,
1291 const CallExpr *theCall, unsigned formatIdx)
1292 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1293 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1294 theCall, formatIdx) {}
1295
1296
1297 bool HandleInvalidPrintfConversionSpecifier(
1298 const analyze_printf::PrintfSpecifier &FS,
1299 const char *startSpecifier,
1300 unsigned specifierLen);
1301
1302 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1303 const char *startSpecifier,
1304 unsigned specifierLen);
1305
1306 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1307 const char *startSpecifier, unsigned specifierLen);
1308 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1309 const analyze_printf::OptionalAmount &Amt,
1310 unsigned type,
1311 const char *startSpecifier, unsigned specifierLen);
1312 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1313 const analyze_printf::OptionalFlag &flag,
1314 const char *startSpecifier, unsigned specifierLen);
1315 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1316 const analyze_printf::OptionalFlag &ignoredFlag,
1317 const analyze_printf::OptionalFlag &flag,
1318 const char *startSpecifier, unsigned specifierLen);
1319};
1320}
1321
1322bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1323 const analyze_printf::PrintfSpecifier &FS,
1324 const char *startSpecifier,
1325 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001326 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001327 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001328
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001329 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1330 getLocationOfByte(CS.getStart()),
1331 startSpecifier, specifierLen,
1332 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001333}
1334
Ted Kremenek826a3452010-07-16 02:11:22 +00001335bool CheckPrintfHandler::HandleAmount(
1336 const analyze_format_string::OptionalAmount &Amt,
1337 unsigned k, const char *startSpecifier,
1338 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001339
1340 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001341 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001342 unsigned argIndex = Amt.getArgIndex();
1343 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001344 S.Diag(getLocationOfByte(Amt.getStart()),
1345 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001346 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001347 // Don't do any more checking. We will just emit
1348 // spurious errors.
1349 return false;
1350 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001351
Ted Kremenek0d277352010-01-29 01:06:55 +00001352 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001353 // Although not in conformance with C99, we also allow the argument to be
1354 // an 'unsigned int' as that is a reasonably safe case. GCC also
1355 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001356 CoveredArgs.set(argIndex);
1357 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001358 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001359
1360 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1361 assert(ATR.isValid());
1362
1363 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001364 S.Diag(getLocationOfByte(Amt.getStart()),
1365 diag::warn_printf_asterisk_wrong_type)
1366 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001367 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001368 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001369 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001370 // Don't do any more checking. We will just emit
1371 // spurious errors.
1372 return false;
1373 }
1374 }
1375 }
1376 return true;
1377}
Ted Kremenek0d277352010-01-29 01:06:55 +00001378
Tom Caree4ee9662010-06-17 19:00:27 +00001379void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001380 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001381 const analyze_printf::OptionalAmount &Amt,
1382 unsigned type,
1383 const char *startSpecifier,
1384 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001385 const analyze_printf::PrintfConversionSpecifier &CS =
1386 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001387 switch (Amt.getHowSpecified()) {
1388 case analyze_printf::OptionalAmount::Constant:
1389 S.Diag(getLocationOfByte(Amt.getStart()),
1390 diag::warn_printf_nonsensical_optional_amount)
1391 << type
1392 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001393 << getSpecifierRange(startSpecifier, specifierLen)
1394 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001395 Amt.getConstantLength()));
1396 break;
1397
1398 default:
1399 S.Diag(getLocationOfByte(Amt.getStart()),
1400 diag::warn_printf_nonsensical_optional_amount)
1401 << type
1402 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001403 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001404 break;
1405 }
1406}
1407
Ted Kremenek826a3452010-07-16 02:11:22 +00001408void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001409 const analyze_printf::OptionalFlag &flag,
1410 const char *startSpecifier,
1411 unsigned specifierLen) {
1412 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001413 const analyze_printf::PrintfConversionSpecifier &CS =
1414 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001415 S.Diag(getLocationOfByte(flag.getPosition()),
1416 diag::warn_printf_nonsensical_flag)
1417 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001418 << getSpecifierRange(startSpecifier, specifierLen)
1419 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001420}
1421
1422void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001423 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001424 const analyze_printf::OptionalFlag &ignoredFlag,
1425 const analyze_printf::OptionalFlag &flag,
1426 const char *startSpecifier,
1427 unsigned specifierLen) {
1428 // Warn about ignored flag with a fixit removal.
1429 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1430 diag::warn_printf_ignored_flag)
1431 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001432 << getSpecifierRange(startSpecifier, specifierLen)
1433 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001434 ignoredFlag.getPosition(), 1));
1435}
1436
Ted Kremeneke0e53132010-01-28 23:39:18 +00001437bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001438CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001439 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001440 const char *startSpecifier,
1441 unsigned specifierLen) {
1442
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001443 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001444 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001445 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001446
Ted Kremenekbaa40062010-07-19 22:01:06 +00001447 if (FS.consumesDataArgument()) {
1448 if (atFirstArg) {
1449 atFirstArg = false;
1450 usesPositionalArgs = FS.usesPositionalArg();
1451 }
1452 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1453 // Cannot mix-and-match positional and non-positional arguments.
1454 S.Diag(getLocationOfByte(CS.getStart()),
1455 diag::warn_format_mix_positional_nonpositional_args)
1456 << getSpecifierRange(startSpecifier, specifierLen);
1457 return false;
1458 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001459 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001460
Ted Kremenekefaff192010-02-27 01:41:03 +00001461 // First check if the field width, precision, and conversion specifier
1462 // have matching data arguments.
1463 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1464 startSpecifier, specifierLen)) {
1465 return false;
1466 }
1467
1468 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1469 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001470 return false;
1471 }
1472
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001473 if (!CS.consumesDataArgument()) {
1474 // FIXME: Technically specifying a precision or field width here
1475 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001476 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001477 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001478
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001479 // Consume the argument.
1480 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001481 if (argIndex < NumDataArgs) {
1482 // The check to see if the argIndex is valid will come later.
1483 // We set the bit here because we may exit early from this
1484 // function if we encounter some other error.
1485 CoveredArgs.set(argIndex);
1486 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001487
1488 // Check for using an Objective-C specific conversion specifier
1489 // in a non-ObjC literal.
1490 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001491 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1492 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001493 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001494
Tom Caree4ee9662010-06-17 19:00:27 +00001495 // Check for invalid use of field width
1496 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001497 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001498 startSpecifier, specifierLen);
1499 }
1500
1501 // Check for invalid use of precision
1502 if (!FS.hasValidPrecision()) {
1503 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1504 startSpecifier, specifierLen);
1505 }
1506
1507 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001508 if (!FS.hasValidThousandsGroupingPrefix())
1509 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001510 if (!FS.hasValidLeadingZeros())
1511 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1512 if (!FS.hasValidPlusPrefix())
1513 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001514 if (!FS.hasValidSpacePrefix())
1515 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001516 if (!FS.hasValidAlternativeForm())
1517 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1518 if (!FS.hasValidLeftJustified())
1519 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1520
1521 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001522 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1523 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1524 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001525 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1526 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1527 startSpecifier, specifierLen);
1528
1529 // Check the length modifier is valid with the given conversion specifier.
1530 const LengthModifier &LM = FS.getLengthModifier();
1531 if (!FS.hasValidLengthModifier())
1532 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001533 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001534 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001535 << getSpecifierRange(startSpecifier, specifierLen)
1536 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001537 LM.getLength()));
1538
1539 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001540 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001541 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001542 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001543 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001544 // Continue checking the other format specifiers.
1545 return true;
1546 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001547
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001548 // The remaining checks depend on the data arguments.
1549 if (HasVAListArg)
1550 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001551
Ted Kremenek666a1972010-07-26 19:45:42 +00001552 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001553 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001554
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001555 // Now type check the data expression that matches the
1556 // format specifier.
1557 const Expr *Ex = getDataArg(argIndex);
1558 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1559 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1560 // Check if we didn't match because of an implicit cast from a 'char'
1561 // or 'short' to an 'int'. This is done because printf is a varargs
1562 // function.
1563 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001564 if (ICE->getType() == S.Context.IntTy) {
1565 // All further checking is done on the subexpression.
1566 Ex = ICE->getSubExpr();
1567 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001568 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001569 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001570
1571 // We may be able to offer a FixItHint if it is a supported type.
1572 PrintfSpecifier fixedFS = FS;
1573 bool success = fixedFS.fixType(Ex->getType());
1574
1575 if (success) {
1576 // Get the fix string from the fixed format specifier
1577 llvm::SmallString<128> buf;
1578 llvm::raw_svector_ostream os(buf);
1579 fixedFS.toString(os);
1580
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001581 // FIXME: getRepresentativeType() perhaps should return a string
1582 // instead of a QualType to better handle when the representative
1583 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001584 S.Diag(getLocationOfByte(CS.getStart()),
1585 diag::warn_printf_conversion_argument_type_mismatch)
1586 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1587 << getSpecifierRange(startSpecifier, specifierLen)
1588 << Ex->getSourceRange()
1589 << FixItHint::CreateReplacement(
1590 getSpecifierRange(startSpecifier, specifierLen),
1591 os.str());
1592 }
1593 else {
1594 S.Diag(getLocationOfByte(CS.getStart()),
1595 diag::warn_printf_conversion_argument_type_mismatch)
1596 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1597 << getSpecifierRange(startSpecifier, specifierLen)
1598 << Ex->getSourceRange();
1599 }
1600 }
1601
Ted Kremeneke0e53132010-01-28 23:39:18 +00001602 return true;
1603}
1604
Ted Kremenek826a3452010-07-16 02:11:22 +00001605//===--- CHECK: Scanf format string checking ------------------------------===//
1606
1607namespace {
1608class CheckScanfHandler : public CheckFormatHandler {
1609public:
1610 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1611 const Expr *origFormatExpr, unsigned firstDataArg,
1612 unsigned numDataArgs, bool isObjCLiteral,
1613 const char *beg, bool hasVAListArg,
1614 const CallExpr *theCall, unsigned formatIdx)
1615 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1616 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1617 theCall, formatIdx) {}
1618
1619 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1620 const char *startSpecifier,
1621 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001622
1623 bool HandleInvalidScanfConversionSpecifier(
1624 const analyze_scanf::ScanfSpecifier &FS,
1625 const char *startSpecifier,
1626 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001627
1628 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001629};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001630}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001631
Ted Kremenekb7c21012010-07-16 18:28:03 +00001632void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1633 const char *end) {
1634 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1635 << getSpecifierRange(start, end - start);
1636}
1637
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001638bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1639 const analyze_scanf::ScanfSpecifier &FS,
1640 const char *startSpecifier,
1641 unsigned specifierLen) {
1642
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001643 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001644 FS.getConversionSpecifier();
1645
1646 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1647 getLocationOfByte(CS.getStart()),
1648 startSpecifier, specifierLen,
1649 CS.getStart(), CS.getLength());
1650}
1651
Ted Kremenek826a3452010-07-16 02:11:22 +00001652bool CheckScanfHandler::HandleScanfSpecifier(
1653 const analyze_scanf::ScanfSpecifier &FS,
1654 const char *startSpecifier,
1655 unsigned specifierLen) {
1656
1657 using namespace analyze_scanf;
1658 using namespace analyze_format_string;
1659
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001660 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001661
Ted Kremenekbaa40062010-07-19 22:01:06 +00001662 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1663 // be used to decide if we are using positional arguments consistently.
1664 if (FS.consumesDataArgument()) {
1665 if (atFirstArg) {
1666 atFirstArg = false;
1667 usesPositionalArgs = FS.usesPositionalArg();
1668 }
1669 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1670 // Cannot mix-and-match positional and non-positional arguments.
1671 S.Diag(getLocationOfByte(CS.getStart()),
1672 diag::warn_format_mix_positional_nonpositional_args)
1673 << getSpecifierRange(startSpecifier, specifierLen);
1674 return false;
1675 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001676 }
1677
1678 // Check if the field with is non-zero.
1679 const OptionalAmount &Amt = FS.getFieldWidth();
1680 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1681 if (Amt.getConstantAmount() == 0) {
1682 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1683 Amt.getConstantLength());
1684 S.Diag(getLocationOfByte(Amt.getStart()),
1685 diag::warn_scanf_nonzero_width)
1686 << R << FixItHint::CreateRemoval(R);
1687 }
1688 }
1689
1690 if (!FS.consumesDataArgument()) {
1691 // FIXME: Technically specifying a precision or field width here
1692 // makes no sense. Worth issuing a warning at some point.
1693 return true;
1694 }
1695
1696 // Consume the argument.
1697 unsigned argIndex = FS.getArgIndex();
1698 if (argIndex < NumDataArgs) {
1699 // The check to see if the argIndex is valid will come later.
1700 // We set the bit here because we may exit early from this
1701 // function if we encounter some other error.
1702 CoveredArgs.set(argIndex);
1703 }
1704
Ted Kremenek1e51c202010-07-20 20:04:47 +00001705 // Check the length modifier is valid with the given conversion specifier.
1706 const LengthModifier &LM = FS.getLengthModifier();
1707 if (!FS.hasValidLengthModifier()) {
1708 S.Diag(getLocationOfByte(LM.getStart()),
1709 diag::warn_format_nonsensical_length)
1710 << LM.toString() << CS.toString()
1711 << getSpecifierRange(startSpecifier, specifierLen)
1712 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1713 LM.getLength()));
1714 }
1715
Ted Kremenek826a3452010-07-16 02:11:22 +00001716 // The remaining checks depend on the data arguments.
1717 if (HasVAListArg)
1718 return true;
1719
Ted Kremenek666a1972010-07-26 19:45:42 +00001720 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001721 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001722
1723 // FIXME: Check that the argument type matches the format specifier.
1724
1725 return true;
1726}
1727
1728void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001729 const Expr *OrigFormatExpr,
1730 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001731 unsigned format_idx, unsigned firstDataArg,
1732 bool isPrintf) {
1733
Ted Kremeneke0e53132010-01-28 23:39:18 +00001734 // CHECK: is the format string a wide literal?
1735 if (FExpr->isWide()) {
1736 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001737 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001738 << OrigFormatExpr->getSourceRange();
1739 return;
1740 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001741
Ted Kremeneke0e53132010-01-28 23:39:18 +00001742 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001743 llvm::StringRef StrRef = FExpr->getString();
1744 const char *Str = StrRef.data();
1745 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001746
Ted Kremeneke0e53132010-01-28 23:39:18 +00001747 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001748 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001749 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001750 << OrigFormatExpr->getSourceRange();
1751 return;
1752 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001753
1754 if (isPrintf) {
1755 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1756 TheCall->getNumArgs() - firstDataArg,
1757 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1758 HasVAListArg, TheCall, format_idx);
1759
1760 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1761 H.DoneProcessing();
1762 }
1763 else {
1764 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1765 TheCall->getNumArgs() - firstDataArg,
1766 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1767 HasVAListArg, TheCall, format_idx);
1768
1769 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1770 H.DoneProcessing();
1771 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001772}
1773
Ted Kremenek06de2762007-08-17 16:46:58 +00001774//===--- CHECK: Return Address of Stack Variable --------------------------===//
1775
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001776static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1777static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001778
1779/// CheckReturnStackAddr - Check if a return statement returns the address
1780/// of a stack variable.
1781void
1782Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1783 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001785 Expr *stackE = 0;
1786 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1787
1788 // Perform checking for returned stack addresses, local blocks,
1789 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001790 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001791 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001792 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001793 stackE = EvalVal(RetValExp, refVars);
1794 }
1795
1796 if (stackE == 0)
1797 return; // Nothing suspicious was found.
1798
1799 SourceLocation diagLoc;
1800 SourceRange diagRange;
1801 if (refVars.empty()) {
1802 diagLoc = stackE->getLocStart();
1803 diagRange = stackE->getSourceRange();
1804 } else {
1805 // We followed through a reference variable. 'stackE' contains the
1806 // problematic expression but we will warn at the return statement pointing
1807 // at the reference variable. We will later display the "trail" of
1808 // reference variables using notes.
1809 diagLoc = refVars[0]->getLocStart();
1810 diagRange = refVars[0]->getSourceRange();
1811 }
1812
1813 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1814 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1815 : diag::warn_ret_stack_addr)
1816 << DR->getDecl()->getDeclName() << diagRange;
1817 } else if (isa<BlockExpr>(stackE)) { // local block.
1818 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1819 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1820 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1821 } else { // local temporary.
1822 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1823 : diag::warn_ret_local_temp_addr)
1824 << diagRange;
1825 }
1826
1827 // Display the "trail" of reference variables that we followed until we
1828 // found the problematic expression using notes.
1829 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1830 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1831 // If this var binds to another reference var, show the range of the next
1832 // var, otherwise the var binds to the problematic expression, in which case
1833 // show the range of the expression.
1834 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1835 : stackE->getSourceRange();
1836 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1837 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001838 }
1839}
1840
1841/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1842/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001843/// to a location on the stack, a local block, an address of a label, or a
1844/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001845/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001846/// encounter a subexpression that (1) clearly does not lead to one of the
1847/// above problematic expressions (2) is something we cannot determine leads to
1848/// a problematic expression based on such local checking.
1849///
1850/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1851/// the expression that they point to. Such variables are added to the
1852/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001853///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001854/// EvalAddr processes expressions that are pointers that are used as
1855/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001856/// At the base case of the recursion is a check for the above problematic
1857/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001858///
1859/// This implementation handles:
1860///
1861/// * pointer-to-pointer casts
1862/// * implicit conversions from array references to pointers
1863/// * taking the address of fields
1864/// * arbitrary interplay between "&" and "*" operators
1865/// * pointer arithmetic from an address of a stack variable
1866/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001867static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1868 if (E->isTypeDependent())
1869 return NULL;
1870
Ted Kremenek06de2762007-08-17 16:46:58 +00001871 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001872 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001873 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001874 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001875 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001876
Ted Kremenek06de2762007-08-17 16:46:58 +00001877 // Our "symbolic interpreter" is just a dispatch off the currently
1878 // viewed AST node. We then recursively traverse the AST by calling
1879 // EvalAddr and EvalVal appropriately.
1880 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001881 case Stmt::ParenExprClass:
1882 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001883 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1884
1885 case Stmt::DeclRefExprClass: {
1886 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1887
1888 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1889 // If this is a reference variable, follow through to the expression that
1890 // it points to.
1891 if (V->hasLocalStorage() &&
1892 V->getType()->isReferenceType() && V->hasInit()) {
1893 // Add the reference variable to the "trail".
1894 refVars.push_back(DR);
1895 return EvalAddr(V->getInit(), refVars);
1896 }
1897
1898 return NULL;
1899 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001900
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001901 case Stmt::UnaryOperatorClass: {
1902 // The only unary operator that make sense to handle here
1903 // is AddrOf. All others don't make sense as pointers.
1904 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001905
John McCall2de56d12010-08-25 11:45:40 +00001906 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001907 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001908 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001909 return NULL;
1910 }
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001912 case Stmt::BinaryOperatorClass: {
1913 // Handle pointer arithmetic. All other binary operators are not valid
1914 // in this context.
1915 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001916 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001917
John McCall2de56d12010-08-25 11:45:40 +00001918 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001919 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001921 Expr *Base = B->getLHS();
1922
1923 // Determine which argument is the real pointer base. It could be
1924 // the RHS argument instead of the LHS.
1925 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001926
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001927 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001928 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001929 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001930
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001931 // For conditional operators we need to see if either the LHS or RHS are
1932 // valid DeclRefExpr*s. If one of them is valid, we return it.
1933 case Stmt::ConditionalOperatorClass: {
1934 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001936 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001937 if (Expr *lhsExpr = C->getLHS()) {
1938 // In C++, we can have a throw-expression, which has 'void' type.
1939 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001940 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001941 return LHS;
1942 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001943
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001944 // In C++, we can have a throw-expression, which has 'void' type.
1945 if (C->getRHS()->getType()->isVoidType())
1946 return NULL;
1947
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001948 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001949 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001950
1951 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001952 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001953 return E; // local block.
1954 return NULL;
1955
1956 case Stmt::AddrLabelExprClass:
1957 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001958
Ted Kremenek54b52742008-08-07 00:49:01 +00001959 // For casts, we need to handle conversions from arrays to
1960 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001961 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001962 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001963 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001964 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001965 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroffdd972f22008-09-05 22:11:13 +00001967 if (SubExpr->getType()->isPointerType() ||
1968 SubExpr->getType()->isBlockPointerType() ||
1969 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001970 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001971 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001972 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001973 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001974 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001977 // C++ casts. For dynamic casts, static casts, and const casts, we
1978 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001979 // through the cast. In the case the dynamic cast doesn't fail (and
1980 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001981 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001982 // FIXME: The comment about is wrong; we're not always converting
1983 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001984 // handle references to objects.
1985 case Stmt::CXXStaticCastExprClass:
1986 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001987 case Stmt::CXXConstCastExprClass:
1988 case Stmt::CXXReinterpretCastExprClass: {
1989 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001990 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001991 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001992 else
1993 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001994 }
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001996 // Everything else: we simply don't reason about them.
1997 default:
1998 return NULL;
1999 }
Ted Kremenek06de2762007-08-17 16:46:58 +00002000}
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Ted Kremenek06de2762007-08-17 16:46:58 +00002002
2003/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2004/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002005static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002006do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002007 // We should only be called for evaluating non-pointer expressions, or
2008 // expressions with a pointer type that are not used as references but instead
2009 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Ted Kremenek06de2762007-08-17 16:46:58 +00002011 // Our "symbolic interpreter" is just a dispatch off the currently
2012 // viewed AST node. We then recursively traverse the AST by calling
2013 // EvalAddr and EvalVal appropriately.
2014 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002015 case Stmt::ImplicitCastExprClass: {
2016 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002017 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002018 E = IE->getSubExpr();
2019 continue;
2020 }
2021 return NULL;
2022 }
2023
Douglas Gregora2813ce2009-10-23 18:54:35 +00002024 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002025 // When we hit a DeclRefExpr we are looking at code that refers to a
2026 // variable's name. If it's not a reference variable we check if it has
2027 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002028 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Ted Kremenek06de2762007-08-17 16:46:58 +00002030 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002031 if (V->hasLocalStorage()) {
2032 if (!V->getType()->isReferenceType())
2033 return DR;
2034
2035 // Reference variable, follow through to the expression that
2036 // it points to.
2037 if (V->hasInit()) {
2038 // Add the reference variable to the "trail".
2039 refVars.push_back(DR);
2040 return EvalVal(V->getInit(), refVars);
2041 }
2042 }
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Ted Kremenek06de2762007-08-17 16:46:58 +00002044 return NULL;
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Ted Kremenek68957a92010-08-04 20:01:07 +00002047 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002048 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002049 E = cast<ParenExpr>(E)->getSubExpr();
2050 continue;
2051 }
Mike Stump1eb44332009-09-09 15:08:12 +00002052
Ted Kremenek06de2762007-08-17 16:46:58 +00002053 case Stmt::UnaryOperatorClass: {
2054 // The only unary operator that make sense to handle here
2055 // is Deref. All others don't resolve to a "name." This includes
2056 // handling all sorts of rvalues passed to a unary operator.
2057 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002058
John McCall2de56d12010-08-25 11:45:40 +00002059 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002060 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002061
2062 return NULL;
2063 }
Mike Stump1eb44332009-09-09 15:08:12 +00002064
Ted Kremenek06de2762007-08-17 16:46:58 +00002065 case Stmt::ArraySubscriptExprClass: {
2066 // Array subscripts are potential references to data on the stack. We
2067 // retrieve the DeclRefExpr* for the array variable if it indeed
2068 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002069 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002070 }
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Ted Kremenek06de2762007-08-17 16:46:58 +00002072 case Stmt::ConditionalOperatorClass: {
2073 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002074 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002075 ConditionalOperator *C = cast<ConditionalOperator>(E);
2076
Anders Carlsson39073232007-11-30 19:04:31 +00002077 // Handle the GNU extension for missing LHS.
2078 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002079 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002080 return LHS;
2081
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002082 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002083 }
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Ted Kremenek06de2762007-08-17 16:46:58 +00002085 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002086 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002087 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Ted Kremenek06de2762007-08-17 16:46:58 +00002089 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002090 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002091 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002092
2093 // Check whether the member type is itself a reference, in which case
2094 // we're not going to refer to the member, but to what the member refers to.
2095 if (M->getMemberDecl()->getType()->isReferenceType())
2096 return NULL;
2097
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002098 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002099 }
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Ted Kremenek06de2762007-08-17 16:46:58 +00002101 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002102 // Check that we don't return or take the address of a reference to a
2103 // temporary. This is only useful in C++.
2104 if (!E->isTypeDependent() && E->isRValue())
2105 return E;
2106
2107 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002108 return NULL;
2109 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002110} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002111}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002112
2113//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2114
2115/// Check for comparisons of floating point operands using != and ==.
2116/// Issue a warning if these are no self-comparisons, as they are not likely
2117/// to do what the programmer intended.
2118void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2119 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002120
John McCallf6a16482010-12-04 03:47:34 +00002121 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2122 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002123
2124 // Special case: check for x == x (which is OK).
2125 // Do not emit warnings for such cases.
2126 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2127 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2128 if (DRL->getDecl() == DRR->getDecl())
2129 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002130
2131
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002132 // Special case: check for comparisons against literals that can be exactly
2133 // represented by APFloat. In such cases, do not emit a warning. This
2134 // is a heuristic: often comparison against such literals are used to
2135 // detect if a value in a variable has not changed. This clearly can
2136 // lead to false negatives.
2137 if (EmitWarning) {
2138 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2139 if (FLL->isExact())
2140 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002141 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002142 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2143 if (FLR->isExact())
2144 EmitWarning = false;
2145 }
2146 }
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002148 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002149 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002150 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002151 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002152 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Sebastian Redl0eb23302009-01-19 00:08:26 +00002154 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002155 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002156 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002157 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002158
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002159 // Emit the diagnostic.
2160 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002161 Diag(loc, diag::warn_floatingpoint_eq)
2162 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002163}
John McCallba26e582010-01-04 23:21:16 +00002164
John McCallf2370c92010-01-06 05:24:50 +00002165//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2166//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002167
John McCallf2370c92010-01-06 05:24:50 +00002168namespace {
John McCallba26e582010-01-04 23:21:16 +00002169
John McCallf2370c92010-01-06 05:24:50 +00002170/// Structure recording the 'active' range of an integer-valued
2171/// expression.
2172struct IntRange {
2173 /// The number of bits active in the int.
2174 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002175
John McCallf2370c92010-01-06 05:24:50 +00002176 /// True if the int is known not to have negative values.
2177 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002178
John McCallf2370c92010-01-06 05:24:50 +00002179 IntRange(unsigned Width, bool NonNegative)
2180 : Width(Width), NonNegative(NonNegative)
2181 {}
John McCallba26e582010-01-04 23:21:16 +00002182
John McCall1844a6e2010-11-10 23:38:19 +00002183 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002184 static IntRange forBoolType() {
2185 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002186 }
2187
John McCall1844a6e2010-11-10 23:38:19 +00002188 /// Returns the range of an opaque value of the given integral type.
2189 static IntRange forValueOfType(ASTContext &C, QualType T) {
2190 return forValueOfCanonicalType(C,
2191 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002192 }
2193
John McCall1844a6e2010-11-10 23:38:19 +00002194 /// Returns the range of an opaque value of a canonical integral type.
2195 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002196 assert(T->isCanonicalUnqualified());
2197
2198 if (const VectorType *VT = dyn_cast<VectorType>(T))
2199 T = VT->getElementType().getTypePtr();
2200 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2201 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002202
John McCall091f23f2010-11-09 22:22:12 +00002203 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002204 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2205 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002206 if (!Enum->isDefinition())
2207 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2208
John McCall323ed742010-05-06 08:58:33 +00002209 unsigned NumPositive = Enum->getNumPositiveBits();
2210 unsigned NumNegative = Enum->getNumNegativeBits();
2211
2212 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2213 }
John McCallf2370c92010-01-06 05:24:50 +00002214
2215 const BuiltinType *BT = cast<BuiltinType>(T);
2216 assert(BT->isInteger());
2217
2218 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2219 }
2220
John McCall1844a6e2010-11-10 23:38:19 +00002221 /// Returns the "target" range of a canonical integral type, i.e.
2222 /// the range of values expressible in the type.
2223 ///
2224 /// This matches forValueOfCanonicalType except that enums have the
2225 /// full range of their type, not the range of their enumerators.
2226 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2227 assert(T->isCanonicalUnqualified());
2228
2229 if (const VectorType *VT = dyn_cast<VectorType>(T))
2230 T = VT->getElementType().getTypePtr();
2231 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2232 T = CT->getElementType().getTypePtr();
2233 if (const EnumType *ET = dyn_cast<EnumType>(T))
2234 T = ET->getDecl()->getIntegerType().getTypePtr();
2235
2236 const BuiltinType *BT = cast<BuiltinType>(T);
2237 assert(BT->isInteger());
2238
2239 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2240 }
2241
2242 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002243 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002244 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002245 L.NonNegative && R.NonNegative);
2246 }
2247
John McCall1844a6e2010-11-10 23:38:19 +00002248 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002249 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002250 return IntRange(std::min(L.Width, R.Width),
2251 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002252 }
2253};
2254
2255IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2256 if (value.isSigned() && value.isNegative())
2257 return IntRange(value.getMinSignedBits(), false);
2258
2259 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002260 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002261
2262 // isNonNegative() just checks the sign bit without considering
2263 // signedness.
2264 return IntRange(value.getActiveBits(), true);
2265}
2266
John McCall0acc3112010-01-06 22:57:21 +00002267IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002268 unsigned MaxWidth) {
2269 if (result.isInt())
2270 return GetValueRange(C, result.getInt(), MaxWidth);
2271
2272 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002273 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2274 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2275 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2276 R = IntRange::join(R, El);
2277 }
John McCallf2370c92010-01-06 05:24:50 +00002278 return R;
2279 }
2280
2281 if (result.isComplexInt()) {
2282 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2283 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2284 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002285 }
2286
2287 // This can happen with lossless casts to intptr_t of "based" lvalues.
2288 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002289 // FIXME: The only reason we need to pass the type in here is to get
2290 // the sign right on this one case. It would be nice if APValue
2291 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002292 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002293 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002294}
John McCallf2370c92010-01-06 05:24:50 +00002295
2296/// Pseudo-evaluate the given integer expression, estimating the
2297/// range of values it might take.
2298///
2299/// \param MaxWidth - the width to which the value will be truncated
2300IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2301 E = E->IgnoreParens();
2302
2303 // Try a full evaluation first.
2304 Expr::EvalResult result;
2305 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002306 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002307
2308 // I think we only want to look through implicit casts here; if the
2309 // user has an explicit widening cast, we should treat the value as
2310 // being of the new, wider type.
2311 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002312 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002313 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2314
John McCall1844a6e2010-11-10 23:38:19 +00002315 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002316
John McCall2de56d12010-08-25 11:45:40 +00002317 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002318
John McCallf2370c92010-01-06 05:24:50 +00002319 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002320 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002321 return OutputTypeRange;
2322
2323 IntRange SubRange
2324 = GetExprRange(C, CE->getSubExpr(),
2325 std::min(MaxWidth, OutputTypeRange.Width));
2326
2327 // Bail out if the subexpr's range is as wide as the cast type.
2328 if (SubRange.Width >= OutputTypeRange.Width)
2329 return OutputTypeRange;
2330
2331 // Otherwise, we take the smaller width, and we're non-negative if
2332 // either the output type or the subexpr is.
2333 return IntRange(SubRange.Width,
2334 SubRange.NonNegative || OutputTypeRange.NonNegative);
2335 }
2336
2337 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2338 // If we can fold the condition, just take that operand.
2339 bool CondResult;
2340 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2341 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2342 : CO->getFalseExpr(),
2343 MaxWidth);
2344
2345 // Otherwise, conservatively merge.
2346 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2347 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2348 return IntRange::join(L, R);
2349 }
2350
2351 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2352 switch (BO->getOpcode()) {
2353
2354 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002355 case BO_LAnd:
2356 case BO_LOr:
2357 case BO_LT:
2358 case BO_GT:
2359 case BO_LE:
2360 case BO_GE:
2361 case BO_EQ:
2362 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002363 return IntRange::forBoolType();
2364
John McCallc0cd21d2010-02-23 19:22:29 +00002365 // The type of these compound assignments is the type of the LHS,
2366 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002367 case BO_MulAssign:
2368 case BO_DivAssign:
2369 case BO_RemAssign:
2370 case BO_AddAssign:
2371 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002372 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002373
John McCallf2370c92010-01-06 05:24:50 +00002374 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002375 case BO_PtrMemD:
2376 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002377 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002378
John McCall60fad452010-01-06 22:07:33 +00002379 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002380 case BO_And:
2381 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002382 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2383 GetExprRange(C, BO->getRHS(), MaxWidth));
2384
John McCallf2370c92010-01-06 05:24:50 +00002385 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002386 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002387 // ...except that we want to treat '1 << (blah)' as logically
2388 // positive. It's an important idiom.
2389 if (IntegerLiteral *I
2390 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2391 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002392 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002393 return IntRange(R.Width, /*NonNegative*/ true);
2394 }
2395 }
2396 // fallthrough
2397
John McCall2de56d12010-08-25 11:45:40 +00002398 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002399 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002400
John McCall60fad452010-01-06 22:07:33 +00002401 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002402 case BO_Shr:
2403 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002404 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2405
2406 // If the shift amount is a positive constant, drop the width by
2407 // that much.
2408 llvm::APSInt shift;
2409 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2410 shift.isNonNegative()) {
2411 unsigned zext = shift.getZExtValue();
2412 if (zext >= L.Width)
2413 L.Width = (L.NonNegative ? 0 : 1);
2414 else
2415 L.Width -= zext;
2416 }
2417
2418 return L;
2419 }
2420
2421 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002422 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002423 return GetExprRange(C, BO->getRHS(), MaxWidth);
2424
John McCall60fad452010-01-06 22:07:33 +00002425 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002426 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002427 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002428 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002429 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002430
John McCallf2370c92010-01-06 05:24:50 +00002431 default:
2432 break;
2433 }
2434
2435 // Treat every other operator as if it were closed on the
2436 // narrowest type that encompasses both operands.
2437 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2438 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2439 return IntRange::join(L, R);
2440 }
2441
2442 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2443 switch (UO->getOpcode()) {
2444 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002445 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002446 return IntRange::forBoolType();
2447
2448 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002449 case UO_Deref:
2450 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002451 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002452
2453 default:
2454 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2455 }
2456 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002457
2458 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002459 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002460 }
John McCallf2370c92010-01-06 05:24:50 +00002461
2462 FieldDecl *BitField = E->getBitField();
2463 if (BitField) {
2464 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2465 unsigned BitWidth = BitWidthAP.getZExtValue();
2466
2467 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2468 }
2469
John McCall1844a6e2010-11-10 23:38:19 +00002470 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002471}
John McCall51313c32010-01-04 23:31:57 +00002472
John McCall323ed742010-05-06 08:58:33 +00002473IntRange GetExprRange(ASTContext &C, Expr *E) {
2474 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2475}
2476
John McCall51313c32010-01-04 23:31:57 +00002477/// Checks whether the given value, which currently has the given
2478/// source semantics, has the same value when coerced through the
2479/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002480bool IsSameFloatAfterCast(const llvm::APFloat &value,
2481 const llvm::fltSemantics &Src,
2482 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002483 llvm::APFloat truncated = value;
2484
2485 bool ignored;
2486 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2487 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2488
2489 return truncated.bitwiseIsEqual(value);
2490}
2491
2492/// Checks whether the given value, which currently has the given
2493/// source semantics, has the same value when coerced through the
2494/// target semantics.
2495///
2496/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002497bool IsSameFloatAfterCast(const APValue &value,
2498 const llvm::fltSemantics &Src,
2499 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002500 if (value.isFloat())
2501 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2502
2503 if (value.isVector()) {
2504 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2505 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2506 return false;
2507 return true;
2508 }
2509
2510 assert(value.isComplexFloat());
2511 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2512 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2513}
2514
John McCallb4eb64d2010-10-08 02:01:28 +00002515void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002516
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002517static bool IsZero(Sema &S, Expr *E) {
2518 // Suppress cases where we are comparing against an enum constant.
2519 if (const DeclRefExpr *DR =
2520 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2521 if (isa<EnumConstantDecl>(DR->getDecl()))
2522 return false;
2523
2524 // Suppress cases where the '0' value is expanded from a macro.
2525 if (E->getLocStart().isMacroID())
2526 return false;
2527
John McCall323ed742010-05-06 08:58:33 +00002528 llvm::APSInt Value;
2529 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2530}
2531
John McCall372e1032010-10-06 00:25:24 +00002532static bool HasEnumType(Expr *E) {
2533 // Strip off implicit integral promotions.
2534 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002535 if (ICE->getCastKind() != CK_IntegralCast &&
2536 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002537 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002538 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002539 }
2540
2541 return E->getType()->isEnumeralType();
2542}
2543
John McCall323ed742010-05-06 08:58:33 +00002544void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002545 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002546 if (E->isValueDependent())
2547 return;
2548
John McCall2de56d12010-08-25 11:45:40 +00002549 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002550 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002551 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002552 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002553 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002554 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002555 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002556 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002557 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002558 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002559 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002560 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002561 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002562 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002563 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002564 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2565 }
2566}
2567
2568/// Analyze the operands of the given comparison. Implements the
2569/// fallback case from AnalyzeComparison.
2570void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002571 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2572 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002573}
John McCall51313c32010-01-04 23:31:57 +00002574
John McCallba26e582010-01-04 23:21:16 +00002575/// \brief Implements -Wsign-compare.
2576///
2577/// \param lex the left-hand expression
2578/// \param rex the right-hand expression
2579/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002580/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002581void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2582 // The type the comparison is being performed in.
2583 QualType T = E->getLHS()->getType();
2584 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2585 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002586
John McCall323ed742010-05-06 08:58:33 +00002587 // We don't do anything special if this isn't an unsigned integral
2588 // comparison: we're only interested in integral comparisons, and
2589 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002590 //
2591 // We also don't care about value-dependent expressions or expressions
2592 // whose result is a constant.
2593 if (!T->hasUnsignedIntegerRepresentation()
2594 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002595 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002596
John McCall323ed742010-05-06 08:58:33 +00002597 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2598 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002599
John McCall323ed742010-05-06 08:58:33 +00002600 // Check to see if one of the (unmodified) operands is of different
2601 // signedness.
2602 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002603 if (lex->getType()->hasSignedIntegerRepresentation()) {
2604 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002605 "unsigned comparison between two signed integer expressions?");
2606 signedOperand = lex;
2607 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002608 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002609 signedOperand = rex;
2610 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002611 } else {
John McCall323ed742010-05-06 08:58:33 +00002612 CheckTrivialUnsignedComparison(S, E);
2613 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002614 }
2615
John McCall323ed742010-05-06 08:58:33 +00002616 // Otherwise, calculate the effective range of the signed operand.
2617 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002618
John McCall323ed742010-05-06 08:58:33 +00002619 // Go ahead and analyze implicit conversions in the operands. Note
2620 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002621 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2622 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002623
John McCall323ed742010-05-06 08:58:33 +00002624 // If the signed range is non-negative, -Wsign-compare won't fire,
2625 // but we should still check for comparisons which are always true
2626 // or false.
2627 if (signedRange.NonNegative)
2628 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002629
2630 // For (in)equality comparisons, if the unsigned operand is a
2631 // constant which cannot collide with a overflowed signed operand,
2632 // then reinterpreting the signed operand as unsigned will not
2633 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002634 if (E->isEqualityOp()) {
2635 unsigned comparisonWidth = S.Context.getIntWidth(T);
2636 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002637
John McCall323ed742010-05-06 08:58:33 +00002638 // We should never be unable to prove that the unsigned operand is
2639 // non-negative.
2640 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2641
2642 if (unsignedRange.Width < comparisonWidth)
2643 return;
2644 }
2645
2646 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2647 << lex->getType() << rex->getType()
2648 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002649}
2650
John McCall15d7d122010-11-11 03:21:53 +00002651/// Analyzes an attempt to assign the given value to a bitfield.
2652///
2653/// Returns true if there was something fishy about the attempt.
2654bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2655 SourceLocation InitLoc) {
2656 assert(Bitfield->isBitField());
2657 if (Bitfield->isInvalidDecl())
2658 return false;
2659
John McCall91b60142010-11-11 05:33:51 +00002660 // White-list bool bitfields.
2661 if (Bitfield->getType()->isBooleanType())
2662 return false;
2663
Douglas Gregor46ff3032011-02-04 13:09:01 +00002664 // Ignore value- or type-dependent expressions.
2665 if (Bitfield->getBitWidth()->isValueDependent() ||
2666 Bitfield->getBitWidth()->isTypeDependent() ||
2667 Init->isValueDependent() ||
2668 Init->isTypeDependent())
2669 return false;
2670
John McCall15d7d122010-11-11 03:21:53 +00002671 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2672
2673 llvm::APSInt Width(32);
2674 Expr::EvalResult InitValue;
2675 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002676 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002677 !InitValue.Val.isInt())
2678 return false;
2679
2680 const llvm::APSInt &Value = InitValue.Val.getInt();
2681 unsigned OriginalWidth = Value.getBitWidth();
2682 unsigned FieldWidth = Width.getZExtValue();
2683
2684 if (OriginalWidth <= FieldWidth)
2685 return false;
2686
Jay Foad9f71a8f2010-12-07 08:25:34 +00002687 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002688
2689 // It's fairly common to write values into signed bitfields
2690 // that, if sign-extended, would end up becoming a different
2691 // value. We don't want to warn about that.
2692 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002693 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002694 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002695 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002696
2697 if (Value == TruncatedValue)
2698 return false;
2699
2700 std::string PrettyValue = Value.toString(10);
2701 std::string PrettyTrunc = TruncatedValue.toString(10);
2702
2703 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2704 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2705 << Init->getSourceRange();
2706
2707 return true;
2708}
2709
John McCallbeb22aa2010-11-09 23:24:47 +00002710/// Analyze the given simple or compound assignment for warning-worthy
2711/// operations.
2712void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2713 // Just recurse on the LHS.
2714 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2715
2716 // We want to recurse on the RHS as normal unless we're assigning to
2717 // a bitfield.
2718 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002719 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2720 E->getOperatorLoc())) {
2721 // Recurse, ignoring any implicit conversions on the RHS.
2722 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2723 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002724 }
2725 }
2726
2727 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2728}
2729
John McCall51313c32010-01-04 23:31:57 +00002730/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002731void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2732 unsigned diag) {
2733 S.Diag(E->getExprLoc(), diag)
2734 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002735}
2736
John McCall091f23f2010-11-09 22:22:12 +00002737std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2738 if (!Range.Width) return "0";
2739
2740 llvm::APSInt ValueInRange = Value;
2741 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002742 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002743 return ValueInRange.toString(10);
2744}
2745
John McCall323ed742010-05-06 08:58:33 +00002746void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002747 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002748 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002749
John McCall323ed742010-05-06 08:58:33 +00002750 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2751 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2752 if (Source == Target) return;
2753 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002754
John McCallb4eb64d2010-10-08 02:01:28 +00002755 // If the conversion context location is invalid or instantiated
2756 // from a system macro, don't complain.
2757 if (CC.isInvalid() ||
2758 (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2759 S.Context.getSourceManager().getSpellingLoc(CC))))
2760 return;
2761
John McCall51313c32010-01-04 23:31:57 +00002762 // Never diagnose implicit casts to bool.
2763 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2764 return;
2765
2766 // Strip vector types.
2767 if (isa<VectorType>(Source)) {
2768 if (!isa<VectorType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002769 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002770
2771 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2772 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2773 }
2774
2775 // Strip complex types.
2776 if (isa<ComplexType>(Source)) {
2777 if (!isa<ComplexType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002778 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002779
2780 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2781 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2782 }
2783
2784 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2785 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2786
2787 // If the source is floating point...
2788 if (SourceBT && SourceBT->isFloatingPoint()) {
2789 // ...and the target is floating point...
2790 if (TargetBT && TargetBT->isFloatingPoint()) {
2791 // ...then warn if we're dropping FP rank.
2792
2793 // Builtin FP kinds are ordered by increasing FP rank.
2794 if (SourceBT->getKind() > TargetBT->getKind()) {
2795 // Don't warn about float constants that are precisely
2796 // representable in the target type.
2797 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002798 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002799 // Value might be a float, a float vector, or a float complex.
2800 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002801 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2802 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002803 return;
2804 }
2805
John McCallb4eb64d2010-10-08 02:01:28 +00002806 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002807 }
2808 return;
2809 }
2810
2811 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002812 if ((TargetBT && TargetBT->isInteger())) {
2813 Expr *InnerE = E->IgnoreParenImpCasts();
2814 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2815 DiagnoseImpCast(S, LiteralExpr, T, CC,
2816 diag::warn_impcast_literal_float_to_integer);
2817 } else {
2818 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2819 }
2820 }
John McCall51313c32010-01-04 23:31:57 +00002821
2822 return;
2823 }
2824
John McCallf2370c92010-01-06 05:24:50 +00002825 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002826 return;
2827
John McCall323ed742010-05-06 08:58:33 +00002828 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002829 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002830
2831 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002832 // If the source is a constant, use a default-on diagnostic.
2833 // TODO: this should happen for bitfield stores, too.
2834 llvm::APSInt Value(32);
2835 if (E->isIntegerConstantExpr(Value, S.Context)) {
2836 std::string PrettySourceValue = Value.toString(10);
2837 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2838
2839 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2840 << PrettySourceValue << PrettyTargetValue
2841 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2842 return;
2843 }
2844
John McCall51313c32010-01-04 23:31:57 +00002845 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2846 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002847 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002848 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2849 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002850 }
2851
2852 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2853 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2854 SourceRange.Width == TargetRange.Width)) {
2855 unsigned DiagID = diag::warn_impcast_integer_sign;
2856
2857 // Traditionally, gcc has warned about this under -Wsign-compare.
2858 // We also want to warn about it in -Wconversion.
2859 // So if -Wconversion is off, use a completely identical diagnostic
2860 // in the sign-compare group.
2861 // The conditional-checking code will
2862 if (ICContext) {
2863 DiagID = diag::warn_impcast_integer_sign_conditional;
2864 *ICContext = true;
2865 }
2866
John McCallb4eb64d2010-10-08 02:01:28 +00002867 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002868 }
2869
Douglas Gregor284cc8d2011-02-22 02:45:07 +00002870 // Diagnose conversions between different enumeration types.
2871 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2872 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2873 if ((SourceEnum->getDecl()->getIdentifier() ||
2874 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2875 (TargetEnum->getDecl()->getIdentifier() ||
2876 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
2877 SourceEnum != TargetEnum)
2878 return DiagnoseImpCast(S, E, T, CC,
2879 diag::warn_impcast_different_enum_types);
2880
John McCall51313c32010-01-04 23:31:57 +00002881 return;
2882}
2883
John McCall323ed742010-05-06 08:58:33 +00002884void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2885
2886void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002887 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002888 E = E->IgnoreParenImpCasts();
2889
2890 if (isa<ConditionalOperator>(E))
2891 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2892
John McCallb4eb64d2010-10-08 02:01:28 +00002893 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002894 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002895 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002896 return;
2897}
2898
2899void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002900 SourceLocation CC = E->getQuestionLoc();
2901
2902 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002903
2904 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002905 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2906 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002907
2908 // If -Wconversion would have warned about either of the candidates
2909 // for a signedness conversion to the context type...
2910 if (!Suspicious) return;
2911
2912 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002913 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2914 CC))
John McCall323ed742010-05-06 08:58:33 +00002915 return;
2916
2917 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002918 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002919 return;
2920
2921 // ...then check whether it would have warned about either of the
2922 // candidates for a signedness conversion to the condition type.
2923 if (E->getType() != T) {
2924 Suspicious = false;
2925 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002926 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002927 if (!Suspicious)
2928 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002929 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002930 if (!Suspicious)
2931 return;
2932 }
2933
2934 // If so, emit a diagnostic under -Wsign-compare.
2935 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2936 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2937 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2938 << lex->getType() << rex->getType()
2939 << lex->getSourceRange() << rex->getSourceRange();
2940}
2941
2942/// AnalyzeImplicitConversions - Find and report any interesting
2943/// implicit conversions in the given expression. There are a couple
2944/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002945void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002946 QualType T = OrigE->getType();
2947 Expr *E = OrigE->IgnoreParenImpCasts();
2948
2949 // For conditional operators, we analyze the arguments as if they
2950 // were being fed directly into the output.
2951 if (isa<ConditionalOperator>(E)) {
2952 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2953 CheckConditionalOperator(S, CO, T);
2954 return;
2955 }
2956
2957 // Go ahead and check any implicit conversions we might have skipped.
2958 // The non-canonical typecheck is just an optimization;
2959 // CheckImplicitConversion will filter out dead implicit conversions.
2960 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002961 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00002962
2963 // Now continue drilling into this expression.
2964
2965 // Skip past explicit casts.
2966 if (isa<ExplicitCastExpr>(E)) {
2967 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00002968 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002969 }
2970
John McCallbeb22aa2010-11-09 23:24:47 +00002971 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2972 // Do a somewhat different check with comparison operators.
2973 if (BO->isComparisonOp())
2974 return AnalyzeComparison(S, BO);
2975
2976 // And with assignments and compound assignments.
2977 if (BO->isAssignmentOp())
2978 return AnalyzeAssignment(S, BO);
2979 }
John McCall323ed742010-05-06 08:58:33 +00002980
2981 // These break the otherwise-useful invariant below. Fortunately,
2982 // we don't really need to recurse into them, because any internal
2983 // expressions should have been analyzed already when they were
2984 // built into statements.
2985 if (isa<StmtExpr>(E)) return;
2986
2987 // Don't descend into unevaluated contexts.
2988 if (isa<SizeOfAlignOfExpr>(E)) return;
2989
2990 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00002991 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00002992 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00002993 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00002994}
2995
2996} // end anonymous namespace
2997
2998/// Diagnoses "dangerous" implicit conversions within the given
2999/// expression (which is a full expression). Implements -Wconversion
3000/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00003001///
3002/// \param CC the "context" location of the implicit conversion, i.e.
3003/// the most location of the syntactic entity requiring the implicit
3004/// conversion
3005void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00003006 // Don't diagnose in unevaluated contexts.
3007 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3008 return;
3009
3010 // Don't diagnose for value- or type-dependent expressions.
3011 if (E->isTypeDependent() || E->isValueDependent())
3012 return;
3013
John McCallb4eb64d2010-10-08 02:01:28 +00003014 // This is not the right CC for (e.g.) a variable initialization.
3015 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00003016}
3017
John McCall15d7d122010-11-11 03:21:53 +00003018void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3019 FieldDecl *BitField,
3020 Expr *Init) {
3021 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3022}
3023
Mike Stumpf8c49212010-01-21 03:59:47 +00003024/// CheckParmsForFunctionDef - Check that the parameters of the given
3025/// function are appropriate for the definition of a function. This
3026/// takes care of any checks that cannot be performed on the
3027/// declaration itself, e.g., that the types of each of the function
3028/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003029bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3030 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003031 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003032 for (; P != PEnd; ++P) {
3033 ParmVarDecl *Param = *P;
3034
Mike Stumpf8c49212010-01-21 03:59:47 +00003035 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3036 // function declarator that is part of a function definition of
3037 // that function shall not have incomplete type.
3038 //
3039 // This is also C++ [dcl.fct]p6.
3040 if (!Param->isInvalidDecl() &&
3041 RequireCompleteType(Param->getLocation(), Param->getType(),
3042 diag::err_typecheck_decl_incomplete_type)) {
3043 Param->setInvalidDecl();
3044 HasInvalidParm = true;
3045 }
3046
3047 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3048 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003049 if (CheckParameterNames &&
3050 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003051 !Param->isImplicit() &&
3052 !getLangOptions().CPlusPlus)
3053 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003054
3055 // C99 6.7.5.3p12:
3056 // If the function declarator is not part of a definition of that
3057 // function, parameters may have incomplete type and may use the [*]
3058 // notation in their sequences of declarator specifiers to specify
3059 // variable length array types.
3060 QualType PType = Param->getOriginalType();
3061 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3062 if (AT->getSizeModifier() == ArrayType::Star) {
3063 // FIXME: This diagnosic should point the the '[*]' if source-location
3064 // information is added for it.
3065 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3066 }
3067 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003068 }
3069
3070 return HasInvalidParm;
3071}
John McCallb7f4ffe2010-08-12 21:44:57 +00003072
3073/// CheckCastAlign - Implements -Wcast-align, which warns when a
3074/// pointer cast increases the alignment requirements.
3075void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3076 // This is actually a lot of work to potentially be doing on every
3077 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003078 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3079 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003080 == Diagnostic::Ignored)
3081 return;
3082
3083 // Ignore dependent types.
3084 if (T->isDependentType() || Op->getType()->isDependentType())
3085 return;
3086
3087 // Require that the destination be a pointer type.
3088 const PointerType *DestPtr = T->getAs<PointerType>();
3089 if (!DestPtr) return;
3090
3091 // If the destination has alignment 1, we're done.
3092 QualType DestPointee = DestPtr->getPointeeType();
3093 if (DestPointee->isIncompleteType()) return;
3094 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3095 if (DestAlign.isOne()) return;
3096
3097 // Require that the source be a pointer type.
3098 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3099 if (!SrcPtr) return;
3100 QualType SrcPointee = SrcPtr->getPointeeType();
3101
3102 // Whitelist casts from cv void*. We already implicitly
3103 // whitelisted casts to cv void*, since they have alignment 1.
3104 // Also whitelist casts involving incomplete types, which implicitly
3105 // includes 'void'.
3106 if (SrcPointee->isIncompleteType()) return;
3107
3108 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3109 if (SrcAlign >= DestAlign) return;
3110
3111 Diag(TRange.getBegin(), diag::warn_cast_align)
3112 << Op->getType() << T
3113 << static_cast<unsigned>(SrcAlign.getQuantity())
3114 << static_cast<unsigned>(DestAlign.getQuantity())
3115 << TRange << Op->getSourceRange();
3116}
3117
Chandler Carruth34064582011-02-17 20:55:08 +00003118void Sema::CheckArrayAccess(const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003119 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003120 const ConstantArrayType *ArrayTy =
Chandler Carruth35001ca2011-02-17 21:10:52 +00003121 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003122 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003123 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003124
Chandler Carruth34064582011-02-17 20:55:08 +00003125 const Expr *IndexExpr = E->getIdx();
3126 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003127 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003128 llvm::APSInt index;
3129 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003130 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003131
Ted Kremenek9e060ca2011-02-23 23:06:04 +00003132 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003133 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003134 if (!size.isStrictlyPositive())
3135 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003136 if (size.getBitWidth() > index.getBitWidth())
3137 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003138 else if (size.getBitWidth() < index.getBitWidth())
3139 size = size.sext(index.getBitWidth());
3140
Chandler Carruth34064582011-02-17 20:55:08 +00003141 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003142 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003143
Ted Kremenek762696f2011-02-23 01:51:43 +00003144 DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
Ted Kremenekb70369c2011-02-23 01:51:40 +00003145 PDiag(diag::warn_array_index_exceeds_bounds)
3146 << index.toString(10, true) << size.toString(10, true)
3147 << IndexExpr->getSourceRange());
Chandler Carruth34064582011-02-17 20:55:08 +00003148 } else {
Ted Kremenek762696f2011-02-23 01:51:43 +00003149 DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
Ted Kremenekb70369c2011-02-23 01:51:40 +00003150 PDiag(diag::warn_array_index_precedes_bounds)
3151 << index.toString(10, true)
3152 << IndexExpr->getSourceRange());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003153 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003154
3155 const NamedDecl *ND = NULL;
3156 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3157 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3158 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3159 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3160 if (ND)
Ted Kremenek762696f2011-02-23 01:51:43 +00003161 DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
Ted Kremenekb70369c2011-02-23 01:51:40 +00003162 PDiag(diag::note_array_index_out_of_bounds)
3163 << ND->getDeclName());
Ted Kremeneka0125d82011-02-16 01:57:07 +00003164}
3165