blob: 556665483e6490108ed7ef0a44f942158d03f15c [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 Kremenekd30ef872009-01-12 23:09:09 +0000878// Handle i > 1 ? "x" : "y", recursivelly
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 Kremenek082d9362009-03-20 21:35:28 +0000921 case Stmt::DeclRefExprClass: {
922 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Ted Kremenek082d9362009-03-20 21:35:28 +0000924 // As an exception, do not flag errors for variables binding to
925 // const string literals.
926 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
927 bool isConstant = false;
928 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000929
Ted Kremenek082d9362009-03-20 21:35:28 +0000930 if (const ArrayType *AT = Context.getAsArrayType(T)) {
931 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000932 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000933 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000934 PT->getPointeeType().isConstant(Context);
935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Ted Kremenek082d9362009-03-20 21:35:28 +0000937 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000938 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000939 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000940 HasVAListArg, format_idx, firstDataArg,
941 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000942 }
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Anders Carlssond966a552009-06-28 19:55:58 +0000944 // For vprintf* functions (i.e., HasVAListArg==true), we add a
945 // special check to see if the format string is a function parameter
946 // of the function calling the printf function. If the function
947 // has an attribute indicating it is a printf-like function, then we
948 // should suppress warnings concerning non-literals being used in a call
949 // to a vprintf function. For example:
950 //
951 // void
952 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
953 // va_list ap;
954 // va_start(ap, fmt);
955 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
956 // ...
957 //
958 //
959 // FIXME: We don't have full attribute support yet, so just check to see
960 // if the argument is a DeclRefExpr that references a parameter. We'll
961 // add proper support for checking the attribute later.
962 if (HasVAListArg)
963 if (isa<ParmVarDecl>(VD))
964 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000965 }
Mike Stump1eb44332009-09-09 15:08:12 +0000966
Ted Kremenek082d9362009-03-20 21:35:28 +0000967 return false;
968 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000969
Anders Carlsson8f031b32009-06-27 04:05:33 +0000970 case Stmt::CallExprClass: {
971 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000972 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000973 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
974 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
975 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000976 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000977 unsigned ArgIndex = FA->getFormatIdx();
978 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
980 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000981 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +0000982 }
983 }
984 }
985 }
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Anders Carlsson8f031b32009-06-27 04:05:33 +0000987 return false;
988 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000989 case Stmt::ObjCStringLiteralClass:
990 case Stmt::StringLiteralClass: {
991 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000992
Ted Kremenek082d9362009-03-20 21:35:28 +0000993 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000994 StrE = ObjCFExpr->getString();
995 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000996 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000997
Ted Kremenekd30ef872009-01-12 23:09:09 +0000998 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +0000999 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1000 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +00001001 return true;
1002 }
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Ted Kremenekd30ef872009-01-12 23:09:09 +00001004 return false;
1005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Ted Kremenek082d9362009-03-20 21:35:28 +00001007 default:
1008 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001009 }
1010}
1011
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001012void
Mike Stump1eb44332009-09-09 15:08:12 +00001013Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1014 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001015 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1016 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001017 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001018 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001019 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001020 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001021 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1022 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001023 }
1024}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001025
Ted Kremenek826a3452010-07-16 02:11:22 +00001026/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1027/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001028void
Ted Kremenek826a3452010-07-16 02:11:22 +00001029Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1030 unsigned format_idx, unsigned firstDataArg,
1031 bool isPrintf) {
1032
Ted Kremenek082d9362009-03-20 21:35:28 +00001033 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001034
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001035 // The way the format attribute works in GCC, the implicit this argument
1036 // of member functions is counted. However, it doesn't appear in our own
1037 // lists, so decrement format_idx in that case.
1038 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001039 const CXXMethodDecl *method_decl =
1040 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1041 if (method_decl && method_decl->isInstance()) {
1042 // Catch a format attribute mistakenly referring to the object argument.
1043 if (format_idx == 0)
1044 return;
1045 --format_idx;
1046 if(firstDataArg != 0)
1047 --firstDataArg;
1048 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001049 }
1050
Ted Kremenek826a3452010-07-16 02:11:22 +00001051 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001052 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001053 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001054 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001055 return;
1056 }
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Ted Kremenek082d9362009-03-20 21:35:28 +00001058 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Chris Lattner59907c42007-08-10 20:18:51 +00001060 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001061 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001062 // Dynamically generated format strings are difficult to
1063 // automatically vet at compile time. Requiring that format strings
1064 // are string literals: (1) permits the checking of format strings by
1065 // the compiler and thereby (2) can practically remove the source of
1066 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001067
Mike Stump1eb44332009-09-09 15:08:12 +00001068 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001069 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001070 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001071 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001072 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001073 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001074 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001075
Chris Lattner655f1412009-04-29 04:59:47 +00001076 // If there are no arguments specified, warn with -Wformat-security, otherwise
1077 // warn only with -Wformat-nonliteral.
1078 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001079 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001080 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001081 << OrigFormatExpr->getSourceRange();
1082 else
Mike Stump1eb44332009-09-09 15:08:12 +00001083 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001084 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001085 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001086}
Ted Kremenek71895b92007-08-14 17:39:48 +00001087
Ted Kremeneke0e53132010-01-28 23:39:18 +00001088namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001089class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1090protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001091 Sema &S;
1092 const StringLiteral *FExpr;
1093 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001094 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001095 const unsigned NumDataArgs;
1096 const bool IsObjCLiteral;
1097 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001098 const bool HasVAListArg;
1099 const CallExpr *TheCall;
1100 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001101 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001102 bool usesPositionalArgs;
1103 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001104public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001105 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001106 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001107 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001108 const char *beg, bool hasVAListArg,
1109 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001110 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001111 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001112 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001113 IsObjCLiteral(isObjCLiteral), Beg(beg),
1114 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001115 TheCall(theCall), FormatIdx(formatIdx),
1116 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001117 CoveredArgs.resize(numDataArgs);
1118 CoveredArgs.reset();
1119 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001120
Ted Kremenek07d161f2010-01-29 01:50:07 +00001121 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001122
Ted Kremenek826a3452010-07-16 02:11:22 +00001123 void HandleIncompleteSpecifier(const char *startSpecifier,
1124 unsigned specifierLen);
1125
Ted Kremenekefaff192010-02-27 01:41:03 +00001126 virtual void HandleInvalidPosition(const char *startSpecifier,
1127 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001128 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001129
1130 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1131
Ted Kremeneke0e53132010-01-28 23:39:18 +00001132 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001133
Ted Kremenek826a3452010-07-16 02:11:22 +00001134protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001135 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1136 const char *startSpec,
1137 unsigned specifierLen,
1138 const char *csStart, unsigned csLen);
1139
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001140 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001141 CharSourceRange getSpecifierRange(const char *startSpecifier,
1142 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001143 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001144
Ted Kremenek0d277352010-01-29 01:06:55 +00001145 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001146
1147 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1148 const analyze_format_string::ConversionSpecifier &CS,
1149 const char *startSpecifier, unsigned specifierLen,
1150 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001151};
1152}
1153
Ted Kremenek826a3452010-07-16 02:11:22 +00001154SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001155 return OrigFormatExpr->getSourceRange();
1156}
1157
Ted Kremenek826a3452010-07-16 02:11:22 +00001158CharSourceRange CheckFormatHandler::
1159getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001160 SourceLocation Start = getLocationOfByte(startSpecifier);
1161 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1162
1163 // Advance the end SourceLocation by one due to half-open ranges.
1164 End = End.getFileLocWithOffset(1);
1165
1166 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001167}
1168
Ted Kremenek826a3452010-07-16 02:11:22 +00001169SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001170 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001171}
1172
Ted Kremenek826a3452010-07-16 02:11:22 +00001173void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1174 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001175 SourceLocation Loc = getLocationOfByte(startSpecifier);
1176 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001177 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001178}
1179
Ted Kremenekefaff192010-02-27 01:41:03 +00001180void
Ted Kremenek826a3452010-07-16 02:11:22 +00001181CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1182 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001183 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001184 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1185 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001186}
1187
Ted Kremenek826a3452010-07-16 02:11:22 +00001188void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001189 unsigned posLen) {
1190 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001191 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1192 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001193}
1194
Ted Kremenek826a3452010-07-16 02:11:22 +00001195void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1196 // The presence of a null character is likely an error.
1197 S.Diag(getLocationOfByte(nullCharacter),
1198 diag::warn_printf_format_string_contains_null_char)
1199 << getFormatStringRange();
1200}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001201
Ted Kremenek826a3452010-07-16 02:11:22 +00001202const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1203 return TheCall->getArg(FirstDataArg + i);
1204}
1205
1206void CheckFormatHandler::DoneProcessing() {
1207 // Does the number of data arguments exceed the number of
1208 // format conversions in the format string?
1209 if (!HasVAListArg) {
1210 // Find any arguments that weren't covered.
1211 CoveredArgs.flip();
1212 signed notCoveredArg = CoveredArgs.find_first();
1213 if (notCoveredArg >= 0) {
1214 assert((unsigned)notCoveredArg < NumDataArgs);
1215 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1216 diag::warn_printf_data_arg_not_used)
1217 << getFormatStringRange();
1218 }
1219 }
1220}
1221
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001222bool
1223CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1224 SourceLocation Loc,
1225 const char *startSpec,
1226 unsigned specifierLen,
1227 const char *csStart,
1228 unsigned csLen) {
1229
1230 bool keepGoing = true;
1231 if (argIndex < NumDataArgs) {
1232 // Consider the argument coverered, even though the specifier doesn't
1233 // make sense.
1234 CoveredArgs.set(argIndex);
1235 }
1236 else {
1237 // If argIndex exceeds the number of data arguments we
1238 // don't issue a warning because that is just a cascade of warnings (and
1239 // they may have intended '%%' anyway). We don't want to continue processing
1240 // the format string after this point, however, as we will like just get
1241 // gibberish when trying to match arguments.
1242 keepGoing = false;
1243 }
1244
1245 S.Diag(Loc, diag::warn_format_invalid_conversion)
1246 << llvm::StringRef(csStart, csLen)
1247 << getSpecifierRange(startSpec, specifierLen);
1248
1249 return keepGoing;
1250}
1251
Ted Kremenek666a1972010-07-26 19:45:42 +00001252bool
1253CheckFormatHandler::CheckNumArgs(
1254 const analyze_format_string::FormatSpecifier &FS,
1255 const analyze_format_string::ConversionSpecifier &CS,
1256 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1257
1258 if (argIndex >= NumDataArgs) {
1259 if (FS.usesPositionalArg()) {
1260 S.Diag(getLocationOfByte(CS.getStart()),
1261 diag::warn_printf_positional_arg_exceeds_data_args)
1262 << (argIndex+1) << NumDataArgs
1263 << getSpecifierRange(startSpecifier, specifierLen);
1264 }
1265 else {
1266 S.Diag(getLocationOfByte(CS.getStart()),
1267 diag::warn_printf_insufficient_data_args)
1268 << getSpecifierRange(startSpecifier, specifierLen);
1269 }
1270
1271 return false;
1272 }
1273 return true;
1274}
1275
Ted Kremenek826a3452010-07-16 02:11:22 +00001276//===--- CHECK: Printf format string checking ------------------------------===//
1277
1278namespace {
1279class CheckPrintfHandler : public CheckFormatHandler {
1280public:
1281 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1282 const Expr *origFormatExpr, unsigned firstDataArg,
1283 unsigned numDataArgs, bool isObjCLiteral,
1284 const char *beg, bool hasVAListArg,
1285 const CallExpr *theCall, unsigned formatIdx)
1286 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1287 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1288 theCall, formatIdx) {}
1289
1290
1291 bool HandleInvalidPrintfConversionSpecifier(
1292 const analyze_printf::PrintfSpecifier &FS,
1293 const char *startSpecifier,
1294 unsigned specifierLen);
1295
1296 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1297 const char *startSpecifier,
1298 unsigned specifierLen);
1299
1300 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1301 const char *startSpecifier, unsigned specifierLen);
1302 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1303 const analyze_printf::OptionalAmount &Amt,
1304 unsigned type,
1305 const char *startSpecifier, unsigned specifierLen);
1306 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1307 const analyze_printf::OptionalFlag &flag,
1308 const char *startSpecifier, unsigned specifierLen);
1309 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1310 const analyze_printf::OptionalFlag &ignoredFlag,
1311 const analyze_printf::OptionalFlag &flag,
1312 const char *startSpecifier, unsigned specifierLen);
1313};
1314}
1315
1316bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1317 const analyze_printf::PrintfSpecifier &FS,
1318 const char *startSpecifier,
1319 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001320 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001321 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001322
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001323 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1324 getLocationOfByte(CS.getStart()),
1325 startSpecifier, specifierLen,
1326 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001327}
1328
Ted Kremenek826a3452010-07-16 02:11:22 +00001329bool CheckPrintfHandler::HandleAmount(
1330 const analyze_format_string::OptionalAmount &Amt,
1331 unsigned k, const char *startSpecifier,
1332 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001333
1334 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001335 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001336 unsigned argIndex = Amt.getArgIndex();
1337 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001338 S.Diag(getLocationOfByte(Amt.getStart()),
1339 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001340 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001341 // Don't do any more checking. We will just emit
1342 // spurious errors.
1343 return false;
1344 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001345
Ted Kremenek0d277352010-01-29 01:06:55 +00001346 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001347 // Although not in conformance with C99, we also allow the argument to be
1348 // an 'unsigned int' as that is a reasonably safe case. GCC also
1349 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001350 CoveredArgs.set(argIndex);
1351 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001352 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001353
1354 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1355 assert(ATR.isValid());
1356
1357 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001358 S.Diag(getLocationOfByte(Amt.getStart()),
1359 diag::warn_printf_asterisk_wrong_type)
1360 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001361 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001362 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001363 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001364 // Don't do any more checking. We will just emit
1365 // spurious errors.
1366 return false;
1367 }
1368 }
1369 }
1370 return true;
1371}
Ted Kremenek0d277352010-01-29 01:06:55 +00001372
Tom Caree4ee9662010-06-17 19:00:27 +00001373void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001374 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001375 const analyze_printf::OptionalAmount &Amt,
1376 unsigned type,
1377 const char *startSpecifier,
1378 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001379 const analyze_printf::PrintfConversionSpecifier &CS =
1380 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001381 switch (Amt.getHowSpecified()) {
1382 case analyze_printf::OptionalAmount::Constant:
1383 S.Diag(getLocationOfByte(Amt.getStart()),
1384 diag::warn_printf_nonsensical_optional_amount)
1385 << type
1386 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001387 << getSpecifierRange(startSpecifier, specifierLen)
1388 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001389 Amt.getConstantLength()));
1390 break;
1391
1392 default:
1393 S.Diag(getLocationOfByte(Amt.getStart()),
1394 diag::warn_printf_nonsensical_optional_amount)
1395 << type
1396 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001397 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001398 break;
1399 }
1400}
1401
Ted Kremenek826a3452010-07-16 02:11:22 +00001402void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001403 const analyze_printf::OptionalFlag &flag,
1404 const char *startSpecifier,
1405 unsigned specifierLen) {
1406 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001407 const analyze_printf::PrintfConversionSpecifier &CS =
1408 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001409 S.Diag(getLocationOfByte(flag.getPosition()),
1410 diag::warn_printf_nonsensical_flag)
1411 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001412 << getSpecifierRange(startSpecifier, specifierLen)
1413 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001414}
1415
1416void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001417 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001418 const analyze_printf::OptionalFlag &ignoredFlag,
1419 const analyze_printf::OptionalFlag &flag,
1420 const char *startSpecifier,
1421 unsigned specifierLen) {
1422 // Warn about ignored flag with a fixit removal.
1423 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1424 diag::warn_printf_ignored_flag)
1425 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001426 << getSpecifierRange(startSpecifier, specifierLen)
1427 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001428 ignoredFlag.getPosition(), 1));
1429}
1430
Ted Kremeneke0e53132010-01-28 23:39:18 +00001431bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001432CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001433 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001434 const char *startSpecifier,
1435 unsigned specifierLen) {
1436
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001437 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001438 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001439 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001440
Ted Kremenekbaa40062010-07-19 22:01:06 +00001441 if (FS.consumesDataArgument()) {
1442 if (atFirstArg) {
1443 atFirstArg = false;
1444 usesPositionalArgs = FS.usesPositionalArg();
1445 }
1446 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1447 // Cannot mix-and-match positional and non-positional arguments.
1448 S.Diag(getLocationOfByte(CS.getStart()),
1449 diag::warn_format_mix_positional_nonpositional_args)
1450 << getSpecifierRange(startSpecifier, specifierLen);
1451 return false;
1452 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001453 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001454
Ted Kremenekefaff192010-02-27 01:41:03 +00001455 // First check if the field width, precision, and conversion specifier
1456 // have matching data arguments.
1457 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1458 startSpecifier, specifierLen)) {
1459 return false;
1460 }
1461
1462 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1463 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001464 return false;
1465 }
1466
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001467 if (!CS.consumesDataArgument()) {
1468 // FIXME: Technically specifying a precision or field width here
1469 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001470 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001471 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001472
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001473 // Consume the argument.
1474 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001475 if (argIndex < NumDataArgs) {
1476 // The check to see if the argIndex is valid will come later.
1477 // We set the bit here because we may exit early from this
1478 // function if we encounter some other error.
1479 CoveredArgs.set(argIndex);
1480 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001481
1482 // Check for using an Objective-C specific conversion specifier
1483 // in a non-ObjC literal.
1484 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001485 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1486 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001487 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001488
Tom Caree4ee9662010-06-17 19:00:27 +00001489 // Check for invalid use of field width
1490 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001491 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001492 startSpecifier, specifierLen);
1493 }
1494
1495 // Check for invalid use of precision
1496 if (!FS.hasValidPrecision()) {
1497 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1498 startSpecifier, specifierLen);
1499 }
1500
1501 // Check each flag does not conflict with any other component.
Ted Kremenek65197b42011-01-08 05:28:46 +00001502 if (!FS.hasValidThousandsGroupingPrefix())
1503 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001504 if (!FS.hasValidLeadingZeros())
1505 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1506 if (!FS.hasValidPlusPrefix())
1507 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001508 if (!FS.hasValidSpacePrefix())
1509 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001510 if (!FS.hasValidAlternativeForm())
1511 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1512 if (!FS.hasValidLeftJustified())
1513 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1514
1515 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001516 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1517 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1518 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001519 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1520 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1521 startSpecifier, specifierLen);
1522
1523 // Check the length modifier is valid with the given conversion specifier.
1524 const LengthModifier &LM = FS.getLengthModifier();
1525 if (!FS.hasValidLengthModifier())
1526 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001527 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001528 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001529 << getSpecifierRange(startSpecifier, specifierLen)
1530 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001531 LM.getLength()));
1532
1533 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001534 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001535 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001536 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001537 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001538 // Continue checking the other format specifiers.
1539 return true;
1540 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001541
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001542 // The remaining checks depend on the data arguments.
1543 if (HasVAListArg)
1544 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001545
Ted Kremenek666a1972010-07-26 19:45:42 +00001546 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001547 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001548
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001549 // Now type check the data expression that matches the
1550 // format specifier.
1551 const Expr *Ex = getDataArg(argIndex);
1552 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1553 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1554 // Check if we didn't match because of an implicit cast from a 'char'
1555 // or 'short' to an 'int'. This is done because printf is a varargs
1556 // function.
1557 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001558 if (ICE->getType() == S.Context.IntTy) {
1559 // All further checking is done on the subexpression.
1560 Ex = ICE->getSubExpr();
1561 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001562 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001563 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001564
1565 // We may be able to offer a FixItHint if it is a supported type.
1566 PrintfSpecifier fixedFS = FS;
1567 bool success = fixedFS.fixType(Ex->getType());
1568
1569 if (success) {
1570 // Get the fix string from the fixed format specifier
1571 llvm::SmallString<128> buf;
1572 llvm::raw_svector_ostream os(buf);
1573 fixedFS.toString(os);
1574
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001575 // FIXME: getRepresentativeType() perhaps should return a string
1576 // instead of a QualType to better handle when the representative
1577 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001578 S.Diag(getLocationOfByte(CS.getStart()),
1579 diag::warn_printf_conversion_argument_type_mismatch)
1580 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1581 << getSpecifierRange(startSpecifier, specifierLen)
1582 << Ex->getSourceRange()
1583 << FixItHint::CreateReplacement(
1584 getSpecifierRange(startSpecifier, specifierLen),
1585 os.str());
1586 }
1587 else {
1588 S.Diag(getLocationOfByte(CS.getStart()),
1589 diag::warn_printf_conversion_argument_type_mismatch)
1590 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1591 << getSpecifierRange(startSpecifier, specifierLen)
1592 << Ex->getSourceRange();
1593 }
1594 }
1595
Ted Kremeneke0e53132010-01-28 23:39:18 +00001596 return true;
1597}
1598
Ted Kremenek826a3452010-07-16 02:11:22 +00001599//===--- CHECK: Scanf format string checking ------------------------------===//
1600
1601namespace {
1602class CheckScanfHandler : public CheckFormatHandler {
1603public:
1604 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1605 const Expr *origFormatExpr, unsigned firstDataArg,
1606 unsigned numDataArgs, bool isObjCLiteral,
1607 const char *beg, bool hasVAListArg,
1608 const CallExpr *theCall, unsigned formatIdx)
1609 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1610 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1611 theCall, formatIdx) {}
1612
1613 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1614 const char *startSpecifier,
1615 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001616
1617 bool HandleInvalidScanfConversionSpecifier(
1618 const analyze_scanf::ScanfSpecifier &FS,
1619 const char *startSpecifier,
1620 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001621
1622 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001623};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001624}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001625
Ted Kremenekb7c21012010-07-16 18:28:03 +00001626void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1627 const char *end) {
1628 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1629 << getSpecifierRange(start, end - start);
1630}
1631
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001632bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1633 const analyze_scanf::ScanfSpecifier &FS,
1634 const char *startSpecifier,
1635 unsigned specifierLen) {
1636
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001637 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001638 FS.getConversionSpecifier();
1639
1640 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1641 getLocationOfByte(CS.getStart()),
1642 startSpecifier, specifierLen,
1643 CS.getStart(), CS.getLength());
1644}
1645
Ted Kremenek826a3452010-07-16 02:11:22 +00001646bool CheckScanfHandler::HandleScanfSpecifier(
1647 const analyze_scanf::ScanfSpecifier &FS,
1648 const char *startSpecifier,
1649 unsigned specifierLen) {
1650
1651 using namespace analyze_scanf;
1652 using namespace analyze_format_string;
1653
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001654 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001655
Ted Kremenekbaa40062010-07-19 22:01:06 +00001656 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1657 // be used to decide if we are using positional arguments consistently.
1658 if (FS.consumesDataArgument()) {
1659 if (atFirstArg) {
1660 atFirstArg = false;
1661 usesPositionalArgs = FS.usesPositionalArg();
1662 }
1663 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1664 // Cannot mix-and-match positional and non-positional arguments.
1665 S.Diag(getLocationOfByte(CS.getStart()),
1666 diag::warn_format_mix_positional_nonpositional_args)
1667 << getSpecifierRange(startSpecifier, specifierLen);
1668 return false;
1669 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001670 }
1671
1672 // Check if the field with is non-zero.
1673 const OptionalAmount &Amt = FS.getFieldWidth();
1674 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1675 if (Amt.getConstantAmount() == 0) {
1676 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1677 Amt.getConstantLength());
1678 S.Diag(getLocationOfByte(Amt.getStart()),
1679 diag::warn_scanf_nonzero_width)
1680 << R << FixItHint::CreateRemoval(R);
1681 }
1682 }
1683
1684 if (!FS.consumesDataArgument()) {
1685 // FIXME: Technically specifying a precision or field width here
1686 // makes no sense. Worth issuing a warning at some point.
1687 return true;
1688 }
1689
1690 // Consume the argument.
1691 unsigned argIndex = FS.getArgIndex();
1692 if (argIndex < NumDataArgs) {
1693 // The check to see if the argIndex is valid will come later.
1694 // We set the bit here because we may exit early from this
1695 // function if we encounter some other error.
1696 CoveredArgs.set(argIndex);
1697 }
1698
Ted Kremenek1e51c202010-07-20 20:04:47 +00001699 // Check the length modifier is valid with the given conversion specifier.
1700 const LengthModifier &LM = FS.getLengthModifier();
1701 if (!FS.hasValidLengthModifier()) {
1702 S.Diag(getLocationOfByte(LM.getStart()),
1703 diag::warn_format_nonsensical_length)
1704 << LM.toString() << CS.toString()
1705 << getSpecifierRange(startSpecifier, specifierLen)
1706 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1707 LM.getLength()));
1708 }
1709
Ted Kremenek826a3452010-07-16 02:11:22 +00001710 // The remaining checks depend on the data arguments.
1711 if (HasVAListArg)
1712 return true;
1713
Ted Kremenek666a1972010-07-26 19:45:42 +00001714 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001715 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001716
1717 // FIXME: Check that the argument type matches the format specifier.
1718
1719 return true;
1720}
1721
1722void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001723 const Expr *OrigFormatExpr,
1724 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001725 unsigned format_idx, unsigned firstDataArg,
1726 bool isPrintf) {
1727
Ted Kremeneke0e53132010-01-28 23:39:18 +00001728 // CHECK: is the format string a wide literal?
1729 if (FExpr->isWide()) {
1730 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001731 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001732 << OrigFormatExpr->getSourceRange();
1733 return;
1734 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001735
Ted Kremeneke0e53132010-01-28 23:39:18 +00001736 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001737 llvm::StringRef StrRef = FExpr->getString();
1738 const char *Str = StrRef.data();
1739 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001740
Ted Kremeneke0e53132010-01-28 23:39:18 +00001741 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001742 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001743 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001744 << OrigFormatExpr->getSourceRange();
1745 return;
1746 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001747
1748 if (isPrintf) {
1749 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1750 TheCall->getNumArgs() - firstDataArg,
1751 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1752 HasVAListArg, TheCall, format_idx);
1753
1754 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1755 H.DoneProcessing();
1756 }
1757 else {
1758 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1759 TheCall->getNumArgs() - firstDataArg,
1760 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1761 HasVAListArg, TheCall, format_idx);
1762
1763 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1764 H.DoneProcessing();
1765 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001766}
1767
Ted Kremenek06de2762007-08-17 16:46:58 +00001768//===--- CHECK: Return Address of Stack Variable --------------------------===//
1769
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001770static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1771static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00001772
1773/// CheckReturnStackAddr - Check if a return statement returns the address
1774/// of a stack variable.
1775void
1776Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1777 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001779 Expr *stackE = 0;
1780 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1781
1782 // Perform checking for returned stack addresses, local blocks,
1783 // label addresses or references to temporaries.
Steve Naroffdd972f22008-09-05 22:11:13 +00001784 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001785 stackE = EvalAddr(RetValExp, refVars);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001786 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001787 stackE = EvalVal(RetValExp, refVars);
1788 }
1789
1790 if (stackE == 0)
1791 return; // Nothing suspicious was found.
1792
1793 SourceLocation diagLoc;
1794 SourceRange diagRange;
1795 if (refVars.empty()) {
1796 diagLoc = stackE->getLocStart();
1797 diagRange = stackE->getSourceRange();
1798 } else {
1799 // We followed through a reference variable. 'stackE' contains the
1800 // problematic expression but we will warn at the return statement pointing
1801 // at the reference variable. We will later display the "trail" of
1802 // reference variables using notes.
1803 diagLoc = refVars[0]->getLocStart();
1804 diagRange = refVars[0]->getSourceRange();
1805 }
1806
1807 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1808 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1809 : diag::warn_ret_stack_addr)
1810 << DR->getDecl()->getDeclName() << diagRange;
1811 } else if (isa<BlockExpr>(stackE)) { // local block.
1812 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1813 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1814 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1815 } else { // local temporary.
1816 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1817 : diag::warn_ret_local_temp_addr)
1818 << diagRange;
1819 }
1820
1821 // Display the "trail" of reference variables that we followed until we
1822 // found the problematic expression using notes.
1823 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1824 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1825 // If this var binds to another reference var, show the range of the next
1826 // var, otherwise the var binds to the problematic expression, in which case
1827 // show the range of the expression.
1828 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1829 : stackE->getSourceRange();
1830 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1831 << VD->getDeclName() << range;
Ted Kremenek06de2762007-08-17 16:46:58 +00001832 }
1833}
1834
1835/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1836/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001837/// to a location on the stack, a local block, an address of a label, or a
1838/// reference to local temporary. The recursion is used to traverse the
Ted Kremenek06de2762007-08-17 16:46:58 +00001839/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001840/// encounter a subexpression that (1) clearly does not lead to one of the
1841/// above problematic expressions (2) is something we cannot determine leads to
1842/// a problematic expression based on such local checking.
1843///
1844/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1845/// the expression that they point to. Such variables are added to the
1846/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenek06de2762007-08-17 16:46:58 +00001847///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001848/// EvalAddr processes expressions that are pointers that are used as
1849/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001850/// At the base case of the recursion is a check for the above problematic
1851/// expressions.
Ted Kremenek06de2762007-08-17 16:46:58 +00001852///
1853/// This implementation handles:
1854///
1855/// * pointer-to-pointer casts
1856/// * implicit conversions from array references to pointers
1857/// * taking the address of fields
1858/// * arbitrary interplay between "&" and "*" operators
1859/// * pointer arithmetic from an address of a stack variable
1860/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001861static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1862 if (E->isTypeDependent())
1863 return NULL;
1864
Ted Kremenek06de2762007-08-17 16:46:58 +00001865 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001866 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001867 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001868 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001869 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Ted Kremenek06de2762007-08-17 16:46:58 +00001871 // Our "symbolic interpreter" is just a dispatch off the currently
1872 // viewed AST node. We then recursively traverse the AST by calling
1873 // EvalAddr and EvalVal appropriately.
1874 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001875 case Stmt::ParenExprClass:
1876 // Ignore parentheses.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001877 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1878
1879 case Stmt::DeclRefExprClass: {
1880 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1881
1882 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1883 // If this is a reference variable, follow through to the expression that
1884 // it points to.
1885 if (V->hasLocalStorage() &&
1886 V->getType()->isReferenceType() && V->hasInit()) {
1887 // Add the reference variable to the "trail".
1888 refVars.push_back(DR);
1889 return EvalAddr(V->getInit(), refVars);
1890 }
1891
1892 return NULL;
1893 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001894
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001895 case Stmt::UnaryOperatorClass: {
1896 // The only unary operator that make sense to handle here
1897 // is AddrOf. All others don't make sense as pointers.
1898 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001899
John McCall2de56d12010-08-25 11:45:40 +00001900 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001901 return EvalVal(U->getSubExpr(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001902 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001903 return NULL;
1904 }
Mike Stump1eb44332009-09-09 15:08:12 +00001905
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001906 case Stmt::BinaryOperatorClass: {
1907 // Handle pointer arithmetic. All other binary operators are not valid
1908 // in this context.
1909 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001910 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
John McCall2de56d12010-08-25 11:45:40 +00001912 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001913 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001915 Expr *Base = B->getLHS();
1916
1917 // Determine which argument is the real pointer base. It could be
1918 // the RHS argument instead of the LHS.
1919 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001921 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001922 return EvalAddr(Base, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001923 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001924
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001925 // For conditional operators we need to see if either the LHS or RHS are
1926 // valid DeclRefExpr*s. If one of them is valid, we return it.
1927 case Stmt::ConditionalOperatorClass: {
1928 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001930 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001931 if (Expr *lhsExpr = C->getLHS()) {
1932 // In C++, we can have a throw-expression, which has 'void' type.
1933 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001934 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001935 return LHS;
1936 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001937
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001938 // In C++, we can have a throw-expression, which has 'void' type.
1939 if (C->getRHS()->getType()->isVoidType())
1940 return NULL;
1941
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001942 return EvalAddr(C->getRHS(), refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001943 }
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001944
1945 case Stmt::BlockExprClass:
John McCall469a1eb2011-02-02 13:00:07 +00001946 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001947 return E; // local block.
1948 return NULL;
1949
1950 case Stmt::AddrLabelExprClass:
1951 return E; // address of label.
Mike Stump1eb44332009-09-09 15:08:12 +00001952
Ted Kremenek54b52742008-08-07 00:49:01 +00001953 // For casts, we need to handle conversions from arrays to
1954 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001955 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001956 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001957 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001958 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001959 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001960
Steve Naroffdd972f22008-09-05 22:11:13 +00001961 if (SubExpr->getType()->isPointerType() ||
1962 SubExpr->getType()->isBlockPointerType() ||
1963 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001964 return EvalAddr(SubExpr, refVars);
Ted Kremenek54b52742008-08-07 00:49:01 +00001965 else if (T->isArrayType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001966 return EvalVal(SubExpr, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001967 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001968 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001969 }
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001971 // C++ casts. For dynamic casts, static casts, and const casts, we
1972 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001973 // through the cast. In the case the dynamic cast doesn't fail (and
1974 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001975 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001976 // FIXME: The comment about is wrong; we're not always converting
1977 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001978 // handle references to objects.
1979 case Stmt::CXXStaticCastExprClass:
1980 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001981 case Stmt::CXXConstCastExprClass:
1982 case Stmt::CXXReinterpretCastExprClass: {
1983 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001984 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001985 return EvalAddr(S, refVars);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001986 else
1987 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001990 // Everything else: we simply don't reason about them.
1991 default:
1992 return NULL;
1993 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001994}
Mike Stump1eb44332009-09-09 15:08:12 +00001995
Ted Kremenek06de2762007-08-17 16:46:58 +00001996
1997/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1998/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00001999static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002000do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00002001 // We should only be called for evaluating non-pointer expressions, or
2002 // expressions with a pointer type that are not used as references but instead
2003 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00002004
Ted Kremenek06de2762007-08-17 16:46:58 +00002005 // Our "symbolic interpreter" is just a dispatch off the currently
2006 // viewed AST node. We then recursively traverse the AST by calling
2007 // EvalAddr and EvalVal appropriately.
2008 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002009 case Stmt::ImplicitCastExprClass: {
2010 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00002011 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00002012 E = IE->getSubExpr();
2013 continue;
2014 }
2015 return NULL;
2016 }
2017
Douglas Gregora2813ce2009-10-23 18:54:35 +00002018 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002019 // When we hit a DeclRefExpr we are looking at code that refers to a
2020 // variable's name. If it's not a reference variable we check if it has
2021 // local storage within the function, and if so, return the expression.
Ted Kremenek06de2762007-08-17 16:46:58 +00002022 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002023
Ted Kremenek06de2762007-08-17 16:46:58 +00002024 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002025 if (V->hasLocalStorage()) {
2026 if (!V->getType()->isReferenceType())
2027 return DR;
2028
2029 // Reference variable, follow through to the expression that
2030 // it points to.
2031 if (V->hasInit()) {
2032 // Add the reference variable to the "trail".
2033 refVars.push_back(DR);
2034 return EvalVal(V->getInit(), refVars);
2035 }
2036 }
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Ted Kremenek06de2762007-08-17 16:46:58 +00002038 return NULL;
2039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Ted Kremenek68957a92010-08-04 20:01:07 +00002041 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002042 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00002043 E = cast<ParenExpr>(E)->getSubExpr();
2044 continue;
2045 }
Mike Stump1eb44332009-09-09 15:08:12 +00002046
Ted Kremenek06de2762007-08-17 16:46:58 +00002047 case Stmt::UnaryOperatorClass: {
2048 // The only unary operator that make sense to handle here
2049 // is Deref. All others don't resolve to a "name." This includes
2050 // handling all sorts of rvalues passed to a unary operator.
2051 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002052
John McCall2de56d12010-08-25 11:45:40 +00002053 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002054 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002055
2056 return NULL;
2057 }
Mike Stump1eb44332009-09-09 15:08:12 +00002058
Ted Kremenek06de2762007-08-17 16:46:58 +00002059 case Stmt::ArraySubscriptExprClass: {
2060 // Array subscripts are potential references to data on the stack. We
2061 // retrieve the DeclRefExpr* for the array variable if it indeed
2062 // has local storage.
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002063 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002064 }
Mike Stump1eb44332009-09-09 15:08:12 +00002065
Ted Kremenek06de2762007-08-17 16:46:58 +00002066 case Stmt::ConditionalOperatorClass: {
2067 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002068 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenek06de2762007-08-17 16:46:58 +00002069 ConditionalOperator *C = cast<ConditionalOperator>(E);
2070
Anders Carlsson39073232007-11-30 19:04:31 +00002071 // Handle the GNU extension for missing LHS.
2072 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002073 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson39073232007-11-30 19:04:31 +00002074 return LHS;
2075
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002076 return EvalVal(C->getRHS(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002077 }
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Ted Kremenek06de2762007-08-17 16:46:58 +00002079 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00002080 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002081 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Ted Kremenek06de2762007-08-17 16:46:58 +00002083 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002084 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002085 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002086
2087 // Check whether the member type is itself a reference, in which case
2088 // we're not going to refer to the member, but to what the member refers to.
2089 if (M->getMemberDecl()->getType()->isReferenceType())
2090 return NULL;
2091
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002092 return EvalVal(M->getBase(), refVars);
Ted Kremenek06de2762007-08-17 16:46:58 +00002093 }
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Ted Kremenek06de2762007-08-17 16:46:58 +00002095 default:
Argyrios Kyrtzidis26e10be2010-11-30 22:57:32 +00002096 // Check that we don't return or take the address of a reference to a
2097 // temporary. This is only useful in C++.
2098 if (!E->isTypeDependent() && E->isRValue())
2099 return E;
2100
2101 // Everything else: we simply don't reason about them.
Ted Kremenek06de2762007-08-17 16:46:58 +00002102 return NULL;
2103 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002104} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002105}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002106
2107//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2108
2109/// Check for comparisons of floating point operands using != and ==.
2110/// Issue a warning if these are no self-comparisons, as they are not likely
2111/// to do what the programmer intended.
2112void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2113 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002114
John McCallf6a16482010-12-04 03:47:34 +00002115 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2116 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002117
2118 // Special case: check for x == x (which is OK).
2119 // Do not emit warnings for such cases.
2120 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2121 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2122 if (DRL->getDecl() == DRR->getDecl())
2123 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
2125
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002126 // Special case: check for comparisons against literals that can be exactly
2127 // represented by APFloat. In such cases, do not emit a warning. This
2128 // is a heuristic: often comparison against such literals are used to
2129 // detect if a value in a variable has not changed. This clearly can
2130 // lead to false negatives.
2131 if (EmitWarning) {
2132 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2133 if (FLL->isExact())
2134 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002135 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002136 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2137 if (FLR->isExact())
2138 EmitWarning = false;
2139 }
2140 }
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002142 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002143 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002144 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002145 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002146 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Sebastian Redl0eb23302009-01-19 00:08:26 +00002148 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002149 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002150 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002151 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002153 // Emit the diagnostic.
2154 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002155 Diag(loc, diag::warn_floatingpoint_eq)
2156 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002157}
John McCallba26e582010-01-04 23:21:16 +00002158
John McCallf2370c92010-01-06 05:24:50 +00002159//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2160//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002161
John McCallf2370c92010-01-06 05:24:50 +00002162namespace {
John McCallba26e582010-01-04 23:21:16 +00002163
John McCallf2370c92010-01-06 05:24:50 +00002164/// Structure recording the 'active' range of an integer-valued
2165/// expression.
2166struct IntRange {
2167 /// The number of bits active in the int.
2168 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002169
John McCallf2370c92010-01-06 05:24:50 +00002170 /// True if the int is known not to have negative values.
2171 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002172
John McCallf2370c92010-01-06 05:24:50 +00002173 IntRange(unsigned Width, bool NonNegative)
2174 : Width(Width), NonNegative(NonNegative)
2175 {}
John McCallba26e582010-01-04 23:21:16 +00002176
John McCall1844a6e2010-11-10 23:38:19 +00002177 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002178 static IntRange forBoolType() {
2179 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002180 }
2181
John McCall1844a6e2010-11-10 23:38:19 +00002182 /// Returns the range of an opaque value of the given integral type.
2183 static IntRange forValueOfType(ASTContext &C, QualType T) {
2184 return forValueOfCanonicalType(C,
2185 T->getCanonicalTypeInternal().getTypePtr());
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 a canonical integral type.
2189 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002190 assert(T->isCanonicalUnqualified());
2191
2192 if (const VectorType *VT = dyn_cast<VectorType>(T))
2193 T = VT->getElementType().getTypePtr();
2194 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2195 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002196
John McCall091f23f2010-11-09 22:22:12 +00002197 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002198 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2199 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002200 if (!Enum->isDefinition())
2201 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2202
John McCall323ed742010-05-06 08:58:33 +00002203 unsigned NumPositive = Enum->getNumPositiveBits();
2204 unsigned NumNegative = Enum->getNumNegativeBits();
2205
2206 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2207 }
John McCallf2370c92010-01-06 05:24:50 +00002208
2209 const BuiltinType *BT = cast<BuiltinType>(T);
2210 assert(BT->isInteger());
2211
2212 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2213 }
2214
John McCall1844a6e2010-11-10 23:38:19 +00002215 /// Returns the "target" range of a canonical integral type, i.e.
2216 /// the range of values expressible in the type.
2217 ///
2218 /// This matches forValueOfCanonicalType except that enums have the
2219 /// full range of their type, not the range of their enumerators.
2220 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2221 assert(T->isCanonicalUnqualified());
2222
2223 if (const VectorType *VT = dyn_cast<VectorType>(T))
2224 T = VT->getElementType().getTypePtr();
2225 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2226 T = CT->getElementType().getTypePtr();
2227 if (const EnumType *ET = dyn_cast<EnumType>(T))
2228 T = ET->getDecl()->getIntegerType().getTypePtr();
2229
2230 const BuiltinType *BT = cast<BuiltinType>(T);
2231 assert(BT->isInteger());
2232
2233 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2234 }
2235
2236 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002237 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002238 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002239 L.NonNegative && R.NonNegative);
2240 }
2241
John McCall1844a6e2010-11-10 23:38:19 +00002242 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002243 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002244 return IntRange(std::min(L.Width, R.Width),
2245 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002246 }
2247};
2248
2249IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2250 if (value.isSigned() && value.isNegative())
2251 return IntRange(value.getMinSignedBits(), false);
2252
2253 if (value.getBitWidth() > MaxWidth)
Jay Foad9f71a8f2010-12-07 08:25:34 +00002254 value = value.trunc(MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002255
2256 // isNonNegative() just checks the sign bit without considering
2257 // signedness.
2258 return IntRange(value.getActiveBits(), true);
2259}
2260
John McCall0acc3112010-01-06 22:57:21 +00002261IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002262 unsigned MaxWidth) {
2263 if (result.isInt())
2264 return GetValueRange(C, result.getInt(), MaxWidth);
2265
2266 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002267 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2268 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2269 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2270 R = IntRange::join(R, El);
2271 }
John McCallf2370c92010-01-06 05:24:50 +00002272 return R;
2273 }
2274
2275 if (result.isComplexInt()) {
2276 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2277 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2278 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002279 }
2280
2281 // This can happen with lossless casts to intptr_t of "based" lvalues.
2282 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002283 // FIXME: The only reason we need to pass the type in here is to get
2284 // the sign right on this one case. It would be nice if APValue
2285 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002286 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002287 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002288}
John McCallf2370c92010-01-06 05:24:50 +00002289
2290/// Pseudo-evaluate the given integer expression, estimating the
2291/// range of values it might take.
2292///
2293/// \param MaxWidth - the width to which the value will be truncated
2294IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2295 E = E->IgnoreParens();
2296
2297 // Try a full evaluation first.
2298 Expr::EvalResult result;
2299 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002300 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002301
2302 // I think we only want to look through implicit casts here; if the
2303 // user has an explicit widening cast, we should treat the value as
2304 // being of the new, wider type.
2305 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002306 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002307 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2308
John McCall1844a6e2010-11-10 23:38:19 +00002309 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002310
John McCall2de56d12010-08-25 11:45:40 +00002311 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002312
John McCallf2370c92010-01-06 05:24:50 +00002313 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002314 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002315 return OutputTypeRange;
2316
2317 IntRange SubRange
2318 = GetExprRange(C, CE->getSubExpr(),
2319 std::min(MaxWidth, OutputTypeRange.Width));
2320
2321 // Bail out if the subexpr's range is as wide as the cast type.
2322 if (SubRange.Width >= OutputTypeRange.Width)
2323 return OutputTypeRange;
2324
2325 // Otherwise, we take the smaller width, and we're non-negative if
2326 // either the output type or the subexpr is.
2327 return IntRange(SubRange.Width,
2328 SubRange.NonNegative || OutputTypeRange.NonNegative);
2329 }
2330
2331 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2332 // If we can fold the condition, just take that operand.
2333 bool CondResult;
2334 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2335 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2336 : CO->getFalseExpr(),
2337 MaxWidth);
2338
2339 // Otherwise, conservatively merge.
2340 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2341 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2342 return IntRange::join(L, R);
2343 }
2344
2345 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2346 switch (BO->getOpcode()) {
2347
2348 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002349 case BO_LAnd:
2350 case BO_LOr:
2351 case BO_LT:
2352 case BO_GT:
2353 case BO_LE:
2354 case BO_GE:
2355 case BO_EQ:
2356 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002357 return IntRange::forBoolType();
2358
John McCallc0cd21d2010-02-23 19:22:29 +00002359 // The type of these compound assignments is the type of the LHS,
2360 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002361 case BO_MulAssign:
2362 case BO_DivAssign:
2363 case BO_RemAssign:
2364 case BO_AddAssign:
2365 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002366 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002367
John McCallf2370c92010-01-06 05:24:50 +00002368 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002369 case BO_PtrMemD:
2370 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002371 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002372
John McCall60fad452010-01-06 22:07:33 +00002373 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002374 case BO_And:
2375 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002376 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2377 GetExprRange(C, BO->getRHS(), MaxWidth));
2378
John McCallf2370c92010-01-06 05:24:50 +00002379 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002380 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002381 // ...except that we want to treat '1 << (blah)' as logically
2382 // positive. It's an important idiom.
2383 if (IntegerLiteral *I
2384 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2385 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002386 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002387 return IntRange(R.Width, /*NonNegative*/ true);
2388 }
2389 }
2390 // fallthrough
2391
John McCall2de56d12010-08-25 11:45:40 +00002392 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002393 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002394
John McCall60fad452010-01-06 22:07:33 +00002395 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002396 case BO_Shr:
2397 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002398 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2399
2400 // If the shift amount is a positive constant, drop the width by
2401 // that much.
2402 llvm::APSInt shift;
2403 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2404 shift.isNonNegative()) {
2405 unsigned zext = shift.getZExtValue();
2406 if (zext >= L.Width)
2407 L.Width = (L.NonNegative ? 0 : 1);
2408 else
2409 L.Width -= zext;
2410 }
2411
2412 return L;
2413 }
2414
2415 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002416 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002417 return GetExprRange(C, BO->getRHS(), MaxWidth);
2418
John McCall60fad452010-01-06 22:07:33 +00002419 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002420 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002421 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002422 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002423 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002424
John McCallf2370c92010-01-06 05:24:50 +00002425 default:
2426 break;
2427 }
2428
2429 // Treat every other operator as if it were closed on the
2430 // narrowest type that encompasses both operands.
2431 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2432 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2433 return IntRange::join(L, R);
2434 }
2435
2436 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2437 switch (UO->getOpcode()) {
2438 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002439 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002440 return IntRange::forBoolType();
2441
2442 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002443 case UO_Deref:
2444 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002445 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002446
2447 default:
2448 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2449 }
2450 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002451
2452 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002453 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002454 }
John McCallf2370c92010-01-06 05:24:50 +00002455
2456 FieldDecl *BitField = E->getBitField();
2457 if (BitField) {
2458 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2459 unsigned BitWidth = BitWidthAP.getZExtValue();
2460
2461 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2462 }
2463
John McCall1844a6e2010-11-10 23:38:19 +00002464 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002465}
John McCall51313c32010-01-04 23:31:57 +00002466
John McCall323ed742010-05-06 08:58:33 +00002467IntRange GetExprRange(ASTContext &C, Expr *E) {
2468 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2469}
2470
John McCall51313c32010-01-04 23:31:57 +00002471/// Checks whether the given value, which currently has the given
2472/// source semantics, has the same value when coerced through the
2473/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002474bool IsSameFloatAfterCast(const llvm::APFloat &value,
2475 const llvm::fltSemantics &Src,
2476 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002477 llvm::APFloat truncated = value;
2478
2479 bool ignored;
2480 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2481 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2482
2483 return truncated.bitwiseIsEqual(value);
2484}
2485
2486/// Checks whether the given value, which currently has the given
2487/// source semantics, has the same value when coerced through the
2488/// target semantics.
2489///
2490/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002491bool IsSameFloatAfterCast(const APValue &value,
2492 const llvm::fltSemantics &Src,
2493 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002494 if (value.isFloat())
2495 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2496
2497 if (value.isVector()) {
2498 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2499 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2500 return false;
2501 return true;
2502 }
2503
2504 assert(value.isComplexFloat());
2505 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2506 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2507}
2508
John McCallb4eb64d2010-10-08 02:01:28 +00002509void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002510
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002511static bool IsZero(Sema &S, Expr *E) {
2512 // Suppress cases where we are comparing against an enum constant.
2513 if (const DeclRefExpr *DR =
2514 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2515 if (isa<EnumConstantDecl>(DR->getDecl()))
2516 return false;
2517
2518 // Suppress cases where the '0' value is expanded from a macro.
2519 if (E->getLocStart().isMacroID())
2520 return false;
2521
John McCall323ed742010-05-06 08:58:33 +00002522 llvm::APSInt Value;
2523 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2524}
2525
John McCall372e1032010-10-06 00:25:24 +00002526static bool HasEnumType(Expr *E) {
2527 // Strip off implicit integral promotions.
2528 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002529 if (ICE->getCastKind() != CK_IntegralCast &&
2530 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002531 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002532 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002533 }
2534
2535 return E->getType()->isEnumeralType();
2536}
2537
John McCall323ed742010-05-06 08:58:33 +00002538void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002539 BinaryOperatorKind op = E->getOpcode();
Douglas Gregor14af91a2010-12-21 07:22:56 +00002540 if (E->isValueDependent())
2541 return;
2542
John McCall2de56d12010-08-25 11:45:40 +00002543 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002544 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002545 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002546 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002547 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002548 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002549 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002550 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002551 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002552 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002553 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002554 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002555 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002556 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002557 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002558 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2559 }
2560}
2561
2562/// Analyze the operands of the given comparison. Implements the
2563/// fallback case from AnalyzeComparison.
2564void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002565 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2566 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002567}
John McCall51313c32010-01-04 23:31:57 +00002568
John McCallba26e582010-01-04 23:21:16 +00002569/// \brief Implements -Wsign-compare.
2570///
2571/// \param lex the left-hand expression
2572/// \param rex the right-hand expression
2573/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002574/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002575void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2576 // The type the comparison is being performed in.
2577 QualType T = E->getLHS()->getType();
2578 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2579 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002580
John McCall323ed742010-05-06 08:58:33 +00002581 // We don't do anything special if this isn't an unsigned integral
2582 // comparison: we're only interested in integral comparisons, and
2583 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor3e026e32011-02-19 22:34:59 +00002584 //
2585 // We also don't care about value-dependent expressions or expressions
2586 // whose result is a constant.
2587 if (!T->hasUnsignedIntegerRepresentation()
2588 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCall323ed742010-05-06 08:58:33 +00002589 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002590
John McCall323ed742010-05-06 08:58:33 +00002591 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2592 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002593
John McCall323ed742010-05-06 08:58:33 +00002594 // Check to see if one of the (unmodified) operands is of different
2595 // signedness.
2596 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002597 if (lex->getType()->hasSignedIntegerRepresentation()) {
2598 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002599 "unsigned comparison between two signed integer expressions?");
2600 signedOperand = lex;
2601 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002602 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002603 signedOperand = rex;
2604 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002605 } else {
John McCall323ed742010-05-06 08:58:33 +00002606 CheckTrivialUnsignedComparison(S, E);
2607 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002608 }
2609
John McCall323ed742010-05-06 08:58:33 +00002610 // Otherwise, calculate the effective range of the signed operand.
2611 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002612
John McCall323ed742010-05-06 08:58:33 +00002613 // Go ahead and analyze implicit conversions in the operands. Note
2614 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002615 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2616 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002617
John McCall323ed742010-05-06 08:58:33 +00002618 // If the signed range is non-negative, -Wsign-compare won't fire,
2619 // but we should still check for comparisons which are always true
2620 // or false.
2621 if (signedRange.NonNegative)
2622 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002623
2624 // For (in)equality comparisons, if the unsigned operand is a
2625 // constant which cannot collide with a overflowed signed operand,
2626 // then reinterpreting the signed operand as unsigned will not
2627 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002628 if (E->isEqualityOp()) {
2629 unsigned comparisonWidth = S.Context.getIntWidth(T);
2630 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002631
John McCall323ed742010-05-06 08:58:33 +00002632 // We should never be unable to prove that the unsigned operand is
2633 // non-negative.
2634 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2635
2636 if (unsignedRange.Width < comparisonWidth)
2637 return;
2638 }
2639
2640 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2641 << lex->getType() << rex->getType()
2642 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002643}
2644
John McCall15d7d122010-11-11 03:21:53 +00002645/// Analyzes an attempt to assign the given value to a bitfield.
2646///
2647/// Returns true if there was something fishy about the attempt.
2648bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2649 SourceLocation InitLoc) {
2650 assert(Bitfield->isBitField());
2651 if (Bitfield->isInvalidDecl())
2652 return false;
2653
John McCall91b60142010-11-11 05:33:51 +00002654 // White-list bool bitfields.
2655 if (Bitfield->getType()->isBooleanType())
2656 return false;
2657
Douglas Gregor46ff3032011-02-04 13:09:01 +00002658 // Ignore value- or type-dependent expressions.
2659 if (Bitfield->getBitWidth()->isValueDependent() ||
2660 Bitfield->getBitWidth()->isTypeDependent() ||
2661 Init->isValueDependent() ||
2662 Init->isTypeDependent())
2663 return false;
2664
John McCall15d7d122010-11-11 03:21:53 +00002665 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2666
2667 llvm::APSInt Width(32);
2668 Expr::EvalResult InitValue;
2669 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002670 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002671 !InitValue.Val.isInt())
2672 return false;
2673
2674 const llvm::APSInt &Value = InitValue.Val.getInt();
2675 unsigned OriginalWidth = Value.getBitWidth();
2676 unsigned FieldWidth = Width.getZExtValue();
2677
2678 if (OriginalWidth <= FieldWidth)
2679 return false;
2680
Jay Foad9f71a8f2010-12-07 08:25:34 +00002681 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall15d7d122010-11-11 03:21:53 +00002682
2683 // It's fairly common to write values into signed bitfields
2684 // that, if sign-extended, would end up becoming a different
2685 // value. We don't want to warn about that.
2686 if (Value.isSigned() && Value.isNegative())
Jay Foad9f71a8f2010-12-07 08:25:34 +00002687 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002688 else
Jay Foad9f71a8f2010-12-07 08:25:34 +00002689 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall15d7d122010-11-11 03:21:53 +00002690
2691 if (Value == TruncatedValue)
2692 return false;
2693
2694 std::string PrettyValue = Value.toString(10);
2695 std::string PrettyTrunc = TruncatedValue.toString(10);
2696
2697 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2698 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2699 << Init->getSourceRange();
2700
2701 return true;
2702}
2703
John McCallbeb22aa2010-11-09 23:24:47 +00002704/// Analyze the given simple or compound assignment for warning-worthy
2705/// operations.
2706void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2707 // Just recurse on the LHS.
2708 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2709
2710 // We want to recurse on the RHS as normal unless we're assigning to
2711 // a bitfield.
2712 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002713 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2714 E->getOperatorLoc())) {
2715 // Recurse, ignoring any implicit conversions on the RHS.
2716 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2717 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002718 }
2719 }
2720
2721 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2722}
2723
John McCall51313c32010-01-04 23:31:57 +00002724/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002725void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2726 unsigned diag) {
2727 S.Diag(E->getExprLoc(), diag)
2728 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002729}
2730
John McCall091f23f2010-11-09 22:22:12 +00002731std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2732 if (!Range.Width) return "0";
2733
2734 llvm::APSInt ValueInRange = Value;
2735 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad9f71a8f2010-12-07 08:25:34 +00002736 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall091f23f2010-11-09 22:22:12 +00002737 return ValueInRange.toString(10);
2738}
2739
John McCall323ed742010-05-06 08:58:33 +00002740void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002741 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002742 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002743
John McCall323ed742010-05-06 08:58:33 +00002744 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2745 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2746 if (Source == Target) return;
2747 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002748
John McCallb4eb64d2010-10-08 02:01:28 +00002749 // If the conversion context location is invalid or instantiated
2750 // from a system macro, don't complain.
2751 if (CC.isInvalid() ||
2752 (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2753 S.Context.getSourceManager().getSpellingLoc(CC))))
2754 return;
2755
John McCall51313c32010-01-04 23:31:57 +00002756 // Never diagnose implicit casts to bool.
2757 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2758 return;
2759
2760 // Strip vector types.
2761 if (isa<VectorType>(Source)) {
2762 if (!isa<VectorType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002763 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002764
2765 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2766 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2767 }
2768
2769 // Strip complex types.
2770 if (isa<ComplexType>(Source)) {
2771 if (!isa<ComplexType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002772 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002773
2774 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2775 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2776 }
2777
2778 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2779 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2780
2781 // If the source is floating point...
2782 if (SourceBT && SourceBT->isFloatingPoint()) {
2783 // ...and the target is floating point...
2784 if (TargetBT && TargetBT->isFloatingPoint()) {
2785 // ...then warn if we're dropping FP rank.
2786
2787 // Builtin FP kinds are ordered by increasing FP rank.
2788 if (SourceBT->getKind() > TargetBT->getKind()) {
2789 // Don't warn about float constants that are precisely
2790 // representable in the target type.
2791 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002792 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002793 // Value might be a float, a float vector, or a float complex.
2794 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002795 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2796 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002797 return;
2798 }
2799
John McCallb4eb64d2010-10-08 02:01:28 +00002800 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002801 }
2802 return;
2803 }
2804
2805 // If the target is integral, always warn.
Chandler Carrutha5b93322011-02-17 11:05:49 +00002806 if ((TargetBT && TargetBT->isInteger())) {
2807 Expr *InnerE = E->IgnoreParenImpCasts();
2808 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2809 DiagnoseImpCast(S, LiteralExpr, T, CC,
2810 diag::warn_impcast_literal_float_to_integer);
2811 } else {
2812 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2813 }
2814 }
John McCall51313c32010-01-04 23:31:57 +00002815
2816 return;
2817 }
2818
John McCallf2370c92010-01-06 05:24:50 +00002819 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002820 return;
2821
John McCall323ed742010-05-06 08:58:33 +00002822 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002823 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002824
2825 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002826 // If the source is a constant, use a default-on diagnostic.
2827 // TODO: this should happen for bitfield stores, too.
2828 llvm::APSInt Value(32);
2829 if (E->isIntegerConstantExpr(Value, S.Context)) {
2830 std::string PrettySourceValue = Value.toString(10);
2831 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2832
2833 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2834 << PrettySourceValue << PrettyTargetValue
2835 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2836 return;
2837 }
2838
John McCall51313c32010-01-04 23:31:57 +00002839 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2840 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002841 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002842 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2843 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002844 }
2845
2846 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2847 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2848 SourceRange.Width == TargetRange.Width)) {
2849 unsigned DiagID = diag::warn_impcast_integer_sign;
2850
2851 // Traditionally, gcc has warned about this under -Wsign-compare.
2852 // We also want to warn about it in -Wconversion.
2853 // So if -Wconversion is off, use a completely identical diagnostic
2854 // in the sign-compare group.
2855 // The conditional-checking code will
2856 if (ICContext) {
2857 DiagID = diag::warn_impcast_integer_sign_conditional;
2858 *ICContext = true;
2859 }
2860
John McCallb4eb64d2010-10-08 02:01:28 +00002861 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002862 }
2863
2864 return;
2865}
2866
John McCall323ed742010-05-06 08:58:33 +00002867void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2868
2869void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002870 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002871 E = E->IgnoreParenImpCasts();
2872
2873 if (isa<ConditionalOperator>(E))
2874 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2875
John McCallb4eb64d2010-10-08 02:01:28 +00002876 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002877 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002878 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002879 return;
2880}
2881
2882void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002883 SourceLocation CC = E->getQuestionLoc();
2884
2885 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002886
2887 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002888 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2889 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002890
2891 // If -Wconversion would have warned about either of the candidates
2892 // for a signedness conversion to the context type...
2893 if (!Suspicious) return;
2894
2895 // ...but it's currently ignored...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002896 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2897 CC))
John McCall323ed742010-05-06 08:58:33 +00002898 return;
2899
2900 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00002901 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCall323ed742010-05-06 08:58:33 +00002902 return;
2903
2904 // ...then check whether it would have warned about either of the
2905 // candidates for a signedness conversion to the condition type.
2906 if (E->getType() != T) {
2907 Suspicious = false;
2908 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002909 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002910 if (!Suspicious)
2911 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002912 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002913 if (!Suspicious)
2914 return;
2915 }
2916
2917 // If so, emit a diagnostic under -Wsign-compare.
2918 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2919 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2920 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2921 << lex->getType() << rex->getType()
2922 << lex->getSourceRange() << rex->getSourceRange();
2923}
2924
2925/// AnalyzeImplicitConversions - Find and report any interesting
2926/// implicit conversions in the given expression. There are a couple
2927/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002928void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002929 QualType T = OrigE->getType();
2930 Expr *E = OrigE->IgnoreParenImpCasts();
2931
2932 // For conditional operators, we analyze the arguments as if they
2933 // were being fed directly into the output.
2934 if (isa<ConditionalOperator>(E)) {
2935 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2936 CheckConditionalOperator(S, CO, T);
2937 return;
2938 }
2939
2940 // Go ahead and check any implicit conversions we might have skipped.
2941 // The non-canonical typecheck is just an optimization;
2942 // CheckImplicitConversion will filter out dead implicit conversions.
2943 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002944 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00002945
2946 // Now continue drilling into this expression.
2947
2948 // Skip past explicit casts.
2949 if (isa<ExplicitCastExpr>(E)) {
2950 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00002951 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002952 }
2953
John McCallbeb22aa2010-11-09 23:24:47 +00002954 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2955 // Do a somewhat different check with comparison operators.
2956 if (BO->isComparisonOp())
2957 return AnalyzeComparison(S, BO);
2958
2959 // And with assignments and compound assignments.
2960 if (BO->isAssignmentOp())
2961 return AnalyzeAssignment(S, BO);
2962 }
John McCall323ed742010-05-06 08:58:33 +00002963
2964 // These break the otherwise-useful invariant below. Fortunately,
2965 // we don't really need to recurse into them, because any internal
2966 // expressions should have been analyzed already when they were
2967 // built into statements.
2968 if (isa<StmtExpr>(E)) return;
2969
2970 // Don't descend into unevaluated contexts.
2971 if (isa<SizeOfAlignOfExpr>(E)) return;
2972
2973 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00002974 CC = E->getExprLoc();
John McCall7502c1d2011-02-13 04:07:26 +00002975 for (Stmt::child_range I = E->children(); I; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00002976 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00002977}
2978
2979} // end anonymous namespace
2980
2981/// Diagnoses "dangerous" implicit conversions within the given
2982/// expression (which is a full expression). Implements -Wconversion
2983/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002984///
2985/// \param CC the "context" location of the implicit conversion, i.e.
2986/// the most location of the syntactic entity requiring the implicit
2987/// conversion
2988void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002989 // Don't diagnose in unevaluated contexts.
2990 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2991 return;
2992
2993 // Don't diagnose for value- or type-dependent expressions.
2994 if (E->isTypeDependent() || E->isValueDependent())
2995 return;
2996
John McCallb4eb64d2010-10-08 02:01:28 +00002997 // This is not the right CC for (e.g.) a variable initialization.
2998 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002999}
3000
John McCall15d7d122010-11-11 03:21:53 +00003001void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3002 FieldDecl *BitField,
3003 Expr *Init) {
3004 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3005}
3006
Mike Stumpf8c49212010-01-21 03:59:47 +00003007/// CheckParmsForFunctionDef - Check that the parameters of the given
3008/// function are appropriate for the definition of a function. This
3009/// takes care of any checks that cannot be performed on the
3010/// declaration itself, e.g., that the types of each of the function
3011/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003012bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3013 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00003014 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00003015 for (; P != PEnd; ++P) {
3016 ParmVarDecl *Param = *P;
3017
Mike Stumpf8c49212010-01-21 03:59:47 +00003018 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3019 // function declarator that is part of a function definition of
3020 // that function shall not have incomplete type.
3021 //
3022 // This is also C++ [dcl.fct]p6.
3023 if (!Param->isInvalidDecl() &&
3024 RequireCompleteType(Param->getLocation(), Param->getType(),
3025 diag::err_typecheck_decl_incomplete_type)) {
3026 Param->setInvalidDecl();
3027 HasInvalidParm = true;
3028 }
3029
3030 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3031 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00003032 if (CheckParameterNames &&
3033 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00003034 !Param->isImplicit() &&
3035 !getLangOptions().CPlusPlus)
3036 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00003037
3038 // C99 6.7.5.3p12:
3039 // If the function declarator is not part of a definition of that
3040 // function, parameters may have incomplete type and may use the [*]
3041 // notation in their sequences of declarator specifiers to specify
3042 // variable length array types.
3043 QualType PType = Param->getOriginalType();
3044 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3045 if (AT->getSizeModifier() == ArrayType::Star) {
3046 // FIXME: This diagnosic should point the the '[*]' if source-location
3047 // information is added for it.
3048 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3049 }
3050 }
Mike Stumpf8c49212010-01-21 03:59:47 +00003051 }
3052
3053 return HasInvalidParm;
3054}
John McCallb7f4ffe2010-08-12 21:44:57 +00003055
3056/// CheckCastAlign - Implements -Wcast-align, which warns when a
3057/// pointer cast increases the alignment requirements.
3058void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3059 // This is actually a lot of work to potentially be doing on every
3060 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis08274082010-12-15 18:44:22 +00003061 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3062 TRange.getBegin())
John McCallb7f4ffe2010-08-12 21:44:57 +00003063 == Diagnostic::Ignored)
3064 return;
3065
3066 // Ignore dependent types.
3067 if (T->isDependentType() || Op->getType()->isDependentType())
3068 return;
3069
3070 // Require that the destination be a pointer type.
3071 const PointerType *DestPtr = T->getAs<PointerType>();
3072 if (!DestPtr) return;
3073
3074 // If the destination has alignment 1, we're done.
3075 QualType DestPointee = DestPtr->getPointeeType();
3076 if (DestPointee->isIncompleteType()) return;
3077 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3078 if (DestAlign.isOne()) return;
3079
3080 // Require that the source be a pointer type.
3081 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3082 if (!SrcPtr) return;
3083 QualType SrcPointee = SrcPtr->getPointeeType();
3084
3085 // Whitelist casts from cv void*. We already implicitly
3086 // whitelisted casts to cv void*, since they have alignment 1.
3087 // Also whitelist casts involving incomplete types, which implicitly
3088 // includes 'void'.
3089 if (SrcPointee->isIncompleteType()) return;
3090
3091 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3092 if (SrcAlign >= DestAlign) return;
3093
3094 Diag(TRange.getBegin(), diag::warn_cast_align)
3095 << Op->getType() << T
3096 << static_cast<unsigned>(SrcAlign.getQuantity())
3097 << static_cast<unsigned>(DestAlign.getQuantity())
3098 << TRange << Op->getSourceRange();
3099}
3100
Chandler Carruth34064582011-02-17 20:55:08 +00003101void Sema::CheckArrayAccess(const clang::ArraySubscriptExpr *E) {
Chandler Carruth35001ca2011-02-17 21:10:52 +00003102 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth34064582011-02-17 20:55:08 +00003103 const ConstantArrayType *ArrayTy =
Chandler Carruth35001ca2011-02-17 21:10:52 +00003104 Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth34064582011-02-17 20:55:08 +00003105 if (!ArrayTy)
Ted Kremeneka0125d82011-02-16 01:57:07 +00003106 return;
Chandler Carruth35001ca2011-02-17 21:10:52 +00003107
Chandler Carruth34064582011-02-17 20:55:08 +00003108 const Expr *IndexExpr = E->getIdx();
3109 if (IndexExpr->isValueDependent())
Ted Kremeneka0125d82011-02-16 01:57:07 +00003110 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003111 llvm::APSInt index;
3112 if (!IndexExpr->isIntegerConstantExpr(index, Context))
Ted Kremeneka0125d82011-02-16 01:57:07 +00003113 return;
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003114
Chandler Carruth34064582011-02-17 20:55:08 +00003115 if (!index.isNegative()) {
Ted Kremenek25b3b842011-02-18 02:27:00 +00003116 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth35001ca2011-02-17 21:10:52 +00003117 if (!size.isStrictlyPositive())
3118 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003119 if (size.getBitWidth() > index.getBitWidth())
3120 index = index.sext(size.getBitWidth());
Ted Kremenek25b3b842011-02-18 02:27:00 +00003121 else if (size.getBitWidth() < index.getBitWidth())
3122 size = size.sext(index.getBitWidth());
3123
Chandler Carruth34064582011-02-17 20:55:08 +00003124 if (index.slt(size))
Ted Kremenek8fd0a5d2011-02-16 04:01:44 +00003125 return;
Chandler Carruth34064582011-02-17 20:55:08 +00003126
3127 Diag(E->getBase()->getLocStart(), diag::warn_array_index_exceeds_bounds)
3128 << index.toString(10, true) << size.toString(10, true)
3129 << IndexExpr->getSourceRange();
3130 } else {
3131 Diag(E->getBase()->getLocStart(), diag::warn_array_index_precedes_bounds)
3132 << index.toString(10, true) << IndexExpr->getSourceRange();
Ted Kremeneka0125d82011-02-16 01:57:07 +00003133 }
Chandler Carruth35001ca2011-02-17 21:10:52 +00003134
3135 const NamedDecl *ND = NULL;
3136 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3137 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3138 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3139 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3140 if (ND)
3141 Diag(ND->getLocStart(), diag::note_array_index_out_of_bounds)
3142 << ND->getDeclName();
Ted Kremeneka0125d82011-02-16 01:57:07 +00003143}
3144