blob: d04addd2103fd8e77cd1663723ba13b984c12791 [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
201 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000202 return (8 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000203 case 6: // poly16
204 assert(!shift && "cannot shift polynomial types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000205 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000206 case 7: // float16
207 assert(!shift && "cannot shift float types!");
Nate Begemand69ec162010-06-17 02:26:59 +0000208 return (4 << (int)quad) - 1;
Nate Begeman61eecf52010-06-14 05:21:25 +0000209 }
210 return 0;
211}
212
Nate Begeman26a31422010-06-08 02:47:44 +0000213bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000214 llvm::APSInt Result;
215
Nate Begeman0d15c532010-06-13 04:47:52 +0000216 unsigned mask = 0;
Nate Begeman61eecf52010-06-14 05:21:25 +0000217 unsigned TV = 0;
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000218 switch (BuiltinID) {
Nate Begemana23326b2010-06-17 04:17:01 +0000219#define GET_NEON_OVERLOAD_CHECK
220#include "clang/Basic/arm_neon.inc"
221#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000222 }
223
Nate Begeman0d15c532010-06-13 04:47:52 +0000224 // For NEON intrinsics which are overloaded on vector element type, validate
225 // the immediate which specifies which variant to emit.
226 if (mask) {
227 unsigned ArgNo = TheCall->getNumArgs()-1;
228 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
229 return true;
230
Nate Begeman61eecf52010-06-14 05:21:25 +0000231 TV = Result.getLimitedValue(32);
232 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begeman0d15c532010-06-13 04:47:52 +0000233 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
234 << TheCall->getArg(ArgNo)->getSourceRange();
235 }
Nate Begeman1c2a88c2010-06-09 01:10:23 +0000236
Nate Begeman0d15c532010-06-13 04:47:52 +0000237 // For NEON intrinsics which take an immediate value as part of the
238 // instruction, range check them here.
Nate Begeman61eecf52010-06-14 05:21:25 +0000239 unsigned i = 0, l = 0, u = 0;
Nate Begeman0d15c532010-06-13 04:47:52 +0000240 switch (BuiltinID) {
241 default: return false;
Nate Begemanbb37f502010-07-29 22:48:34 +0000242 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
243 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begeman99c40bb2010-08-03 21:32:34 +0000244 case ARM::BI__builtin_arm_vcvtr_f:
245 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begemana23326b2010-06-17 04:17:01 +0000246#define GET_NEON_IMMEDIATE_CHECK
247#include "clang/Basic/arm_neon.inc"
248#undef GET_NEON_IMMEDIATE_CHECK
Nate Begeman0d15c532010-06-13 04:47:52 +0000249 };
250
Nate Begeman61eecf52010-06-14 05:21:25 +0000251 // Check that the immediate argument is actually a constant.
Nate Begeman0d15c532010-06-13 04:47:52 +0000252 if (SemaBuiltinConstantArg(TheCall, i, Result))
253 return true;
254
Nate Begeman61eecf52010-06-14 05:21:25 +0000255 // Range check against the upper/lower values for this isntruction.
Nate Begeman0d15c532010-06-13 04:47:52 +0000256 unsigned Val = Result.getZExtValue();
Nate Begeman61eecf52010-06-14 05:21:25 +0000257 if (Val < l || Val > (u + l))
Nate Begeman0d15c532010-06-13 04:47:52 +0000258 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000259 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begeman0d15c532010-06-13 04:47:52 +0000260
Nate Begeman99c40bb2010-08-03 21:32:34 +0000261 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman26a31422010-06-08 02:47:44 +0000262 return false;
Anders Carlssond406bf02009-08-16 01:56:34 +0000263}
Daniel Dunbarde454282008-10-02 18:44:07 +0000264
Anders Carlssond406bf02009-08-16 01:56:34 +0000265/// CheckFunctionCall - Check a direct function call for various correctness
266/// and safety properties not strictly enforced by the C type system.
267bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
268 // Get the IdentifierInfo* for the called function.
269 IdentifierInfo *FnInfo = FDecl->getIdentifier();
270
271 // None of the checks below are needed for functions that don't have
272 // simple names (e.g., C++ conversion functions).
273 if (!FnInfo)
274 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Daniel Dunbarde454282008-10-02 18:44:07 +0000276 // FIXME: This mechanism should be abstracted to be less fragile and
277 // more efficient. For example, just map function ids to custom
278 // handlers.
279
Ted Kremenekc82faca2010-09-09 04:33:05 +0000280 // Printf and scanf checking.
281 for (specific_attr_iterator<FormatAttr>
282 i = FDecl->specific_attr_begin<FormatAttr>(),
283 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
284
285 const FormatAttr *Format = *i;
Ted Kremenek826a3452010-07-16 02:11:22 +0000286 const bool b = Format->getType() == "scanf";
287 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek3d692df2009-02-27 17:58:43 +0000288 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000289 CheckPrintfScanfArguments(TheCall, HasVAListArg,
290 Format->getFormatIdx() - 1,
291 HasVAListArg ? 0 : Format->getFirstArg() - 1,
292 !b);
Douglas Gregor3c385e52009-02-14 18:57:46 +0000293 }
Chris Lattner59907c42007-08-10 20:18:51 +0000294 }
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Ted Kremenekc82faca2010-09-09 04:33:05 +0000296 for (specific_attr_iterator<NonNullAttr>
297 i = FDecl->specific_attr_begin<NonNullAttr>(),
298 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Sean Huntcf807c42010-08-18 23:23:40 +0000299 CheckNonNullArguments(*i, TheCall);
Ted Kremenekc82faca2010-09-09 04:33:05 +0000300 }
Sebastian Redl0eb23302009-01-19 00:08:26 +0000301
Anders Carlssond406bf02009-08-16 01:56:34 +0000302 return false;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000303}
304
Anders Carlssond406bf02009-08-16 01:56:34 +0000305bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000306 // Printf checking.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000307 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000308 if (!Format)
Anders Carlssond406bf02009-08-16 01:56:34 +0000309 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000311 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
312 if (!V)
Anders Carlssond406bf02009-08-16 01:56:34 +0000313 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000314
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000315 QualType Ty = V->getType();
316 if (!Ty->isBlockPointerType())
Anders Carlssond406bf02009-08-16 01:56:34 +0000317 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Ted Kremenek826a3452010-07-16 02:11:22 +0000319 const bool b = Format->getType() == "scanf";
320 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +0000321 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Anders Carlssond406bf02009-08-16 01:56:34 +0000323 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek826a3452010-07-16 02:11:22 +0000324 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
325 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssond406bf02009-08-16 01:56:34 +0000326
327 return false;
Fariborz Jahanian725165f2009-05-18 21:05:18 +0000328}
329
Chris Lattner5caa3702009-05-08 06:58:22 +0000330/// SemaBuiltinAtomicOverloaded - We have a call to a function like
331/// __sync_fetch_and_add, which is an overloaded function based on the pointer
332/// type of its first argument. The main ActOnCallExpr routines have already
333/// promoted the types of arguments because all of these calls are prototyped as
334/// void(...).
335///
336/// This function goes through and does final semantic checking for these
337/// builtins,
John McCall60d7b3a2010-08-24 06:29:42 +0000338ExprResult
339Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruthd2014572010-07-09 18:59:35 +0000340 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattner5caa3702009-05-08 06:58:22 +0000341 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
342 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
343
344 // Ensure that we have at least one argument to do type inference from.
Chandler Carruthd2014572010-07-09 18:59:35 +0000345 if (TheCall->getNumArgs() < 1) {
346 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
347 << 0 << 1 << TheCall->getNumArgs()
348 << TheCall->getCallee()->getSourceRange();
349 return ExprError();
350 }
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Chris Lattner5caa3702009-05-08 06:58:22 +0000352 // Inspect the first argument of the atomic builtin. This should always be
353 // a pointer type, whose element is an integral scalar or pointer type.
354 // Because it is a pointer type, we don't have to worry about any implicit
355 // casts here.
Chandler Carruthd2014572010-07-09 18:59:35 +0000356 // FIXME: We don't allow floating point scalars as input.
Chris Lattner5caa3702009-05-08 06:58:22 +0000357 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruthd2014572010-07-09 18:59:35 +0000358 if (!FirstArg->getType()->isPointerType()) {
359 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
360 << FirstArg->getType() << FirstArg->getSourceRange();
361 return ExprError();
362 }
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chandler Carruthd2014572010-07-09 18:59:35 +0000364 QualType ValType =
365 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerdd5fa7a2010-09-17 21:12:38 +0000366 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruthd2014572010-07-09 18:59:35 +0000367 !ValType->isBlockPointerType()) {
368 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
369 << FirstArg->getType() << FirstArg->getSourceRange();
370 return ExprError();
371 }
Chris Lattner5caa3702009-05-08 06:58:22 +0000372
Chandler Carruth8d13d222010-07-18 20:54:12 +0000373 // The majority of builtins return a value, but a few have special return
374 // types, so allow them to override appropriately below.
375 QualType ResultType = ValType;
376
Chris Lattner5caa3702009-05-08 06:58:22 +0000377 // We need to figure out which concrete builtin this maps onto. For example,
378 // __sync_fetch_and_add with a 2 byte object turns into
379 // __sync_fetch_and_add_2.
380#define BUILTIN_ROW(x) \
381 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
382 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Chris Lattner5caa3702009-05-08 06:58:22 +0000384 static const unsigned BuiltinIndices[][5] = {
385 BUILTIN_ROW(__sync_fetch_and_add),
386 BUILTIN_ROW(__sync_fetch_and_sub),
387 BUILTIN_ROW(__sync_fetch_and_or),
388 BUILTIN_ROW(__sync_fetch_and_and),
389 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner5caa3702009-05-08 06:58:22 +0000391 BUILTIN_ROW(__sync_add_and_fetch),
392 BUILTIN_ROW(__sync_sub_and_fetch),
393 BUILTIN_ROW(__sync_and_and_fetch),
394 BUILTIN_ROW(__sync_or_and_fetch),
395 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Chris Lattner5caa3702009-05-08 06:58:22 +0000397 BUILTIN_ROW(__sync_val_compare_and_swap),
398 BUILTIN_ROW(__sync_bool_compare_and_swap),
399 BUILTIN_ROW(__sync_lock_test_and_set),
400 BUILTIN_ROW(__sync_lock_release)
401 };
Mike Stump1eb44332009-09-09 15:08:12 +0000402#undef BUILTIN_ROW
403
Chris Lattner5caa3702009-05-08 06:58:22 +0000404 // Determine the index of the size.
405 unsigned SizeIndex;
Ken Dyck199c3d62010-01-11 17:06:35 +0000406 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattner5caa3702009-05-08 06:58:22 +0000407 case 1: SizeIndex = 0; break;
408 case 2: SizeIndex = 1; break;
409 case 4: SizeIndex = 2; break;
410 case 8: SizeIndex = 3; break;
411 case 16: SizeIndex = 4; break;
412 default:
Chandler Carruthd2014572010-07-09 18:59:35 +0000413 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
414 << FirstArg->getType() << FirstArg->getSourceRange();
415 return ExprError();
Chris Lattner5caa3702009-05-08 06:58:22 +0000416 }
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Chris Lattner5caa3702009-05-08 06:58:22 +0000418 // Each of these builtins has one pointer argument, followed by some number of
419 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
420 // that we ignore. Find out which row of BuiltinIndices to read from as well
421 // as the number of fixed args.
Douglas Gregor7814e6d2009-09-12 00:22:50 +0000422 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattner5caa3702009-05-08 06:58:22 +0000423 unsigned BuiltinIndex, NumFixed = 1;
424 switch (BuiltinID) {
425 default: assert(0 && "Unknown overloaded atomic builtin!");
426 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
427 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
428 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
429 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
430 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000432 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
433 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
434 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
435 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
436 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Chris Lattner5caa3702009-05-08 06:58:22 +0000438 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000439 BuiltinIndex = 10;
Chris Lattner5caa3702009-05-08 06:58:22 +0000440 NumFixed = 2;
441 break;
442 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000443 BuiltinIndex = 11;
Chris Lattner5caa3702009-05-08 06:58:22 +0000444 NumFixed = 2;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000445 ResultType = Context.BoolTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000446 break;
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000447 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattner5caa3702009-05-08 06:58:22 +0000448 case Builtin::BI__sync_lock_release:
Daniel Dunbar7eff7c42010-03-25 17:13:09 +0000449 BuiltinIndex = 13;
Chris Lattner5caa3702009-05-08 06:58:22 +0000450 NumFixed = 0;
Chandler Carruth8d13d222010-07-18 20:54:12 +0000451 ResultType = Context.VoidTy;
Chris Lattner5caa3702009-05-08 06:58:22 +0000452 break;
453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Chris Lattner5caa3702009-05-08 06:58:22 +0000455 // Now that we know how many fixed arguments we expect, first check that we
456 // have at least that many.
Chandler Carruthd2014572010-07-09 18:59:35 +0000457 if (TheCall->getNumArgs() < 1+NumFixed) {
458 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
459 << 0 << 1+NumFixed << TheCall->getNumArgs()
460 << TheCall->getCallee()->getSourceRange();
461 return ExprError();
462 }
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000464 // Get the decl for the concrete builtin from this, we can tell what the
465 // concrete integer type we should convert to is.
466 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
467 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
468 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump1eb44332009-09-09 15:08:12 +0000469 FunctionDecl *NewBuiltinDecl =
Chris Lattnere7ac0a92009-05-08 15:36:58 +0000470 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
471 TUScope, false, DRE->getLocStart()));
Chandler Carruthd2014572010-07-09 18:59:35 +0000472
John McCallf871d0c2010-08-07 06:22:56 +0000473 // The first argument --- the pointer --- has a fixed type; we
474 // deduce the types of the rest of the arguments accordingly. Walk
475 // the remaining arguments, converting them to the deduced value type.
Chris Lattner5caa3702009-05-08 06:58:22 +0000476 for (unsigned i = 0; i != NumFixed; ++i) {
477 Expr *Arg = TheCall->getArg(i+1);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Chris Lattner5caa3702009-05-08 06:58:22 +0000479 // If the argument is an implicit cast, then there was a promotion due to
480 // "...", just remove it now.
481 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
482 Arg = ICE->getSubExpr();
483 ICE->setSubExpr(0);
Chris Lattner5caa3702009-05-08 06:58:22 +0000484 TheCall->setArg(i+1, Arg);
485 }
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner5caa3702009-05-08 06:58:22 +0000487 // GCC does an implicit conversion to the pointer or integer ValType. This
488 // can fail in some cases (1i -> int**), check for this error case now.
John McCalldaa8e4e2010-11-15 09:13:47 +0000489 CastKind Kind = CK_Invalid;
John McCallf871d0c2010-08-07 06:22:56 +0000490 CXXCastPath BasePath;
Anders Carlsson5cf86ba2010-04-24 19:06:50 +0000491 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, BasePath))
Chandler Carruthd2014572010-07-09 18:59:35 +0000492 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattner5caa3702009-05-08 06:58:22 +0000494 // Okay, we have something that *can* be converted to the right type. Check
495 // to see if there is a potentially weird extension going on here. This can
496 // happen when you do an atomic operation on something like an char* and
497 // pass in 42. The 42 gets converted to char. This is even more strange
498 // for things like 45.123 -> char, etc.
Mike Stump1eb44332009-09-09 15:08:12 +0000499 // FIXME: Do this check.
John McCall5baba9d2010-08-25 10:28:54 +0000500 ImpCastExprToType(Arg, ValType, Kind, VK_RValue, &BasePath);
Chris Lattner5caa3702009-05-08 06:58:22 +0000501 TheCall->setArg(i+1, Arg);
502 }
Mike Stump1eb44332009-09-09 15:08:12 +0000503
Chris Lattner5caa3702009-05-08 06:58:22 +0000504 // Switch the DeclRefExpr to refer to the new decl.
505 DRE->setDecl(NewBuiltinDecl);
506 DRE->setType(NewBuiltinDecl->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Chris Lattner5caa3702009-05-08 06:58:22 +0000508 // Set the callee in the CallExpr.
509 // FIXME: This leaks the original parens and implicit casts.
510 Expr *PromotedCall = DRE;
511 UsualUnaryConversions(PromotedCall);
512 TheCall->setCallee(PromotedCall);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Chandler Carruthdb4325b2010-07-18 07:23:17 +0000514 // Change the result type of the call to match the original value type. This
515 // is arbitrary, but the codegen for these builtins ins design to handle it
516 // gracefully.
Chandler Carruth8d13d222010-07-18 20:54:12 +0000517 TheCall->setType(ResultType);
Chandler Carruthd2014572010-07-09 18:59:35 +0000518
519 return move(TheCallResult);
Chris Lattner5caa3702009-05-08 06:58:22 +0000520}
521
522
Chris Lattner69039812009-02-18 06:01:06 +0000523/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson71993dd2007-08-17 05:31:46 +0000524/// CFString constructor is correct
Steve Narofffd942622009-04-13 20:26:29 +0000525/// Note: It might also make sense to do the UTF-16 conversion here (would
526/// simplify the backend).
Chris Lattner69039812009-02-18 06:01:06 +0000527bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattner56f34942008-02-13 01:02:39 +0000528 Arg = Arg->IgnoreParenCasts();
Anders Carlsson71993dd2007-08-17 05:31:46 +0000529 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
530
531 if (!Literal || Literal->isWide()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000532 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
533 << Arg->getSourceRange();
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000534 return true;
Anders Carlsson71993dd2007-08-17 05:31:46 +0000535 }
Mike Stump1eb44332009-09-09 15:08:12 +0000536
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +0000537 size_t NulPos = Literal->getString().find('\0');
538 if (NulPos != llvm::StringRef::npos) {
539 Diag(getLocationOfStringLiteralByte(Literal, NulPos),
540 diag::warn_cfstring_literal_contains_nul_character)
541 << Arg->getSourceRange();
Daniel Dunbarf015b032009-09-22 10:03:52 +0000542 }
Fariborz Jahanian7da71022010-09-07 19:38:13 +0000543 if (Literal->containsNonAsciiOrNull()) {
544 llvm::StringRef String = Literal->getString();
545 unsigned NumBytes = String.size();
546 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
547 const UTF8 *FromPtr = (UTF8 *)String.data();
548 UTF16 *ToPtr = &ToBuf[0];
549
550 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
551 &ToPtr, ToPtr + NumBytes,
552 strictConversion);
553 // Check for conversion failure.
554 if (Result != conversionOK)
555 Diag(Arg->getLocStart(),
556 diag::warn_cfstring_truncated) << Arg->getSourceRange();
557 }
Anders Carlsson9cdc4d32007-08-17 15:44:17 +0000558 return false;
Chris Lattner59907c42007-08-10 20:18:51 +0000559}
560
Chris Lattnerc27c6652007-12-20 00:05:45 +0000561/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
562/// Emit an error and return true on failure, return false on success.
Chris Lattner925e60d2007-12-28 05:29:59 +0000563bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
564 Expr *Fn = TheCall->getCallee();
565 if (TheCall->getNumArgs() > 2) {
Chris Lattner2c21a072008-11-21 18:44:24 +0000566 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000567 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000568 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
569 << Fn->getSourceRange()
Mike Stump1eb44332009-09-09 15:08:12 +0000570 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000571 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner30ce3442007-12-19 23:59:04 +0000572 return true;
573 }
Eli Friedman56f20ae2008-12-15 22:05:35 +0000574
575 if (TheCall->getNumArgs() < 2) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000576 return Diag(TheCall->getLocEnd(),
577 diag::err_typecheck_call_too_few_args_at_least)
578 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedman56f20ae2008-12-15 22:05:35 +0000579 }
580
Chris Lattnerc27c6652007-12-20 00:05:45 +0000581 // Determine whether the current function is variadic or not.
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000582 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnerc27c6652007-12-20 00:05:45 +0000583 bool isVariadic;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000584 if (CurBlock)
John McCallc71a4912010-06-04 19:02:56 +0000585 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek9498d382010-04-29 16:49:01 +0000586 else if (FunctionDecl *FD = getCurFunctionDecl())
587 isVariadic = FD->isVariadic();
588 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000589 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump1eb44332009-09-09 15:08:12 +0000590
Chris Lattnerc27c6652007-12-20 00:05:45 +0000591 if (!isVariadic) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000592 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
593 return true;
594 }
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Chris Lattner30ce3442007-12-19 23:59:04 +0000596 // Verify that the second argument to the builtin is the last argument of the
597 // current function or method.
598 bool SecondArgIsLastNamedArgument = false;
Anders Carlssone2c14102008-02-13 01:22:59 +0000599 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +0000600
Anders Carlsson88cf2262008-02-11 04:20:54 +0000601 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
602 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner30ce3442007-12-19 23:59:04 +0000603 // FIXME: This isn't correct for methods (results in bogus warning).
604 // Get the last formal in the current function.
Anders Carlsson88cf2262008-02-11 04:20:54 +0000605 const ParmVarDecl *LastArg;
Steve Naroffcd9c5142009-04-15 19:33:47 +0000606 if (CurBlock)
607 LastArg = *(CurBlock->TheDecl->param_end()-1);
608 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner371f2582008-12-04 23:50:19 +0000609 LastArg = *(FD->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000610 else
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +0000611 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner30ce3442007-12-19 23:59:04 +0000612 SecondArgIsLastNamedArgument = PV == LastArg;
613 }
614 }
Mike Stump1eb44332009-09-09 15:08:12 +0000615
Chris Lattner30ce3442007-12-19 23:59:04 +0000616 if (!SecondArgIsLastNamedArgument)
Mike Stump1eb44332009-09-09 15:08:12 +0000617 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner30ce3442007-12-19 23:59:04 +0000618 diag::warn_second_parameter_of_va_start_not_last_named_argument);
619 return false;
Eli Friedman6cfda232008-05-20 08:23:37 +0000620}
Chris Lattner30ce3442007-12-19 23:59:04 +0000621
Chris Lattner1b9a0792007-12-20 00:26:33 +0000622/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
623/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner925e60d2007-12-28 05:29:59 +0000624bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
625 if (TheCall->getNumArgs() < 2)
Chris Lattner2c21a072008-11-21 18:44:24 +0000626 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000627 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner925e60d2007-12-28 05:29:59 +0000628 if (TheCall->getNumArgs() > 2)
Mike Stump1eb44332009-09-09 15:08:12 +0000629 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000630 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000631 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000632 << SourceRange(TheCall->getArg(2)->getLocStart(),
633 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Chris Lattner925e60d2007-12-28 05:29:59 +0000635 Expr *OrigArg0 = TheCall->getArg(0);
636 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorcde01732009-05-19 22:10:17 +0000637
Chris Lattner1b9a0792007-12-20 00:26:33 +0000638 // Do standard promotions between the two arguments, returning their common
639 // type.
Chris Lattner925e60d2007-12-28 05:29:59 +0000640 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar403bc2b2009-02-19 19:28:43 +0000641
642 // Make sure any conversions are pushed back into the call; this is
643 // type safe since unordered compare builtins are declared as "_Bool
644 // foo(...)".
645 TheCall->setArg(0, OrigArg0);
646 TheCall->setArg(1, OrigArg1);
Mike Stump1eb44332009-09-09 15:08:12 +0000647
Douglas Gregorcde01732009-05-19 22:10:17 +0000648 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
649 return false;
650
Chris Lattner1b9a0792007-12-20 00:26:33 +0000651 // If the common type isn't a real floating type, then the arguments were
652 // invalid for this operation.
653 if (!Res->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000654 return Diag(OrigArg0->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000655 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattnerd1625842008-11-24 06:25:27 +0000656 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000657 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattner1b9a0792007-12-20 00:26:33 +0000659 return false;
660}
661
Benjamin Kramere771a7a2010-02-15 22:42:31 +0000662/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
663/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000664/// to check everything. We expect the last argument to be a floating point
665/// value.
666bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
667 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman9ac6f622009-08-31 20:06:00 +0000668 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherd77b9a22010-04-16 04:48:22 +0000669 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000670 if (TheCall->getNumArgs() > NumArgs)
671 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000672 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000673 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000674 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000675 (*(TheCall->arg_end()-1))->getLocEnd());
676
Benjamin Kramer3b1e26b2010-02-16 10:07:31 +0000677 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Eli Friedman9ac6f622009-08-31 20:06:00 +0000679 if (OrigArg->isTypeDependent())
680 return false;
681
Chris Lattner81368fb2010-05-06 05:50:07 +0000682 // This operation requires a non-_Complex floating-point number.
Eli Friedman9ac6f622009-08-31 20:06:00 +0000683 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump1eb44332009-09-09 15:08:12 +0000684 return Diag(OrigArg->getLocStart(),
Eli Friedman9ac6f622009-08-31 20:06:00 +0000685 diag::err_typecheck_call_invalid_unary_fp)
686 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Chris Lattner81368fb2010-05-06 05:50:07 +0000688 // If this is an implicit conversion from float -> double, remove it.
689 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
690 Expr *CastArg = Cast->getSubExpr();
691 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
692 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
693 "promotion from float to double is the only expected cast here");
694 Cast->setSubExpr(0);
Chris Lattner81368fb2010-05-06 05:50:07 +0000695 TheCall->setArg(NumArgs-1, CastArg);
696 OrigArg = CastArg;
697 }
698 }
699
Eli Friedman9ac6f622009-08-31 20:06:00 +0000700 return false;
701}
702
Eli Friedmand38617c2008-05-14 19:38:39 +0000703/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
704// This is declared to take (...), so we have to check everything.
John McCall60d7b3a2010-08-24 06:29:42 +0000705ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000706 if (TheCall->getNumArgs() < 2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000707 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherd77b9a22010-04-16 04:48:22 +0000708 diag::err_typecheck_call_too_few_args_at_least)
Nate Begeman37b6a572010-06-08 00:16:34 +0000709 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherd77b9a22010-04-16 04:48:22 +0000710 << TheCall->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000711
Nate Begeman37b6a572010-06-08 00:16:34 +0000712 // Determine which of the following types of shufflevector we're checking:
713 // 1) unary, vector mask: (lhs, mask)
714 // 2) binary, vector mask: (lhs, rhs, mask)
715 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
716 QualType resType = TheCall->getArg(0)->getType();
717 unsigned numElements = 0;
718
Douglas Gregorcde01732009-05-19 22:10:17 +0000719 if (!TheCall->getArg(0)->isTypeDependent() &&
720 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000721 QualType LHSType = TheCall->getArg(0)->getType();
722 QualType RHSType = TheCall->getArg(1)->getType();
723
724 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000725 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000726 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000727 TheCall->getArg(1)->getLocEnd());
728 return ExprError();
729 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000730
731 numElements = LHSType->getAs<VectorType>()->getNumElements();
732 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Nate Begeman37b6a572010-06-08 00:16:34 +0000734 // Check to see if we have a call with 2 vector arguments, the unary shuffle
735 // with mask. If so, verify that RHS is an integer vector type with the
736 // same number of elts as lhs.
737 if (TheCall->getNumArgs() == 2) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000738 if (!RHSType->hasIntegerRepresentation() ||
Nate Begeman37b6a572010-06-08 00:16:34 +0000739 RHSType->getAs<VectorType>()->getNumElements() != numElements)
740 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
741 << SourceRange(TheCall->getArg(1)->getLocStart(),
742 TheCall->getArg(1)->getLocEnd());
743 numResElements = numElements;
744 }
745 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000746 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump1eb44332009-09-09 15:08:12 +0000747 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorcde01732009-05-19 22:10:17 +0000748 TheCall->getArg(1)->getLocEnd());
749 return ExprError();
Nate Begeman37b6a572010-06-08 00:16:34 +0000750 } else if (numElements != numResElements) {
751 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner788b0fd2010-06-23 06:00:24 +0000752 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsone86d78c2010-11-10 21:56:12 +0000753 VectorType::GenericVector);
Douglas Gregorcde01732009-05-19 22:10:17 +0000754 }
Eli Friedmand38617c2008-05-14 19:38:39 +0000755 }
756
757 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorcde01732009-05-19 22:10:17 +0000758 if (TheCall->getArg(i)->isTypeDependent() ||
759 TheCall->getArg(i)->isValueDependent())
760 continue;
761
Nate Begeman37b6a572010-06-08 00:16:34 +0000762 llvm::APSInt Result(32);
763 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
764 return ExprError(Diag(TheCall->getLocStart(),
765 diag::err_shufflevector_nonconstant_argument)
766 << TheCall->getArg(i)->getSourceRange());
Sebastian Redl0eb23302009-01-19 00:08:26 +0000767
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000768 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000769 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000770 diag::err_shufflevector_argument_too_large)
Sebastian Redl0eb23302009-01-19 00:08:26 +0000771 << TheCall->getArg(i)->getSourceRange());
Eli Friedmand38617c2008-05-14 19:38:39 +0000772 }
773
774 llvm::SmallVector<Expr*, 32> exprs;
775
Chris Lattnerd1a0b6d2008-08-10 02:05:13 +0000776 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmand38617c2008-05-14 19:38:39 +0000777 exprs.push_back(TheCall->getArg(i));
778 TheCall->setArg(i, 0);
779 }
780
Nate Begemana88dc302009-08-12 02:10:25 +0000781 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000782 exprs.size(), resType,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000783 TheCall->getCallee()->getLocStart(),
784 TheCall->getRParenLoc()));
Eli Friedmand38617c2008-05-14 19:38:39 +0000785}
Chris Lattner30ce3442007-12-19 23:59:04 +0000786
Daniel Dunbar4493f792008-07-21 22:59:13 +0000787/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
788// This is declared to take (const void*, ...) and can take two
789// optional constant int args.
790bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000791 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000792
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000793 if (NumArgs > 3)
Eric Christopherccfa9632010-04-16 04:56:46 +0000794 return Diag(TheCall->getLocEnd(),
795 diag::err_typecheck_call_too_many_args_at_most)
796 << 0 /*function call*/ << 3 << NumArgs
797 << TheCall->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000798
799 // Argument 0 is checked for us and the remaining arguments must be
800 // constant integers.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000801 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbar4493f792008-07-21 22:59:13 +0000802 Expr *Arg = TheCall->getArg(i);
Eric Christopher691ebc32010-04-17 02:26:23 +0000803
Eli Friedman9aef7262009-12-04 00:30:06 +0000804 llvm::APSInt Result;
Eric Christopher691ebc32010-04-17 02:26:23 +0000805 if (SemaBuiltinConstantArg(TheCall, i, Result))
806 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Daniel Dunbar4493f792008-07-21 22:59:13 +0000808 // FIXME: gcc issues a warning and rewrites these to 0. These
809 // seems especially odd for the third argument since the default
810 // is 3.
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000811 if (i == 1) {
Eli Friedman9aef7262009-12-04 00:30:06 +0000812 if (Result.getLimitedValue() > 1)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000813 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000814 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000815 } else {
Eli Friedman9aef7262009-12-04 00:30:06 +0000816 if (Result.getLimitedValue() > 3)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000817 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattner21fb98e2009-09-23 06:06:36 +0000818 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbar4493f792008-07-21 22:59:13 +0000819 }
820 }
821
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000822 return false;
Daniel Dunbar4493f792008-07-21 22:59:13 +0000823}
824
Eric Christopher691ebc32010-04-17 02:26:23 +0000825/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
826/// TheCall is a constant expression.
827bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
828 llvm::APSInt &Result) {
829 Expr *Arg = TheCall->getArg(ArgNum);
830 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
831 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
832
833 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
834
835 if (!Arg->isIntegerConstantExpr(Result, Context))
836 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher5e896552010-04-19 18:23:02 +0000837 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher691ebc32010-04-17 02:26:23 +0000838
Chris Lattner21fb98e2009-09-23 06:06:36 +0000839 return false;
840}
841
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000842/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
843/// int type). This simply type checks that type is one of the defined
844/// constants (0-3).
Eric Christopherfee667f2009-12-23 03:49:37 +0000845// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000846bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher691ebc32010-04-17 02:26:23 +0000847 llvm::APSInt Result;
848
849 // Check constant-ness first.
850 if (SemaBuiltinConstantArg(TheCall, 1, Result))
851 return true;
852
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000853 Expr *Arg = TheCall->getArg(1);
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000854 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000855 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
856 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbard5f8a4f2008-09-03 21:13:56 +0000857 }
858
859 return false;
860}
861
Eli Friedman586d6a82009-05-03 06:04:26 +0000862/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmand875fed2009-05-03 04:46:36 +0000863/// This checks that val is a constant 1.
864bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
865 Expr *Arg = TheCall->getArg(1);
Eric Christopher691ebc32010-04-17 02:26:23 +0000866 llvm::APSInt Result;
Douglas Gregorcde01732009-05-19 22:10:17 +0000867
Eric Christopher691ebc32010-04-17 02:26:23 +0000868 // TODO: This is less than ideal. Overload this to take a value.
869 if (SemaBuiltinConstantArg(TheCall, 1, Result))
870 return true;
871
872 if (Result != 1)
Eli Friedmand875fed2009-05-03 04:46:36 +0000873 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
874 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
875
876 return false;
877}
878
Ted Kremenekd30ef872009-01-12 23:09:09 +0000879// Handle i > 1 ? "x" : "y", recursivelly
Ted Kremenek082d9362009-03-20 21:35:28 +0000880bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
881 bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000882 unsigned format_idx, unsigned firstDataArg,
883 bool isPrintf) {
Ted Kremenek4fe64412010-09-09 03:51:39 +0000884 tryAgain:
Douglas Gregorcde01732009-05-19 22:10:17 +0000885 if (E->isTypeDependent() || E->isValueDependent())
886 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +0000887
888 switch (E->getStmtClass()) {
889 case Stmt::ConditionalOperatorClass: {
Ted Kremenek082d9362009-03-20 21:35:28 +0000890 const ConditionalOperator *C = cast<ConditionalOperator>(E);
Ted Kremenek826a3452010-07-16 02:11:22 +0000891 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
892 format_idx, firstDataArg, isPrintf)
893 && SemaCheckStringLiteral(C->getRHS(), TheCall, HasVAListArg,
894 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
Ted Kremenek082d9362009-03-20 21:35:28 +0000914 case Stmt::DeclRefExprClass: {
915 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000916
Ted Kremenek082d9362009-03-20 21:35:28 +0000917 // As an exception, do not flag errors for variables binding to
918 // const string literals.
919 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
920 bool isConstant = false;
921 QualType T = DR->getType();
Ted Kremenekd30ef872009-01-12 23:09:09 +0000922
Ted Kremenek082d9362009-03-20 21:35:28 +0000923 if (const ArrayType *AT = Context.getAsArrayType(T)) {
924 isConstant = AT->getElementType().isConstant(Context);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000925 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000926 isConstant = T.isConstant(Context) &&
Ted Kremenek082d9362009-03-20 21:35:28 +0000927 PT->getPointeeType().isConstant(Context);
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Ted Kremenek082d9362009-03-20 21:35:28 +0000930 if (isConstant) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000931 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenek082d9362009-03-20 21:35:28 +0000932 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek826a3452010-07-16 02:11:22 +0000933 HasVAListArg, format_idx, firstDataArg,
934 isPrintf);
Ted Kremenek082d9362009-03-20 21:35:28 +0000935 }
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Anders Carlssond966a552009-06-28 19:55:58 +0000937 // For vprintf* functions (i.e., HasVAListArg==true), we add a
938 // special check to see if the format string is a function parameter
939 // of the function calling the printf function. If the function
940 // has an attribute indicating it is a printf-like function, then we
941 // should suppress warnings concerning non-literals being used in a call
942 // to a vprintf function. For example:
943 //
944 // void
945 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
946 // va_list ap;
947 // va_start(ap, fmt);
948 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
949 // ...
950 //
951 //
952 // FIXME: We don't have full attribute support yet, so just check to see
953 // if the argument is a DeclRefExpr that references a parameter. We'll
954 // add proper support for checking the attribute later.
955 if (HasVAListArg)
956 if (isa<ParmVarDecl>(VD))
957 return true;
Ted Kremenek082d9362009-03-20 21:35:28 +0000958 }
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Ted Kremenek082d9362009-03-20 21:35:28 +0000960 return false;
961 }
Ted Kremenekd30ef872009-01-12 23:09:09 +0000962
Anders Carlsson8f031b32009-06-27 04:05:33 +0000963 case Stmt::CallExprClass: {
964 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000965 if (const ImplicitCastExpr *ICE
Anders Carlsson8f031b32009-06-27 04:05:33 +0000966 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
967 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
968 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000969 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlsson8f031b32009-06-27 04:05:33 +0000970 unsigned ArgIndex = FA->getFormatIdx();
971 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump1eb44332009-09-09 15:08:12 +0000972
973 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +0000974 format_idx, firstDataArg, isPrintf);
Anders Carlsson8f031b32009-06-27 04:05:33 +0000975 }
976 }
977 }
978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Anders Carlsson8f031b32009-06-27 04:05:33 +0000980 return false;
981 }
Ted Kremenek082d9362009-03-20 21:35:28 +0000982 case Stmt::ObjCStringLiteralClass:
983 case Stmt::StringLiteralClass: {
984 const StringLiteral *StrE = NULL;
Mike Stump1eb44332009-09-09 15:08:12 +0000985
Ted Kremenek082d9362009-03-20 21:35:28 +0000986 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenekd30ef872009-01-12 23:09:09 +0000987 StrE = ObjCFExpr->getString();
988 else
Ted Kremenek082d9362009-03-20 21:35:28 +0000989 StrE = cast<StringLiteral>(E);
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Ted Kremenekd30ef872009-01-12 23:09:09 +0000991 if (StrE) {
Ted Kremenek826a3452010-07-16 02:11:22 +0000992 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
993 firstDataArg, isPrintf);
Ted Kremenekd30ef872009-01-12 23:09:09 +0000994 return true;
995 }
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Ted Kremenekd30ef872009-01-12 23:09:09 +0000997 return false;
998 }
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Ted Kremenek082d9362009-03-20 21:35:28 +00001000 default:
1001 return false;
Ted Kremenekd30ef872009-01-12 23:09:09 +00001002 }
1003}
1004
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001005void
Mike Stump1eb44332009-09-09 15:08:12 +00001006Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1007 const CallExpr *TheCall) {
Sean Huntcf807c42010-08-18 23:23:40 +00001008 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1009 e = NonNull->args_end();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001010 i != e; ++i) {
Chris Lattner12b97ff2009-05-25 18:23:36 +00001011 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001012 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00001013 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner12b97ff2009-05-25 18:23:36 +00001014 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1015 << ArgExpr->getSourceRange();
Fariborz Jahaniane898f8a2009-05-21 18:48:51 +00001016 }
1017}
Ted Kremenekd30ef872009-01-12 23:09:09 +00001018
Ted Kremenek826a3452010-07-16 02:11:22 +00001019/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1020/// functions) for correct use of format strings.
Chris Lattner59907c42007-08-10 20:18:51 +00001021void
Ted Kremenek826a3452010-07-16 02:11:22 +00001022Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1023 unsigned format_idx, unsigned firstDataArg,
1024 bool isPrintf) {
1025
Ted Kremenek082d9362009-03-20 21:35:28 +00001026 const Expr *Fn = TheCall->getCallee();
Chris Lattner925e60d2007-12-28 05:29:59 +00001027
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001028 // The way the format attribute works in GCC, the implicit this argument
1029 // of member functions is counted. However, it doesn't appear in our own
1030 // lists, so decrement format_idx in that case.
1031 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth9263a302010-11-16 08:49:43 +00001032 const CXXMethodDecl *method_decl =
1033 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1034 if (method_decl && method_decl->isInstance()) {
1035 // Catch a format attribute mistakenly referring to the object argument.
1036 if (format_idx == 0)
1037 return;
1038 --format_idx;
1039 if(firstDataArg != 0)
1040 --firstDataArg;
1041 }
Sebastian Redl4a2614e2009-11-17 18:02:24 +00001042 }
1043
Ted Kremenek826a3452010-07-16 02:11:22 +00001044 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner925e60d2007-12-28 05:29:59 +00001045 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001046 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001047 << Fn->getSourceRange();
Ted Kremenek71895b92007-08-14 17:39:48 +00001048 return;
1049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Ted Kremenek082d9362009-03-20 21:35:28 +00001051 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner59907c42007-08-10 20:18:51 +00001053 // CHECK: format string is not a string literal.
Mike Stump1eb44332009-09-09 15:08:12 +00001054 //
Ted Kremenek71895b92007-08-14 17:39:48 +00001055 // Dynamically generated format strings are difficult to
1056 // automatically vet at compile time. Requiring that format strings
1057 // are string literals: (1) permits the checking of format strings by
1058 // the compiler and thereby (2) can practically remove the source of
1059 // many format string exploits.
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001060
Mike Stump1eb44332009-09-09 15:08:12 +00001061 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001062 // C string (e.g. "%d")
Mike Stump1eb44332009-09-09 15:08:12 +00001063 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001064 // the same format string checking logic for both ObjC and C strings.
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001065 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek826a3452010-07-16 02:11:22 +00001066 firstDataArg, isPrintf))
Chris Lattner1cd3e1f2009-04-29 04:49:34 +00001067 return; // Literal format string found, check done!
Ted Kremenek7ff22b22008-06-16 18:00:42 +00001068
Chris Lattner655f1412009-04-29 04:59:47 +00001069 // If there are no arguments specified, warn with -Wformat-security, otherwise
1070 // warn only with -Wformat-nonliteral.
1071 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump1eb44332009-09-09 15:08:12 +00001072 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001073 diag::warn_format_nonliteral_noargs)
Chris Lattner655f1412009-04-29 04:59:47 +00001074 << OrigFormatExpr->getSourceRange();
1075 else
Mike Stump1eb44332009-09-09 15:08:12 +00001076 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001077 diag::warn_format_nonliteral)
Chris Lattner655f1412009-04-29 04:59:47 +00001078 << OrigFormatExpr->getSourceRange();
Ted Kremenekd30ef872009-01-12 23:09:09 +00001079}
Ted Kremenek71895b92007-08-14 17:39:48 +00001080
Ted Kremeneke0e53132010-01-28 23:39:18 +00001081namespace {
Ted Kremenek826a3452010-07-16 02:11:22 +00001082class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1083protected:
Ted Kremeneke0e53132010-01-28 23:39:18 +00001084 Sema &S;
1085 const StringLiteral *FExpr;
1086 const Expr *OrigFormatExpr;
Ted Kremenek6ee76532010-03-25 03:59:12 +00001087 const unsigned FirstDataArg;
Ted Kremeneke0e53132010-01-28 23:39:18 +00001088 const unsigned NumDataArgs;
1089 const bool IsObjCLiteral;
1090 const char *Beg; // Start of format string.
Ted Kremenek0d277352010-01-29 01:06:55 +00001091 const bool HasVAListArg;
1092 const CallExpr *TheCall;
1093 unsigned FormatIdx;
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001094 llvm::BitVector CoveredArgs;
Ted Kremenekefaff192010-02-27 01:41:03 +00001095 bool usesPositionalArgs;
1096 bool atFirstArg;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001097public:
Ted Kremenek826a3452010-07-16 02:11:22 +00001098 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek6ee76532010-03-25 03:59:12 +00001099 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001100 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek0d277352010-01-29 01:06:55 +00001101 const char *beg, bool hasVAListArg,
1102 const CallExpr *theCall, unsigned formatIdx)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001103 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek6ee76532010-03-25 03:59:12 +00001104 FirstDataArg(firstDataArg),
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001105 NumDataArgs(numDataArgs),
Ted Kremenek0d277352010-01-29 01:06:55 +00001106 IsObjCLiteral(isObjCLiteral), Beg(beg),
1107 HasVAListArg(hasVAListArg),
Ted Kremenekefaff192010-02-27 01:41:03 +00001108 TheCall(theCall), FormatIdx(formatIdx),
1109 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001110 CoveredArgs.resize(numDataArgs);
1111 CoveredArgs.reset();
1112 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001113
Ted Kremenek07d161f2010-01-29 01:50:07 +00001114 void DoneProcessing();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001115
Ted Kremenek826a3452010-07-16 02:11:22 +00001116 void HandleIncompleteSpecifier(const char *startSpecifier,
1117 unsigned specifierLen);
1118
Ted Kremenekefaff192010-02-27 01:41:03 +00001119 virtual void HandleInvalidPosition(const char *startSpecifier,
1120 unsigned specifierLen,
Ted Kremenek826a3452010-07-16 02:11:22 +00001121 analyze_format_string::PositionContext p);
Ted Kremenekefaff192010-02-27 01:41:03 +00001122
1123 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1124
Ted Kremeneke0e53132010-01-28 23:39:18 +00001125 void HandleNullChar(const char *nullCharacter);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001126
Ted Kremenek826a3452010-07-16 02:11:22 +00001127protected:
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001128 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1129 const char *startSpec,
1130 unsigned specifierLen,
1131 const char *csStart, unsigned csLen);
1132
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001133 SourceRange getFormatStringRange();
Ted Kremenek826a3452010-07-16 02:11:22 +00001134 CharSourceRange getSpecifierRange(const char *startSpecifier,
1135 unsigned specifierLen);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001136 SourceLocation getLocationOfByte(const char *x);
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001137
Ted Kremenek0d277352010-01-29 01:06:55 +00001138 const Expr *getDataArg(unsigned i) const;
Ted Kremenek666a1972010-07-26 19:45:42 +00001139
1140 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1141 const analyze_format_string::ConversionSpecifier &CS,
1142 const char *startSpecifier, unsigned specifierLen,
1143 unsigned argIndex);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001144};
1145}
1146
Ted Kremenek826a3452010-07-16 02:11:22 +00001147SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremeneke0e53132010-01-28 23:39:18 +00001148 return OrigFormatExpr->getSourceRange();
1149}
1150
Ted Kremenek826a3452010-07-16 02:11:22 +00001151CharSourceRange CheckFormatHandler::
1152getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001153 SourceLocation Start = getLocationOfByte(startSpecifier);
1154 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1155
1156 // Advance the end SourceLocation by one due to half-open ranges.
1157 End = End.getFileLocWithOffset(1);
1158
1159 return CharSourceRange::getCharRange(Start, End);
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001160}
1161
Ted Kremenek826a3452010-07-16 02:11:22 +00001162SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001163 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremeneke0e53132010-01-28 23:39:18 +00001164}
1165
Ted Kremenek826a3452010-07-16 02:11:22 +00001166void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1167 unsigned specifierLen){
Ted Kremenek808015a2010-01-29 03:16:21 +00001168 SourceLocation Loc = getLocationOfByte(startSpecifier);
1169 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek826a3452010-07-16 02:11:22 +00001170 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek808015a2010-01-29 03:16:21 +00001171}
1172
Ted Kremenekefaff192010-02-27 01:41:03 +00001173void
Ted Kremenek826a3452010-07-16 02:11:22 +00001174CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1175 analyze_format_string::PositionContext p) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001176 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001177 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1178 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001179}
1180
Ted Kremenek826a3452010-07-16 02:11:22 +00001181void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekefaff192010-02-27 01:41:03 +00001182 unsigned posLen) {
1183 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek826a3452010-07-16 02:11:22 +00001184 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1185 << getSpecifierRange(startPos, posLen);
Ted Kremenekefaff192010-02-27 01:41:03 +00001186}
1187
Ted Kremenek826a3452010-07-16 02:11:22 +00001188void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
1189 // The presence of a null character is likely an error.
1190 S.Diag(getLocationOfByte(nullCharacter),
1191 diag::warn_printf_format_string_contains_null_char)
1192 << getFormatStringRange();
1193}
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001194
Ted Kremenek826a3452010-07-16 02:11:22 +00001195const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1196 return TheCall->getArg(FirstDataArg + i);
1197}
1198
1199void CheckFormatHandler::DoneProcessing() {
1200 // Does the number of data arguments exceed the number of
1201 // format conversions in the format string?
1202 if (!HasVAListArg) {
1203 // Find any arguments that weren't covered.
1204 CoveredArgs.flip();
1205 signed notCoveredArg = CoveredArgs.find_first();
1206 if (notCoveredArg >= 0) {
1207 assert((unsigned)notCoveredArg < NumDataArgs);
1208 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1209 diag::warn_printf_data_arg_not_used)
1210 << getFormatStringRange();
1211 }
1212 }
1213}
1214
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001215bool
1216CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1217 SourceLocation Loc,
1218 const char *startSpec,
1219 unsigned specifierLen,
1220 const char *csStart,
1221 unsigned csLen) {
1222
1223 bool keepGoing = true;
1224 if (argIndex < NumDataArgs) {
1225 // Consider the argument coverered, even though the specifier doesn't
1226 // make sense.
1227 CoveredArgs.set(argIndex);
1228 }
1229 else {
1230 // If argIndex exceeds the number of data arguments we
1231 // don't issue a warning because that is just a cascade of warnings (and
1232 // they may have intended '%%' anyway). We don't want to continue processing
1233 // the format string after this point, however, as we will like just get
1234 // gibberish when trying to match arguments.
1235 keepGoing = false;
1236 }
1237
1238 S.Diag(Loc, diag::warn_format_invalid_conversion)
1239 << llvm::StringRef(csStart, csLen)
1240 << getSpecifierRange(startSpec, specifierLen);
1241
1242 return keepGoing;
1243}
1244
Ted Kremenek666a1972010-07-26 19:45:42 +00001245bool
1246CheckFormatHandler::CheckNumArgs(
1247 const analyze_format_string::FormatSpecifier &FS,
1248 const analyze_format_string::ConversionSpecifier &CS,
1249 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1250
1251 if (argIndex >= NumDataArgs) {
1252 if (FS.usesPositionalArg()) {
1253 S.Diag(getLocationOfByte(CS.getStart()),
1254 diag::warn_printf_positional_arg_exceeds_data_args)
1255 << (argIndex+1) << NumDataArgs
1256 << getSpecifierRange(startSpecifier, specifierLen);
1257 }
1258 else {
1259 S.Diag(getLocationOfByte(CS.getStart()),
1260 diag::warn_printf_insufficient_data_args)
1261 << getSpecifierRange(startSpecifier, specifierLen);
1262 }
1263
1264 return false;
1265 }
1266 return true;
1267}
1268
Ted Kremenek826a3452010-07-16 02:11:22 +00001269//===--- CHECK: Printf format string checking ------------------------------===//
1270
1271namespace {
1272class CheckPrintfHandler : public CheckFormatHandler {
1273public:
1274 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1275 const Expr *origFormatExpr, unsigned firstDataArg,
1276 unsigned numDataArgs, bool isObjCLiteral,
1277 const char *beg, bool hasVAListArg,
1278 const CallExpr *theCall, unsigned formatIdx)
1279 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1280 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1281 theCall, formatIdx) {}
1282
1283
1284 bool HandleInvalidPrintfConversionSpecifier(
1285 const analyze_printf::PrintfSpecifier &FS,
1286 const char *startSpecifier,
1287 unsigned specifierLen);
1288
1289 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1290 const char *startSpecifier,
1291 unsigned specifierLen);
1292
1293 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1294 const char *startSpecifier, unsigned specifierLen);
1295 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1296 const analyze_printf::OptionalAmount &Amt,
1297 unsigned type,
1298 const char *startSpecifier, unsigned specifierLen);
1299 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1300 const analyze_printf::OptionalFlag &flag,
1301 const char *startSpecifier, unsigned specifierLen);
1302 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1303 const analyze_printf::OptionalFlag &ignoredFlag,
1304 const analyze_printf::OptionalFlag &flag,
1305 const char *startSpecifier, unsigned specifierLen);
1306};
1307}
1308
1309bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1310 const analyze_printf::PrintfSpecifier &FS,
1311 const char *startSpecifier,
1312 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001313 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001314 FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001315
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001316 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1317 getLocationOfByte(CS.getStart()),
1318 startSpecifier, specifierLen,
1319 CS.getStart(), CS.getLength());
Ted Kremenek26ac2e02010-01-29 02:40:24 +00001320}
1321
Ted Kremenek826a3452010-07-16 02:11:22 +00001322bool CheckPrintfHandler::HandleAmount(
1323 const analyze_format_string::OptionalAmount &Amt,
1324 unsigned k, const char *startSpecifier,
1325 unsigned specifierLen) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001326
1327 if (Amt.hasDataArgument()) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001328 if (!HasVAListArg) {
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001329 unsigned argIndex = Amt.getArgIndex();
1330 if (argIndex >= NumDataArgs) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001331 S.Diag(getLocationOfByte(Amt.getStart()),
1332 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek826a3452010-07-16 02:11:22 +00001333 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek0d277352010-01-29 01:06:55 +00001334 // Don't do any more checking. We will just emit
1335 // spurious errors.
1336 return false;
1337 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001338
Ted Kremenek0d277352010-01-29 01:06:55 +00001339 // Type check the data argument. It should be an 'int'.
Ted Kremenek31f8e322010-01-29 23:32:22 +00001340 // Although not in conformance with C99, we also allow the argument to be
1341 // an 'unsigned int' as that is a reasonably safe case. GCC also
1342 // doesn't emit a warning for that case.
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001343 CoveredArgs.set(argIndex);
1344 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek0d277352010-01-29 01:06:55 +00001345 QualType T = Arg->getType();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001346
1347 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1348 assert(ATR.isValid());
1349
1350 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekefaff192010-02-27 01:41:03 +00001351 S.Diag(getLocationOfByte(Amt.getStart()),
1352 diag::warn_printf_asterisk_wrong_type)
1353 << k
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001354 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek826a3452010-07-16 02:11:22 +00001355 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekd635c5f2010-01-30 00:49:51 +00001356 << Arg->getSourceRange();
Ted Kremenek0d277352010-01-29 01:06:55 +00001357 // Don't do any more checking. We will just emit
1358 // spurious errors.
1359 return false;
1360 }
1361 }
1362 }
1363 return true;
1364}
Ted Kremenek0d277352010-01-29 01:06:55 +00001365
Tom Caree4ee9662010-06-17 19:00:27 +00001366void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek826a3452010-07-16 02:11:22 +00001367 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001368 const analyze_printf::OptionalAmount &Amt,
1369 unsigned type,
1370 const char *startSpecifier,
1371 unsigned specifierLen) {
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001372 const analyze_printf::PrintfConversionSpecifier &CS =
1373 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001374 switch (Amt.getHowSpecified()) {
1375 case analyze_printf::OptionalAmount::Constant:
1376 S.Diag(getLocationOfByte(Amt.getStart()),
1377 diag::warn_printf_nonsensical_optional_amount)
1378 << type
1379 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001380 << getSpecifierRange(startSpecifier, specifierLen)
1381 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001382 Amt.getConstantLength()));
1383 break;
1384
1385 default:
1386 S.Diag(getLocationOfByte(Amt.getStart()),
1387 diag::warn_printf_nonsensical_optional_amount)
1388 << type
1389 << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001390 << getSpecifierRange(startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001391 break;
1392 }
1393}
1394
Ted Kremenek826a3452010-07-16 02:11:22 +00001395void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001396 const analyze_printf::OptionalFlag &flag,
1397 const char *startSpecifier,
1398 unsigned specifierLen) {
1399 // Warn about pointless flag with a fixit removal.
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001400 const analyze_printf::PrintfConversionSpecifier &CS =
1401 FS.getConversionSpecifier();
Tom Caree4ee9662010-06-17 19:00:27 +00001402 S.Diag(getLocationOfByte(flag.getPosition()),
1403 diag::warn_printf_nonsensical_flag)
1404 << flag.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001405 << getSpecifierRange(startSpecifier, specifierLen)
1406 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Caree4ee9662010-06-17 19:00:27 +00001407}
1408
1409void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek826a3452010-07-16 02:11:22 +00001410 const analyze_printf::PrintfSpecifier &FS,
Tom Caree4ee9662010-06-17 19:00:27 +00001411 const analyze_printf::OptionalFlag &ignoredFlag,
1412 const analyze_printf::OptionalFlag &flag,
1413 const char *startSpecifier,
1414 unsigned specifierLen) {
1415 // Warn about ignored flag with a fixit removal.
1416 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1417 diag::warn_printf_ignored_flag)
1418 << ignoredFlag.toString() << flag.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001419 << getSpecifierRange(startSpecifier, specifierLen)
1420 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Caree4ee9662010-06-17 19:00:27 +00001421 ignoredFlag.getPosition(), 1));
1422}
1423
Ted Kremeneke0e53132010-01-28 23:39:18 +00001424bool
Ted Kremenek826a3452010-07-16 02:11:22 +00001425CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001426 &FS,
Ted Kremeneke0e53132010-01-28 23:39:18 +00001427 const char *startSpecifier,
1428 unsigned specifierLen) {
1429
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001430 using namespace analyze_format_string;
Ted Kremenekefaff192010-02-27 01:41:03 +00001431 using namespace analyze_printf;
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001432 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremeneke0e53132010-01-28 23:39:18 +00001433
Ted Kremenekbaa40062010-07-19 22:01:06 +00001434 if (FS.consumesDataArgument()) {
1435 if (atFirstArg) {
1436 atFirstArg = false;
1437 usesPositionalArgs = FS.usesPositionalArg();
1438 }
1439 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1440 // Cannot mix-and-match positional and non-positional arguments.
1441 S.Diag(getLocationOfByte(CS.getStart()),
1442 diag::warn_format_mix_positional_nonpositional_args)
1443 << getSpecifierRange(startSpecifier, specifierLen);
1444 return false;
1445 }
Ted Kremenek0d277352010-01-29 01:06:55 +00001446 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001447
Ted Kremenekefaff192010-02-27 01:41:03 +00001448 // First check if the field width, precision, and conversion specifier
1449 // have matching data arguments.
1450 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1451 startSpecifier, specifierLen)) {
1452 return false;
1453 }
1454
1455 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1456 startSpecifier, specifierLen)) {
Ted Kremenek0d277352010-01-29 01:06:55 +00001457 return false;
1458 }
1459
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001460 if (!CS.consumesDataArgument()) {
1461 // FIXME: Technically specifying a precision or field width here
1462 // makes no sense. Worth issuing a warning at some point.
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001463 return true;
Ted Kremenekf88c8e02010-01-29 20:55:36 +00001464 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001465
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001466 // Consume the argument.
1467 unsigned argIndex = FS.getArgIndex();
Ted Kremeneke3fc5472010-02-27 08:34:51 +00001468 if (argIndex < NumDataArgs) {
1469 // The check to see if the argIndex is valid will come later.
1470 // We set the bit here because we may exit early from this
1471 // function if we encounter some other error.
1472 CoveredArgs.set(argIndex);
1473 }
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001474
1475 // Check for using an Objective-C specific conversion specifier
1476 // in a non-ObjC literal.
1477 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001478 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1479 specifierLen);
Ted Kremenek7f70dc82010-02-26 19:18:41 +00001480 }
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001481
Tom Caree4ee9662010-06-17 19:00:27 +00001482 // Check for invalid use of field width
1483 if (!FS.hasValidFieldWidth()) {
Tom Care45f9b7e2010-06-21 21:21:01 +00001484 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Caree4ee9662010-06-17 19:00:27 +00001485 startSpecifier, specifierLen);
1486 }
1487
1488 // Check for invalid use of precision
1489 if (!FS.hasValidPrecision()) {
1490 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1491 startSpecifier, specifierLen);
1492 }
1493
1494 // Check each flag does not conflict with any other component.
1495 if (!FS.hasValidLeadingZeros())
1496 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1497 if (!FS.hasValidPlusPrefix())
1498 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care45f9b7e2010-06-21 21:21:01 +00001499 if (!FS.hasValidSpacePrefix())
1500 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001501 if (!FS.hasValidAlternativeForm())
1502 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1503 if (!FS.hasValidLeftJustified())
1504 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1505
1506 // Check that flags are not ignored by another flag
Tom Care45f9b7e2010-06-21 21:21:01 +00001507 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1508 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1509 startSpecifier, specifierLen);
Tom Caree4ee9662010-06-17 19:00:27 +00001510 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1511 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1512 startSpecifier, specifierLen);
1513
1514 // Check the length modifier is valid with the given conversion specifier.
1515 const LengthModifier &LM = FS.getLengthModifier();
1516 if (!FS.hasValidLengthModifier())
1517 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenek649aecf2010-07-20 20:03:43 +00001518 diag::warn_format_nonsensical_length)
Tom Caree4ee9662010-06-17 19:00:27 +00001519 << LM.toString() << CS.toString()
Ted Kremenek826a3452010-07-16 02:11:22 +00001520 << getSpecifierRange(startSpecifier, specifierLen)
1521 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Caree4ee9662010-06-17 19:00:27 +00001522 LM.getLength()));
1523
1524 // Are we using '%n'?
Ted Kremenek35d353b2010-07-20 20:04:10 +00001525 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Caree4ee9662010-06-17 19:00:27 +00001526 // Issue a warning about this being a possible security issue.
Ted Kremeneke82d8042010-01-29 01:35:25 +00001527 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek826a3452010-07-16 02:11:22 +00001528 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremeneke82d8042010-01-29 01:35:25 +00001529 // Continue checking the other format specifiers.
1530 return true;
1531 }
Ted Kremenek5c41ee82010-02-11 09:27:41 +00001532
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001533 // The remaining checks depend on the data arguments.
1534 if (HasVAListArg)
1535 return true;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001536
Ted Kremenek666a1972010-07-26 19:45:42 +00001537 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenekda51f0d2010-01-29 01:43:31 +00001538 return false;
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001539
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001540 // Now type check the data expression that matches the
1541 // format specifier.
1542 const Expr *Ex = getDataArg(argIndex);
1543 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1544 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1545 // Check if we didn't match because of an implicit cast from a 'char'
1546 // or 'short' to an 'int'. This is done because printf is a varargs
1547 // function.
1548 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001549 if (ICE->getType() == S.Context.IntTy) {
1550 // All further checking is done on the subexpression.
1551 Ex = ICE->getSubExpr();
1552 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001553 return true;
Ted Kremenek4d8ae4d2010-10-21 04:00:58 +00001554 }
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001555
1556 // We may be able to offer a FixItHint if it is a supported type.
1557 PrintfSpecifier fixedFS = FS;
1558 bool success = fixedFS.fixType(Ex->getType());
1559
1560 if (success) {
1561 // Get the fix string from the fixed format specifier
1562 llvm::SmallString<128> buf;
1563 llvm::raw_svector_ostream os(buf);
1564 fixedFS.toString(os);
1565
Ted Kremenek9325eaf2010-08-24 22:24:51 +00001566 // FIXME: getRepresentativeType() perhaps should return a string
1567 // instead of a QualType to better handle when the representative
1568 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer96827eb2010-07-27 04:46:02 +00001569 S.Diag(getLocationOfByte(CS.getStart()),
1570 diag::warn_printf_conversion_argument_type_mismatch)
1571 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1572 << getSpecifierRange(startSpecifier, specifierLen)
1573 << Ex->getSourceRange()
1574 << FixItHint::CreateReplacement(
1575 getSpecifierRange(startSpecifier, specifierLen),
1576 os.str());
1577 }
1578 else {
1579 S.Diag(getLocationOfByte(CS.getStart()),
1580 diag::warn_printf_conversion_argument_type_mismatch)
1581 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1582 << getSpecifierRange(startSpecifier, specifierLen)
1583 << Ex->getSourceRange();
1584 }
1585 }
1586
Ted Kremeneke0e53132010-01-28 23:39:18 +00001587 return true;
1588}
1589
Ted Kremenek826a3452010-07-16 02:11:22 +00001590//===--- CHECK: Scanf format string checking ------------------------------===//
1591
1592namespace {
1593class CheckScanfHandler : public CheckFormatHandler {
1594public:
1595 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1596 const Expr *origFormatExpr, unsigned firstDataArg,
1597 unsigned numDataArgs, bool isObjCLiteral,
1598 const char *beg, bool hasVAListArg,
1599 const CallExpr *theCall, unsigned formatIdx)
1600 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1601 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1602 theCall, formatIdx) {}
1603
1604 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1605 const char *startSpecifier,
1606 unsigned specifierLen);
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001607
1608 bool HandleInvalidScanfConversionSpecifier(
1609 const analyze_scanf::ScanfSpecifier &FS,
1610 const char *startSpecifier,
1611 unsigned specifierLen);
Ted Kremenekb7c21012010-07-16 18:28:03 +00001612
1613 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek826a3452010-07-16 02:11:22 +00001614};
Ted Kremenek07d161f2010-01-29 01:50:07 +00001615}
Ted Kremeneke0e53132010-01-28 23:39:18 +00001616
Ted Kremenekb7c21012010-07-16 18:28:03 +00001617void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1618 const char *end) {
1619 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1620 << getSpecifierRange(start, end - start);
1621}
1622
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001623bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1624 const analyze_scanf::ScanfSpecifier &FS,
1625 const char *startSpecifier,
1626 unsigned specifierLen) {
1627
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001628 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekc09b6a52010-07-19 21:25:57 +00001629 FS.getConversionSpecifier();
1630
1631 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1632 getLocationOfByte(CS.getStart()),
1633 startSpecifier, specifierLen,
1634 CS.getStart(), CS.getLength());
1635}
1636
Ted Kremenek826a3452010-07-16 02:11:22 +00001637bool CheckScanfHandler::HandleScanfSpecifier(
1638 const analyze_scanf::ScanfSpecifier &FS,
1639 const char *startSpecifier,
1640 unsigned specifierLen) {
1641
1642 using namespace analyze_scanf;
1643 using namespace analyze_format_string;
1644
Ted Kremenek6ecb9502010-07-20 20:04:27 +00001645 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek826a3452010-07-16 02:11:22 +00001646
Ted Kremenekbaa40062010-07-19 22:01:06 +00001647 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1648 // be used to decide if we are using positional arguments consistently.
1649 if (FS.consumesDataArgument()) {
1650 if (atFirstArg) {
1651 atFirstArg = false;
1652 usesPositionalArgs = FS.usesPositionalArg();
1653 }
1654 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1655 // Cannot mix-and-match positional and non-positional arguments.
1656 S.Diag(getLocationOfByte(CS.getStart()),
1657 diag::warn_format_mix_positional_nonpositional_args)
1658 << getSpecifierRange(startSpecifier, specifierLen);
1659 return false;
1660 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001661 }
1662
1663 // Check if the field with is non-zero.
1664 const OptionalAmount &Amt = FS.getFieldWidth();
1665 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1666 if (Amt.getConstantAmount() == 0) {
1667 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1668 Amt.getConstantLength());
1669 S.Diag(getLocationOfByte(Amt.getStart()),
1670 diag::warn_scanf_nonzero_width)
1671 << R << FixItHint::CreateRemoval(R);
1672 }
1673 }
1674
1675 if (!FS.consumesDataArgument()) {
1676 // FIXME: Technically specifying a precision or field width here
1677 // makes no sense. Worth issuing a warning at some point.
1678 return true;
1679 }
1680
1681 // Consume the argument.
1682 unsigned argIndex = FS.getArgIndex();
1683 if (argIndex < NumDataArgs) {
1684 // The check to see if the argIndex is valid will come later.
1685 // We set the bit here because we may exit early from this
1686 // function if we encounter some other error.
1687 CoveredArgs.set(argIndex);
1688 }
1689
Ted Kremenek1e51c202010-07-20 20:04:47 +00001690 // Check the length modifier is valid with the given conversion specifier.
1691 const LengthModifier &LM = FS.getLengthModifier();
1692 if (!FS.hasValidLengthModifier()) {
1693 S.Diag(getLocationOfByte(LM.getStart()),
1694 diag::warn_format_nonsensical_length)
1695 << LM.toString() << CS.toString()
1696 << getSpecifierRange(startSpecifier, specifierLen)
1697 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1698 LM.getLength()));
1699 }
1700
Ted Kremenek826a3452010-07-16 02:11:22 +00001701 // The remaining checks depend on the data arguments.
1702 if (HasVAListArg)
1703 return true;
1704
Ted Kremenek666a1972010-07-26 19:45:42 +00001705 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek826a3452010-07-16 02:11:22 +00001706 return false;
Ted Kremenek826a3452010-07-16 02:11:22 +00001707
1708 // FIXME: Check that the argument type matches the format specifier.
1709
1710 return true;
1711}
1712
1713void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenek0e5675d2010-02-10 02:16:30 +00001714 const Expr *OrigFormatExpr,
1715 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek826a3452010-07-16 02:11:22 +00001716 unsigned format_idx, unsigned firstDataArg,
1717 bool isPrintf) {
1718
Ted Kremeneke0e53132010-01-28 23:39:18 +00001719 // CHECK: is the format string a wide literal?
1720 if (FExpr->isWide()) {
1721 Diag(FExpr->getLocStart(),
Ted Kremenek826a3452010-07-16 02:11:22 +00001722 diag::warn_format_string_is_wide_literal)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001723 << OrigFormatExpr->getSourceRange();
1724 return;
1725 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001726
Ted Kremeneke0e53132010-01-28 23:39:18 +00001727 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00001728 llvm::StringRef StrRef = FExpr->getString();
1729 const char *Str = StrRef.data();
1730 unsigned StrLen = StrRef.size();
Ted Kremenek826a3452010-07-16 02:11:22 +00001731
Ted Kremeneke0e53132010-01-28 23:39:18 +00001732 // CHECK: empty format string?
Ted Kremeneke0e53132010-01-28 23:39:18 +00001733 if (StrLen == 0) {
Ted Kremenek826a3452010-07-16 02:11:22 +00001734 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremeneke0e53132010-01-28 23:39:18 +00001735 << OrigFormatExpr->getSourceRange();
1736 return;
1737 }
Ted Kremenek826a3452010-07-16 02:11:22 +00001738
1739 if (isPrintf) {
1740 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1741 TheCall->getNumArgs() - firstDataArg,
1742 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1743 HasVAListArg, TheCall, format_idx);
1744
1745 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1746 H.DoneProcessing();
1747 }
1748 else {
1749 CheckScanfHandler 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::ParseScanfString(H, Str, Str + StrLen))
1755 H.DoneProcessing();
1756 }
Ted Kremenekce7024e2010-01-28 01:18:22 +00001757}
1758
Ted Kremenek06de2762007-08-17 16:46:58 +00001759//===--- CHECK: Return Address of Stack Variable --------------------------===//
1760
1761static DeclRefExpr* EvalVal(Expr *E);
1762static DeclRefExpr* EvalAddr(Expr* E);
1763
1764/// CheckReturnStackAddr - Check if a return statement returns the address
1765/// of a stack variable.
1766void
1767Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1768 SourceLocation ReturnLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001769
Ted Kremenek06de2762007-08-17 16:46:58 +00001770 // Perform checking for returned stack addresses.
Steve Naroffdd972f22008-09-05 22:11:13 +00001771 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001772 if (DeclRefExpr *DR = EvalAddr(RetValExp))
Chris Lattner3c73c412008-11-19 08:23:25 +00001773 Diag(DR->getLocStart(), diag::warn_ret_stack_addr)
Chris Lattner08631c52008-11-23 21:45:46 +00001774 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001775
Steve Naroffc50a4a52008-09-16 22:25:10 +00001776 // Skip over implicit cast expressions when checking for block expressions.
Chris Lattner4ca606e2009-09-08 00:36:37 +00001777 RetValExp = RetValExp->IgnoreParenCasts();
Steve Naroffc50a4a52008-09-16 22:25:10 +00001778
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001779 if (BlockExpr *C = dyn_cast<BlockExpr>(RetValExp))
Mike Stump397195b2009-04-17 00:09:41 +00001780 if (C->hasBlockDeclRefExprs())
1781 Diag(C->getLocStart(), diag::err_ret_local_block)
1782 << C->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001783
Chris Lattner9e6b37a2009-10-30 04:01:58 +00001784 if (AddrLabelExpr *ALE = dyn_cast<AddrLabelExpr>(RetValExp))
1785 Diag(ALE->getLocStart(), diag::warn_ret_addr_label)
1786 << ALE->getSourceRange();
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00001787
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001788 } else if (lhsType->isReferenceType()) {
1789 // Perform checking for stack values returned by reference.
Douglas Gregor49badde2008-10-27 19:41:14 +00001790 // Check for a reference to the stack
1791 if (DeclRefExpr *DR = EvalVal(RetValExp))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001792 Diag(DR->getLocStart(), diag::warn_ret_stack_ref)
Chris Lattner08631c52008-11-23 21:45:46 +00001793 << DR->getDecl()->getDeclName() << RetValExp->getSourceRange();
Ted Kremenek06de2762007-08-17 16:46:58 +00001794 }
1795}
1796
1797/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1798/// check if the expression in a return statement evaluates to an address
1799/// to a location on the stack. The recursion is used to traverse the
1800/// AST of the return expression, with recursion backtracking when we
1801/// encounter a subexpression that (1) clearly does not lead to the address
1802/// of a stack variable or (2) is something we cannot determine leads to
1803/// the address of a stack variable based on such local checking.
1804///
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001805/// EvalAddr processes expressions that are pointers that are used as
1806/// references (and not L-values). EvalVal handles all other values.
Mike Stump1eb44332009-09-09 15:08:12 +00001807/// At the base case of the recursion is a check for a DeclRefExpr* in
Ted Kremenek06de2762007-08-17 16:46:58 +00001808/// the refers to a stack variable.
1809///
1810/// This implementation handles:
1811///
1812/// * pointer-to-pointer casts
1813/// * implicit conversions from array references to pointers
1814/// * taking the address of fields
1815/// * arbitrary interplay between "&" and "*" operators
1816/// * pointer arithmetic from an address of a stack variable
1817/// * taking the address of an array element where the array is on the stack
1818static DeclRefExpr* EvalAddr(Expr *E) {
Ted Kremenek06de2762007-08-17 16:46:58 +00001819 // We should only be called for evaluating pointer expressions.
David Chisnall0f436562009-08-17 16:35:33 +00001820 assert((E->getType()->isAnyPointerType() ||
Steve Naroffdd972f22008-09-05 22:11:13 +00001821 E->getType()->isBlockPointerType() ||
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001822 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001823 "EvalAddr only works on pointers");
Mike Stump1eb44332009-09-09 15:08:12 +00001824
Ted Kremenek06de2762007-08-17 16:46:58 +00001825 // Our "symbolic interpreter" is just a dispatch off the currently
1826 // viewed AST node. We then recursively traverse the AST by calling
1827 // EvalAddr and EvalVal appropriately.
1828 switch (E->getStmtClass()) {
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001829 case Stmt::ParenExprClass:
1830 // Ignore parentheses.
1831 return EvalAddr(cast<ParenExpr>(E)->getSubExpr());
Ted Kremenek06de2762007-08-17 16:46:58 +00001832
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001833 case Stmt::UnaryOperatorClass: {
1834 // The only unary operator that make sense to handle here
1835 // is AddrOf. All others don't make sense as pointers.
1836 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001837
John McCall2de56d12010-08-25 11:45:40 +00001838 if (U->getOpcode() == UO_AddrOf)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001839 return EvalVal(U->getSubExpr());
1840 else
Ted Kremenek06de2762007-08-17 16:46:58 +00001841 return NULL;
1842 }
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001844 case Stmt::BinaryOperatorClass: {
1845 // Handle pointer arithmetic. All other binary operators are not valid
1846 // in this context.
1847 BinaryOperator *B = cast<BinaryOperator>(E);
John McCall2de56d12010-08-25 11:45:40 +00001848 BinaryOperatorKind op = B->getOpcode();
Mike Stump1eb44332009-09-09 15:08:12 +00001849
John McCall2de56d12010-08-25 11:45:40 +00001850 if (op != BO_Add && op != BO_Sub)
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001851 return NULL;
Mike Stump1eb44332009-09-09 15:08:12 +00001852
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001853 Expr *Base = B->getLHS();
1854
1855 // Determine which argument is the real pointer base. It could be
1856 // the RHS argument instead of the LHS.
1857 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump1eb44332009-09-09 15:08:12 +00001858
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001859 assert (Base->getType()->isPointerType());
1860 return EvalAddr(Base);
1861 }
Steve Naroff61f40a22008-09-10 19:17:48 +00001862
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001863 // For conditional operators we need to see if either the LHS or RHS are
1864 // valid DeclRefExpr*s. If one of them is valid, we return it.
1865 case Stmt::ConditionalOperatorClass: {
1866 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001867
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001868 // Handle the GNU extension for missing LHS.
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001869 if (Expr *lhsExpr = C->getLHS()) {
1870 // In C++, we can have a throw-expression, which has 'void' type.
1871 if (!lhsExpr->getType()->isVoidType())
1872 if (DeclRefExpr* LHS = EvalAddr(lhsExpr))
1873 return LHS;
1874 }
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001875
Douglas Gregor9ee5ee82010-10-21 16:21:08 +00001876 // In C++, we can have a throw-expression, which has 'void' type.
1877 if (C->getRHS()->getType()->isVoidType())
1878 return NULL;
1879
1880 return EvalAddr(C->getRHS());
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001881 }
Mike Stump1eb44332009-09-09 15:08:12 +00001882
Ted Kremenek54b52742008-08-07 00:49:01 +00001883 // For casts, we need to handle conversions from arrays to
1884 // pointer values, and pointer-to-pointer conversions.
Douglas Gregor49badde2008-10-27 19:41:14 +00001885 case Stmt::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001886 case Stmt::CStyleCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001887 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001888 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenek54b52742008-08-07 00:49:01 +00001889 QualType T = SubExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001890
Steve Naroffdd972f22008-09-05 22:11:13 +00001891 if (SubExpr->getType()->isPointerType() ||
1892 SubExpr->getType()->isBlockPointerType() ||
1893 SubExpr->getType()->isObjCQualifiedIdType())
Ted Kremenek54b52742008-08-07 00:49:01 +00001894 return EvalAddr(SubExpr);
1895 else if (T->isArrayType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001896 return EvalVal(SubExpr);
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001897 else
Ted Kremenek54b52742008-08-07 00:49:01 +00001898 return 0;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001899 }
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001901 // C++ casts. For dynamic casts, static casts, and const casts, we
1902 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregor49badde2008-10-27 19:41:14 +00001903 // through the cast. In the case the dynamic cast doesn't fail (and
1904 // return NULL), we take the conservative route and report cases
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001905 // where we return the address of a stack variable. For Reinterpre
Douglas Gregor49badde2008-10-27 19:41:14 +00001906 // FIXME: The comment about is wrong; we're not always converting
1907 // from pointer to pointer. I'm guessing that this code should also
Mike Stump1eb44332009-09-09 15:08:12 +00001908 // handle references to objects.
1909 case Stmt::CXXStaticCastExprClass:
1910 case Stmt::CXXDynamicCastExprClass:
Douglas Gregor49badde2008-10-27 19:41:14 +00001911 case Stmt::CXXConstCastExprClass:
1912 case Stmt::CXXReinterpretCastExprClass: {
1913 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroffdd972f22008-09-05 22:11:13 +00001914 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001915 return EvalAddr(S);
1916 else
1917 return NULL;
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001918 }
Mike Stump1eb44332009-09-09 15:08:12 +00001919
Chris Lattnerfae3f1f2007-12-28 05:31:15 +00001920 // Everything else: we simply don't reason about them.
1921 default:
1922 return NULL;
1923 }
Ted Kremenek06de2762007-08-17 16:46:58 +00001924}
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Ted Kremenek06de2762007-08-17 16:46:58 +00001926
1927/// EvalVal - This function is complements EvalAddr in the mutual recursion.
1928/// See the comments for EvalAddr for more details.
1929static DeclRefExpr* EvalVal(Expr *E) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001930do {
Ted Kremeneke8c600f2007-08-28 17:02:55 +00001931 // We should only be called for evaluating non-pointer expressions, or
1932 // expressions with a pointer type that are not used as references but instead
1933 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump1eb44332009-09-09 15:08:12 +00001934
Ted Kremenek06de2762007-08-17 16:46:58 +00001935 // Our "symbolic interpreter" is just a dispatch off the currently
1936 // viewed AST node. We then recursively traverse the AST by calling
1937 // EvalAddr and EvalVal appropriately.
1938 switch (E->getStmtClass()) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001939 case Stmt::ImplicitCastExprClass: {
1940 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall5baba9d2010-08-25 10:28:54 +00001941 if (IE->getValueKind() == VK_LValue) {
Ted Kremenek68957a92010-08-04 20:01:07 +00001942 E = IE->getSubExpr();
1943 continue;
1944 }
1945 return NULL;
1946 }
1947
Douglas Gregora2813ce2009-10-23 18:54:35 +00001948 case Stmt::DeclRefExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001949 // DeclRefExpr: the base case. When we hit a DeclRefExpr we are looking
1950 // at code that refers to a variable's name. We check if it has local
1951 // storage within the function, and if so, return the expression.
1952 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001953
Ted Kremenek06de2762007-08-17 16:46:58 +00001954 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Mike Stump1eb44332009-09-09 15:08:12 +00001955 if (V->hasLocalStorage() && !V->getType()->isReferenceType()) return DR;
1956
Ted Kremenek06de2762007-08-17 16:46:58 +00001957 return NULL;
1958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Ted Kremenek68957a92010-08-04 20:01:07 +00001960 case Stmt::ParenExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00001961 // Ignore parentheses.
Ted Kremenek68957a92010-08-04 20:01:07 +00001962 E = cast<ParenExpr>(E)->getSubExpr();
1963 continue;
1964 }
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Ted Kremenek06de2762007-08-17 16:46:58 +00001966 case Stmt::UnaryOperatorClass: {
1967 // The only unary operator that make sense to handle here
1968 // is Deref. All others don't resolve to a "name." This includes
1969 // handling all sorts of rvalues passed to a unary operator.
1970 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001971
John McCall2de56d12010-08-25 11:45:40 +00001972 if (U->getOpcode() == UO_Deref)
Ted Kremenek06de2762007-08-17 16:46:58 +00001973 return EvalAddr(U->getSubExpr());
1974
1975 return NULL;
1976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Ted Kremenek06de2762007-08-17 16:46:58 +00001978 case Stmt::ArraySubscriptExprClass: {
1979 // Array subscripts are potential references to data on the stack. We
1980 // retrieve the DeclRefExpr* for the array variable if it indeed
1981 // has local storage.
Ted Kremenek23245122007-08-20 16:18:38 +00001982 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00001983 }
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Ted Kremenek06de2762007-08-17 16:46:58 +00001985 case Stmt::ConditionalOperatorClass: {
1986 // For conditional operators we need to see if either the LHS or RHS are
1987 // non-NULL DeclRefExpr's. If one is non-NULL, we return it.
1988 ConditionalOperator *C = cast<ConditionalOperator>(E);
1989
Anders Carlsson39073232007-11-30 19:04:31 +00001990 // Handle the GNU extension for missing LHS.
1991 if (Expr *lhsExpr = C->getLHS())
1992 if (DeclRefExpr *LHS = EvalVal(lhsExpr))
1993 return LHS;
1994
1995 return EvalVal(C->getRHS());
Ted Kremenek06de2762007-08-17 16:46:58 +00001996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Ted Kremenek06de2762007-08-17 16:46:58 +00001998 // Accesses to members are potential references to data on the stack.
Douglas Gregor83f6faf2009-08-31 23:41:50 +00001999 case Stmt::MemberExprClass: {
Ted Kremenek06de2762007-08-17 16:46:58 +00002000 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Ted Kremenek06de2762007-08-17 16:46:58 +00002002 // Check for indirect access. We only want direct field accesses.
Ted Kremeneka423e812010-09-02 01:12:13 +00002003 if (M->isArrow())
Ted Kremenek06de2762007-08-17 16:46:58 +00002004 return NULL;
Ted Kremeneka423e812010-09-02 01:12:13 +00002005
2006 // Check whether the member type is itself a reference, in which case
2007 // we're not going to refer to the member, but to what the member refers to.
2008 if (M->getMemberDecl()->getType()->isReferenceType())
2009 return NULL;
2010
2011 return EvalVal(M->getBase());
Ted Kremenek06de2762007-08-17 16:46:58 +00002012 }
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Ted Kremenek06de2762007-08-17 16:46:58 +00002014 // Everything else: we simply don't reason about them.
2015 default:
2016 return NULL;
2017 }
Ted Kremenek68957a92010-08-04 20:01:07 +00002018} while (true);
Ted Kremenek06de2762007-08-17 16:46:58 +00002019}
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002020
2021//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2022
2023/// Check for comparisons of floating point operands using != and ==.
2024/// Issue a warning if these are no self-comparisons, as they are not likely
2025/// to do what the programmer intended.
2026void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2027 bool EmitWarning = true;
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Ted Kremenek4e99a5f2008-01-17 16:57:34 +00002029 Expr* LeftExprSansParen = lex->IgnoreParens();
Ted Kremenek32e97b62008-01-17 17:55:13 +00002030 Expr* RightExprSansParen = rex->IgnoreParens();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002031
2032 // Special case: check for x == x (which is OK).
2033 // Do not emit warnings for such cases.
2034 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2035 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2036 if (DRL->getDecl() == DRR->getDecl())
2037 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002038
2039
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002040 // Special case: check for comparisons against literals that can be exactly
2041 // represented by APFloat. In such cases, do not emit a warning. This
2042 // is a heuristic: often comparison against such literals are used to
2043 // detect if a value in a variable has not changed. This clearly can
2044 // lead to false negatives.
2045 if (EmitWarning) {
2046 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2047 if (FLL->isExact())
2048 EmitWarning = false;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002049 } else
Ted Kremenek1b500bb2007-11-29 00:59:04 +00002050 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2051 if (FLR->isExact())
2052 EmitWarning = false;
2053 }
2054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002056 // Check for comparisons with builtin types.
Sebastian Redl0eb23302009-01-19 00:08:26 +00002057 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002058 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002059 if (CL->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002060 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Sebastian Redl0eb23302009-01-19 00:08:26 +00002062 if (EmitWarning)
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002063 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregor3c385e52009-02-14 18:57:46 +00002064 if (CR->isBuiltinCall(Context))
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002065 EmitWarning = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002067 // Emit the diagnostic.
2068 if (EmitWarning)
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002069 Diag(loc, diag::warn_floatingpoint_eq)
2070 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek588e5eb2007-11-25 00:58:00 +00002071}
John McCallba26e582010-01-04 23:21:16 +00002072
John McCallf2370c92010-01-06 05:24:50 +00002073//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2074//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallba26e582010-01-04 23:21:16 +00002075
John McCallf2370c92010-01-06 05:24:50 +00002076namespace {
John McCallba26e582010-01-04 23:21:16 +00002077
John McCallf2370c92010-01-06 05:24:50 +00002078/// Structure recording the 'active' range of an integer-valued
2079/// expression.
2080struct IntRange {
2081 /// The number of bits active in the int.
2082 unsigned Width;
John McCallba26e582010-01-04 23:21:16 +00002083
John McCallf2370c92010-01-06 05:24:50 +00002084 /// True if the int is known not to have negative values.
2085 bool NonNegative;
John McCallba26e582010-01-04 23:21:16 +00002086
John McCallf2370c92010-01-06 05:24:50 +00002087 IntRange(unsigned Width, bool NonNegative)
2088 : Width(Width), NonNegative(NonNegative)
2089 {}
John McCallba26e582010-01-04 23:21:16 +00002090
John McCall1844a6e2010-11-10 23:38:19 +00002091 /// Returns the range of the bool type.
John McCallf2370c92010-01-06 05:24:50 +00002092 static IntRange forBoolType() {
2093 return IntRange(1, true);
John McCall51313c32010-01-04 23:31:57 +00002094 }
2095
John McCall1844a6e2010-11-10 23:38:19 +00002096 /// Returns the range of an opaque value of the given integral type.
2097 static IntRange forValueOfType(ASTContext &C, QualType T) {
2098 return forValueOfCanonicalType(C,
2099 T->getCanonicalTypeInternal().getTypePtr());
John McCall51313c32010-01-04 23:31:57 +00002100 }
2101
John McCall1844a6e2010-11-10 23:38:19 +00002102 /// Returns the range of an opaque value of a canonical integral type.
2103 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCallf2370c92010-01-06 05:24:50 +00002104 assert(T->isCanonicalUnqualified());
2105
2106 if (const VectorType *VT = dyn_cast<VectorType>(T))
2107 T = VT->getElementType().getTypePtr();
2108 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2109 T = CT->getElementType().getTypePtr();
John McCall323ed742010-05-06 08:58:33 +00002110
John McCall091f23f2010-11-09 22:22:12 +00002111 // For enum types, use the known bit width of the enumerators.
John McCall323ed742010-05-06 08:58:33 +00002112 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2113 EnumDecl *Enum = ET->getDecl();
John McCall091f23f2010-11-09 22:22:12 +00002114 if (!Enum->isDefinition())
2115 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2116
John McCall323ed742010-05-06 08:58:33 +00002117 unsigned NumPositive = Enum->getNumPositiveBits();
2118 unsigned NumNegative = Enum->getNumNegativeBits();
2119
2120 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2121 }
John McCallf2370c92010-01-06 05:24:50 +00002122
2123 const BuiltinType *BT = cast<BuiltinType>(T);
2124 assert(BT->isInteger());
2125
2126 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2127 }
2128
John McCall1844a6e2010-11-10 23:38:19 +00002129 /// Returns the "target" range of a canonical integral type, i.e.
2130 /// the range of values expressible in the type.
2131 ///
2132 /// This matches forValueOfCanonicalType except that enums have the
2133 /// full range of their type, not the range of their enumerators.
2134 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2135 assert(T->isCanonicalUnqualified());
2136
2137 if (const VectorType *VT = dyn_cast<VectorType>(T))
2138 T = VT->getElementType().getTypePtr();
2139 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2140 T = CT->getElementType().getTypePtr();
2141 if (const EnumType *ET = dyn_cast<EnumType>(T))
2142 T = ET->getDecl()->getIntegerType().getTypePtr();
2143
2144 const BuiltinType *BT = cast<BuiltinType>(T);
2145 assert(BT->isInteger());
2146
2147 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2148 }
2149
2150 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002151 static IntRange join(IntRange L, IntRange R) {
John McCallf2370c92010-01-06 05:24:50 +00002152 return IntRange(std::max(L.Width, R.Width),
John McCall60fad452010-01-06 22:07:33 +00002153 L.NonNegative && R.NonNegative);
2154 }
2155
John McCall1844a6e2010-11-10 23:38:19 +00002156 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallc0cd21d2010-02-23 19:22:29 +00002157 static IntRange meet(IntRange L, IntRange R) {
John McCall60fad452010-01-06 22:07:33 +00002158 return IntRange(std::min(L.Width, R.Width),
2159 L.NonNegative || R.NonNegative);
John McCallf2370c92010-01-06 05:24:50 +00002160 }
2161};
2162
2163IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2164 if (value.isSigned() && value.isNegative())
2165 return IntRange(value.getMinSignedBits(), false);
2166
2167 if (value.getBitWidth() > MaxWidth)
2168 value.trunc(MaxWidth);
2169
2170 // isNonNegative() just checks the sign bit without considering
2171 // signedness.
2172 return IntRange(value.getActiveBits(), true);
2173}
2174
John McCall0acc3112010-01-06 22:57:21 +00002175IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCallf2370c92010-01-06 05:24:50 +00002176 unsigned MaxWidth) {
2177 if (result.isInt())
2178 return GetValueRange(C, result.getInt(), MaxWidth);
2179
2180 if (result.isVector()) {
John McCall0acc3112010-01-06 22:57:21 +00002181 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2182 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2183 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2184 R = IntRange::join(R, El);
2185 }
John McCallf2370c92010-01-06 05:24:50 +00002186 return R;
2187 }
2188
2189 if (result.isComplexInt()) {
2190 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2191 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2192 return IntRange::join(R, I);
John McCall51313c32010-01-04 23:31:57 +00002193 }
2194
2195 // This can happen with lossless casts to intptr_t of "based" lvalues.
2196 // Assume it might use arbitrary bits.
John McCall0acc3112010-01-06 22:57:21 +00002197 // FIXME: The only reason we need to pass the type in here is to get
2198 // the sign right on this one case. It would be nice if APValue
2199 // preserved this.
John McCallf2370c92010-01-06 05:24:50 +00002200 assert(result.isLValue());
John McCall0acc3112010-01-06 22:57:21 +00002201 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall51313c32010-01-04 23:31:57 +00002202}
John McCallf2370c92010-01-06 05:24:50 +00002203
2204/// Pseudo-evaluate the given integer expression, estimating the
2205/// range of values it might take.
2206///
2207/// \param MaxWidth - the width to which the value will be truncated
2208IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2209 E = E->IgnoreParens();
2210
2211 // Try a full evaluation first.
2212 Expr::EvalResult result;
2213 if (E->Evaluate(result, C))
John McCall0acc3112010-01-06 22:57:21 +00002214 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCallf2370c92010-01-06 05:24:50 +00002215
2216 // I think we only want to look through implicit casts here; if the
2217 // user has an explicit widening cast, we should treat the value as
2218 // being of the new, wider type.
2219 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00002220 if (CE->getCastKind() == CK_NoOp)
John McCallf2370c92010-01-06 05:24:50 +00002221 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2222
John McCall1844a6e2010-11-10 23:38:19 +00002223 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCallf2370c92010-01-06 05:24:50 +00002224
John McCall2de56d12010-08-25 11:45:40 +00002225 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall60fad452010-01-06 22:07:33 +00002226
John McCallf2370c92010-01-06 05:24:50 +00002227 // Assume that non-integer casts can span the full range of the type.
John McCall60fad452010-01-06 22:07:33 +00002228 if (!isIntegerCast)
John McCallf2370c92010-01-06 05:24:50 +00002229 return OutputTypeRange;
2230
2231 IntRange SubRange
2232 = GetExprRange(C, CE->getSubExpr(),
2233 std::min(MaxWidth, OutputTypeRange.Width));
2234
2235 // Bail out if the subexpr's range is as wide as the cast type.
2236 if (SubRange.Width >= OutputTypeRange.Width)
2237 return OutputTypeRange;
2238
2239 // Otherwise, we take the smaller width, and we're non-negative if
2240 // either the output type or the subexpr is.
2241 return IntRange(SubRange.Width,
2242 SubRange.NonNegative || OutputTypeRange.NonNegative);
2243 }
2244
2245 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2246 // If we can fold the condition, just take that operand.
2247 bool CondResult;
2248 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2249 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2250 : CO->getFalseExpr(),
2251 MaxWidth);
2252
2253 // Otherwise, conservatively merge.
2254 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2255 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2256 return IntRange::join(L, R);
2257 }
2258
2259 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2260 switch (BO->getOpcode()) {
2261
2262 // Boolean-valued operations are single-bit and positive.
John McCall2de56d12010-08-25 11:45:40 +00002263 case BO_LAnd:
2264 case BO_LOr:
2265 case BO_LT:
2266 case BO_GT:
2267 case BO_LE:
2268 case BO_GE:
2269 case BO_EQ:
2270 case BO_NE:
John McCallf2370c92010-01-06 05:24:50 +00002271 return IntRange::forBoolType();
2272
John McCallc0cd21d2010-02-23 19:22:29 +00002273 // The type of these compound assignments is the type of the LHS,
2274 // so the RHS is not necessarily an integer.
John McCall2de56d12010-08-25 11:45:40 +00002275 case BO_MulAssign:
2276 case BO_DivAssign:
2277 case BO_RemAssign:
2278 case BO_AddAssign:
2279 case BO_SubAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002280 return IntRange::forValueOfType(C, E->getType());
John McCallc0cd21d2010-02-23 19:22:29 +00002281
John McCallf2370c92010-01-06 05:24:50 +00002282 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002283 case BO_PtrMemD:
2284 case BO_PtrMemI:
John McCall1844a6e2010-11-10 23:38:19 +00002285 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002286
John McCall60fad452010-01-06 22:07:33 +00002287 // Bitwise-and uses the *infinum* of the two source ranges.
John McCall2de56d12010-08-25 11:45:40 +00002288 case BO_And:
2289 case BO_AndAssign:
John McCall60fad452010-01-06 22:07:33 +00002290 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2291 GetExprRange(C, BO->getRHS(), MaxWidth));
2292
John McCallf2370c92010-01-06 05:24:50 +00002293 // Left shift gets black-listed based on a judgement call.
John McCall2de56d12010-08-25 11:45:40 +00002294 case BO_Shl:
John McCall3aae6092010-04-07 01:14:35 +00002295 // ...except that we want to treat '1 << (blah)' as logically
2296 // positive. It's an important idiom.
2297 if (IntegerLiteral *I
2298 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2299 if (I->getValue() == 1) {
John McCall1844a6e2010-11-10 23:38:19 +00002300 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall3aae6092010-04-07 01:14:35 +00002301 return IntRange(R.Width, /*NonNegative*/ true);
2302 }
2303 }
2304 // fallthrough
2305
John McCall2de56d12010-08-25 11:45:40 +00002306 case BO_ShlAssign:
John McCall1844a6e2010-11-10 23:38:19 +00002307 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002308
John McCall60fad452010-01-06 22:07:33 +00002309 // Right shift by a constant can narrow its left argument.
John McCall2de56d12010-08-25 11:45:40 +00002310 case BO_Shr:
2311 case BO_ShrAssign: {
John McCall60fad452010-01-06 22:07:33 +00002312 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2313
2314 // If the shift amount is a positive constant, drop the width by
2315 // that much.
2316 llvm::APSInt shift;
2317 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2318 shift.isNonNegative()) {
2319 unsigned zext = shift.getZExtValue();
2320 if (zext >= L.Width)
2321 L.Width = (L.NonNegative ? 0 : 1);
2322 else
2323 L.Width -= zext;
2324 }
2325
2326 return L;
2327 }
2328
2329 // Comma acts as its right operand.
John McCall2de56d12010-08-25 11:45:40 +00002330 case BO_Comma:
John McCallf2370c92010-01-06 05:24:50 +00002331 return GetExprRange(C, BO->getRHS(), MaxWidth);
2332
John McCall60fad452010-01-06 22:07:33 +00002333 // Black-list pointer subtractions.
John McCall2de56d12010-08-25 11:45:40 +00002334 case BO_Sub:
John McCallf2370c92010-01-06 05:24:50 +00002335 if (BO->getLHS()->getType()->isPointerType())
John McCall1844a6e2010-11-10 23:38:19 +00002336 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002337 // fallthrough
Ted Kremenek4e4b30e2010-02-16 01:46:59 +00002338
John McCallf2370c92010-01-06 05:24:50 +00002339 default:
2340 break;
2341 }
2342
2343 // Treat every other operator as if it were closed on the
2344 // narrowest type that encompasses both operands.
2345 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2346 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2347 return IntRange::join(L, R);
2348 }
2349
2350 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2351 switch (UO->getOpcode()) {
2352 // Boolean-valued operations are white-listed.
John McCall2de56d12010-08-25 11:45:40 +00002353 case UO_LNot:
John McCallf2370c92010-01-06 05:24:50 +00002354 return IntRange::forBoolType();
2355
2356 // Operations with opaque sources are black-listed.
John McCall2de56d12010-08-25 11:45:40 +00002357 case UO_Deref:
2358 case UO_AddrOf: // should be impossible
John McCall1844a6e2010-11-10 23:38:19 +00002359 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002360
2361 default:
2362 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2363 }
2364 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002365
2366 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall1844a6e2010-11-10 23:38:19 +00002367 IntRange::forValueOfType(C, E->getType());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00002368 }
John McCallf2370c92010-01-06 05:24:50 +00002369
2370 FieldDecl *BitField = E->getBitField();
2371 if (BitField) {
2372 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2373 unsigned BitWidth = BitWidthAP.getZExtValue();
2374
2375 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2376 }
2377
John McCall1844a6e2010-11-10 23:38:19 +00002378 return IntRange::forValueOfType(C, E->getType());
John McCallf2370c92010-01-06 05:24:50 +00002379}
John McCall51313c32010-01-04 23:31:57 +00002380
John McCall323ed742010-05-06 08:58:33 +00002381IntRange GetExprRange(ASTContext &C, Expr *E) {
2382 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2383}
2384
John McCall51313c32010-01-04 23:31:57 +00002385/// Checks whether the given value, which currently has the given
2386/// source semantics, has the same value when coerced through the
2387/// target semantics.
John McCallf2370c92010-01-06 05:24:50 +00002388bool IsSameFloatAfterCast(const llvm::APFloat &value,
2389 const llvm::fltSemantics &Src,
2390 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002391 llvm::APFloat truncated = value;
2392
2393 bool ignored;
2394 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2395 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2396
2397 return truncated.bitwiseIsEqual(value);
2398}
2399
2400/// Checks whether the given value, which currently has the given
2401/// source semantics, has the same value when coerced through the
2402/// target semantics.
2403///
2404/// The value might be a vector of floats (or a complex number).
John McCallf2370c92010-01-06 05:24:50 +00002405bool IsSameFloatAfterCast(const APValue &value,
2406 const llvm::fltSemantics &Src,
2407 const llvm::fltSemantics &Tgt) {
John McCall51313c32010-01-04 23:31:57 +00002408 if (value.isFloat())
2409 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2410
2411 if (value.isVector()) {
2412 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2413 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2414 return false;
2415 return true;
2416 }
2417
2418 assert(value.isComplexFloat());
2419 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2420 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2421}
2422
John McCallb4eb64d2010-10-08 02:01:28 +00002423void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCall323ed742010-05-06 08:58:33 +00002424
Ted Kremeneke3b159c2010-09-23 21:43:44 +00002425static bool IsZero(Sema &S, Expr *E) {
2426 // Suppress cases where we are comparing against an enum constant.
2427 if (const DeclRefExpr *DR =
2428 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2429 if (isa<EnumConstantDecl>(DR->getDecl()))
2430 return false;
2431
2432 // Suppress cases where the '0' value is expanded from a macro.
2433 if (E->getLocStart().isMacroID())
2434 return false;
2435
John McCall323ed742010-05-06 08:58:33 +00002436 llvm::APSInt Value;
2437 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2438}
2439
John McCall372e1032010-10-06 00:25:24 +00002440static bool HasEnumType(Expr *E) {
2441 // Strip off implicit integral promotions.
2442 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002443 if (ICE->getCastKind() != CK_IntegralCast &&
2444 ICE->getCastKind() != CK_NoOp)
John McCall372e1032010-10-06 00:25:24 +00002445 break;
Argyrios Kyrtzidis63b57ae2010-10-07 21:52:18 +00002446 E = ICE->getSubExpr();
John McCall372e1032010-10-06 00:25:24 +00002447 }
2448
2449 return E->getType()->isEnumeralType();
2450}
2451
John McCall323ed742010-05-06 08:58:33 +00002452void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002453 BinaryOperatorKind op = E->getOpcode();
2454 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002455 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002456 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002457 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002458 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCall323ed742010-05-06 08:58:33 +00002459 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002460 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCall323ed742010-05-06 08:58:33 +00002461 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002462 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002463 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002464 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002465 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCall2de56d12010-08-25 11:45:40 +00002466 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCall323ed742010-05-06 08:58:33 +00002467 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall372e1032010-10-06 00:25:24 +00002468 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCall323ed742010-05-06 08:58:33 +00002469 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2470 }
2471}
2472
2473/// Analyze the operands of the given comparison. Implements the
2474/// fallback case from AnalyzeComparison.
2475void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallb4eb64d2010-10-08 02:01:28 +00002476 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2477 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCall323ed742010-05-06 08:58:33 +00002478}
John McCall51313c32010-01-04 23:31:57 +00002479
John McCallba26e582010-01-04 23:21:16 +00002480/// \brief Implements -Wsign-compare.
2481///
2482/// \param lex the left-hand expression
2483/// \param rex the right-hand expression
2484/// \param OpLoc the location of the joining operator
John McCalld1b47bf2010-03-11 19:43:18 +00002485/// \param BinOpc binary opcode or 0
John McCall323ed742010-05-06 08:58:33 +00002486void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2487 // The type the comparison is being performed in.
2488 QualType T = E->getLHS()->getType();
2489 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2490 && "comparison with mismatched types");
John McCallba26e582010-01-04 23:21:16 +00002491
John McCall323ed742010-05-06 08:58:33 +00002492 // We don't do anything special if this isn't an unsigned integral
2493 // comparison: we're only interested in integral comparisons, and
2494 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregorf6094622010-07-23 15:58:24 +00002495 if (!T->hasUnsignedIntegerRepresentation())
John McCall323ed742010-05-06 08:58:33 +00002496 return AnalyzeImpConvsInComparison(S, E);
John McCallf2370c92010-01-06 05:24:50 +00002497
John McCall323ed742010-05-06 08:58:33 +00002498 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2499 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallba26e582010-01-04 23:21:16 +00002500
John McCall323ed742010-05-06 08:58:33 +00002501 // Check to see if one of the (unmodified) operands is of different
2502 // signedness.
2503 Expr *signedOperand, *unsignedOperand;
Douglas Gregorf6094622010-07-23 15:58:24 +00002504 if (lex->getType()->hasSignedIntegerRepresentation()) {
2505 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCall323ed742010-05-06 08:58:33 +00002506 "unsigned comparison between two signed integer expressions?");
2507 signedOperand = lex;
2508 unsignedOperand = rex;
Douglas Gregorf6094622010-07-23 15:58:24 +00002509 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCall323ed742010-05-06 08:58:33 +00002510 signedOperand = rex;
2511 unsignedOperand = lex;
John McCallba26e582010-01-04 23:21:16 +00002512 } else {
John McCall323ed742010-05-06 08:58:33 +00002513 CheckTrivialUnsignedComparison(S, E);
2514 return AnalyzeImpConvsInComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002515 }
2516
John McCall323ed742010-05-06 08:58:33 +00002517 // Otherwise, calculate the effective range of the signed operand.
2518 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCallf2370c92010-01-06 05:24:50 +00002519
John McCall323ed742010-05-06 08:58:33 +00002520 // Go ahead and analyze implicit conversions in the operands. Note
2521 // that we skip the implicit conversions on both sides.
John McCallb4eb64d2010-10-08 02:01:28 +00002522 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2523 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallba26e582010-01-04 23:21:16 +00002524
John McCall323ed742010-05-06 08:58:33 +00002525 // If the signed range is non-negative, -Wsign-compare won't fire,
2526 // but we should still check for comparisons which are always true
2527 // or false.
2528 if (signedRange.NonNegative)
2529 return CheckTrivialUnsignedComparison(S, E);
John McCallba26e582010-01-04 23:21:16 +00002530
2531 // For (in)equality comparisons, if the unsigned operand is a
2532 // constant which cannot collide with a overflowed signed operand,
2533 // then reinterpreting the signed operand as unsigned will not
2534 // change the result of the comparison.
John McCall323ed742010-05-06 08:58:33 +00002535 if (E->isEqualityOp()) {
2536 unsigned comparisonWidth = S.Context.getIntWidth(T);
2537 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallba26e582010-01-04 23:21:16 +00002538
John McCall323ed742010-05-06 08:58:33 +00002539 // We should never be unable to prove that the unsigned operand is
2540 // non-negative.
2541 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2542
2543 if (unsignedRange.Width < comparisonWidth)
2544 return;
2545 }
2546
2547 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2548 << lex->getType() << rex->getType()
2549 << lex->getSourceRange() << rex->getSourceRange();
John McCallba26e582010-01-04 23:21:16 +00002550}
2551
John McCall15d7d122010-11-11 03:21:53 +00002552/// Analyzes an attempt to assign the given value to a bitfield.
2553///
2554/// Returns true if there was something fishy about the attempt.
2555bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2556 SourceLocation InitLoc) {
2557 assert(Bitfield->isBitField());
2558 if (Bitfield->isInvalidDecl())
2559 return false;
2560
John McCall91b60142010-11-11 05:33:51 +00002561 // White-list bool bitfields.
2562 if (Bitfield->getType()->isBooleanType())
2563 return false;
2564
John McCall15d7d122010-11-11 03:21:53 +00002565 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2566
2567 llvm::APSInt Width(32);
2568 Expr::EvalResult InitValue;
2569 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCall91b60142010-11-11 05:33:51 +00002570 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall15d7d122010-11-11 03:21:53 +00002571 !InitValue.Val.isInt())
2572 return false;
2573
2574 const llvm::APSInt &Value = InitValue.Val.getInt();
2575 unsigned OriginalWidth = Value.getBitWidth();
2576 unsigned FieldWidth = Width.getZExtValue();
2577
2578 if (OriginalWidth <= FieldWidth)
2579 return false;
2580
2581 llvm::APSInt TruncatedValue = Value;
2582 TruncatedValue.trunc(FieldWidth);
2583
2584 // It's fairly common to write values into signed bitfields
2585 // that, if sign-extended, would end up becoming a different
2586 // value. We don't want to warn about that.
2587 if (Value.isSigned() && Value.isNegative())
2588 TruncatedValue.sext(OriginalWidth);
2589 else
2590 TruncatedValue.zext(OriginalWidth);
2591
2592 if (Value == TruncatedValue)
2593 return false;
2594
2595 std::string PrettyValue = Value.toString(10);
2596 std::string PrettyTrunc = TruncatedValue.toString(10);
2597
2598 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2599 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2600 << Init->getSourceRange();
2601
2602 return true;
2603}
2604
John McCallbeb22aa2010-11-09 23:24:47 +00002605/// Analyze the given simple or compound assignment for warning-worthy
2606/// operations.
2607void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2608 // Just recurse on the LHS.
2609 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2610
2611 // We want to recurse on the RHS as normal unless we're assigning to
2612 // a bitfield.
2613 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall15d7d122010-11-11 03:21:53 +00002614 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2615 E->getOperatorLoc())) {
2616 // Recurse, ignoring any implicit conversions on the RHS.
2617 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2618 E->getOperatorLoc());
John McCallbeb22aa2010-11-09 23:24:47 +00002619 }
2620 }
2621
2622 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2623}
2624
John McCall51313c32010-01-04 23:31:57 +00002625/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallb4eb64d2010-10-08 02:01:28 +00002626void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2627 unsigned diag) {
2628 S.Diag(E->getExprLoc(), diag)
2629 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall51313c32010-01-04 23:31:57 +00002630}
2631
John McCall091f23f2010-11-09 22:22:12 +00002632std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2633 if (!Range.Width) return "0";
2634
2635 llvm::APSInt ValueInRange = Value;
2636 ValueInRange.setIsSigned(!Range.NonNegative);
2637 ValueInRange.trunc(Range.Width);
2638 return ValueInRange.toString(10);
2639}
2640
John McCall323ed742010-05-06 08:58:33 +00002641void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002642 SourceLocation CC, bool *ICContext = 0) {
John McCall323ed742010-05-06 08:58:33 +00002643 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall51313c32010-01-04 23:31:57 +00002644
John McCall323ed742010-05-06 08:58:33 +00002645 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2646 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2647 if (Source == Target) return;
2648 if (Target->isDependentType()) return;
John McCall51313c32010-01-04 23:31:57 +00002649
John McCallb4eb64d2010-10-08 02:01:28 +00002650 // If the conversion context location is invalid or instantiated
2651 // from a system macro, don't complain.
2652 if (CC.isInvalid() ||
2653 (CC.isMacroID() && S.Context.getSourceManager().isInSystemHeader(
2654 S.Context.getSourceManager().getSpellingLoc(CC))))
2655 return;
2656
John McCall51313c32010-01-04 23:31:57 +00002657 // Never diagnose implicit casts to bool.
2658 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2659 return;
2660
2661 // Strip vector types.
2662 if (isa<VectorType>(Source)) {
2663 if (!isa<VectorType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002664 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
John McCall51313c32010-01-04 23:31:57 +00002665
2666 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2667 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2668 }
2669
2670 // Strip complex types.
2671 if (isa<ComplexType>(Source)) {
2672 if (!isa<ComplexType>(Target))
John McCallb4eb64d2010-10-08 02:01:28 +00002673 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
John McCall51313c32010-01-04 23:31:57 +00002674
2675 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2676 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2677 }
2678
2679 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2680 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2681
2682 // If the source is floating point...
2683 if (SourceBT && SourceBT->isFloatingPoint()) {
2684 // ...and the target is floating point...
2685 if (TargetBT && TargetBT->isFloatingPoint()) {
2686 // ...then warn if we're dropping FP rank.
2687
2688 // Builtin FP kinds are ordered by increasing FP rank.
2689 if (SourceBT->getKind() > TargetBT->getKind()) {
2690 // Don't warn about float constants that are precisely
2691 // representable in the target type.
2692 Expr::EvalResult result;
John McCall323ed742010-05-06 08:58:33 +00002693 if (E->Evaluate(result, S.Context)) {
John McCall51313c32010-01-04 23:31:57 +00002694 // Value might be a float, a float vector, or a float complex.
2695 if (IsSameFloatAfterCast(result.Val,
John McCall323ed742010-05-06 08:58:33 +00002696 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2697 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall51313c32010-01-04 23:31:57 +00002698 return;
2699 }
2700
John McCallb4eb64d2010-10-08 02:01:28 +00002701 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall51313c32010-01-04 23:31:57 +00002702 }
2703 return;
2704 }
2705
2706 // If the target is integral, always warn.
2707 if ((TargetBT && TargetBT->isInteger()))
2708 // TODO: don't warn for integer values?
John McCallb4eb64d2010-10-08 02:01:28 +00002709 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
John McCall51313c32010-01-04 23:31:57 +00002710
2711 return;
2712 }
2713
John McCallf2370c92010-01-06 05:24:50 +00002714 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall51313c32010-01-04 23:31:57 +00002715 return;
2716
John McCall323ed742010-05-06 08:58:33 +00002717 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall1844a6e2010-11-10 23:38:19 +00002718 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCallf2370c92010-01-06 05:24:50 +00002719
2720 if (SourceRange.Width > TargetRange.Width) {
John McCall091f23f2010-11-09 22:22:12 +00002721 // If the source is a constant, use a default-on diagnostic.
2722 // TODO: this should happen for bitfield stores, too.
2723 llvm::APSInt Value(32);
2724 if (E->isIntegerConstantExpr(Value, S.Context)) {
2725 std::string PrettySourceValue = Value.toString(10);
2726 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2727
2728 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2729 << PrettySourceValue << PrettyTargetValue
2730 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2731 return;
2732 }
2733
John McCall51313c32010-01-04 23:31:57 +00002734 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2735 // and by god we'll let them.
John McCallf2370c92010-01-06 05:24:50 +00002736 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallb4eb64d2010-10-08 02:01:28 +00002737 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2738 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCall323ed742010-05-06 08:58:33 +00002739 }
2740
2741 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2742 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2743 SourceRange.Width == TargetRange.Width)) {
2744 unsigned DiagID = diag::warn_impcast_integer_sign;
2745
2746 // Traditionally, gcc has warned about this under -Wsign-compare.
2747 // We also want to warn about it in -Wconversion.
2748 // So if -Wconversion is off, use a completely identical diagnostic
2749 // in the sign-compare group.
2750 // The conditional-checking code will
2751 if (ICContext) {
2752 DiagID = diag::warn_impcast_integer_sign_conditional;
2753 *ICContext = true;
2754 }
2755
John McCallb4eb64d2010-10-08 02:01:28 +00002756 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall51313c32010-01-04 23:31:57 +00002757 }
2758
2759 return;
2760}
2761
John McCall323ed742010-05-06 08:58:33 +00002762void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2763
2764void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallb4eb64d2010-10-08 02:01:28 +00002765 SourceLocation CC, bool &ICContext) {
John McCall323ed742010-05-06 08:58:33 +00002766 E = E->IgnoreParenImpCasts();
2767
2768 if (isa<ConditionalOperator>(E))
2769 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2770
John McCallb4eb64d2010-10-08 02:01:28 +00002771 AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002772 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002773 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCall323ed742010-05-06 08:58:33 +00002774 return;
2775}
2776
2777void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallb4eb64d2010-10-08 02:01:28 +00002778 SourceLocation CC = E->getQuestionLoc();
2779
2780 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCall323ed742010-05-06 08:58:33 +00002781
2782 bool Suspicious = false;
John McCallb4eb64d2010-10-08 02:01:28 +00002783 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2784 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002785
2786 // If -Wconversion would have warned about either of the candidates
2787 // for a signedness conversion to the context type...
2788 if (!Suspicious) return;
2789
2790 // ...but it's currently ignored...
2791 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional))
2792 return;
2793
2794 // ...and -Wsign-compare isn't...
2795 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional))
2796 return;
2797
2798 // ...then check whether it would have warned about either of the
2799 // candidates for a signedness conversion to the condition type.
2800 if (E->getType() != T) {
2801 Suspicious = false;
2802 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002803 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002804 if (!Suspicious)
2805 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallb4eb64d2010-10-08 02:01:28 +00002806 E->getType(), CC, &Suspicious);
John McCall323ed742010-05-06 08:58:33 +00002807 if (!Suspicious)
2808 return;
2809 }
2810
2811 // If so, emit a diagnostic under -Wsign-compare.
2812 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
2813 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
2814 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
2815 << lex->getType() << rex->getType()
2816 << lex->getSourceRange() << rex->getSourceRange();
2817}
2818
2819/// AnalyzeImplicitConversions - Find and report any interesting
2820/// implicit conversions in the given expression. There are a couple
2821/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002822void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002823 QualType T = OrigE->getType();
2824 Expr *E = OrigE->IgnoreParenImpCasts();
2825
2826 // For conditional operators, we analyze the arguments as if they
2827 // were being fed directly into the output.
2828 if (isa<ConditionalOperator>(E)) {
2829 ConditionalOperator *CO = cast<ConditionalOperator>(E);
2830 CheckConditionalOperator(S, CO, T);
2831 return;
2832 }
2833
2834 // Go ahead and check any implicit conversions we might have skipped.
2835 // The non-canonical typecheck is just an optimization;
2836 // CheckImplicitConversion will filter out dead implicit conversions.
2837 if (E->getType() != T)
John McCallb4eb64d2010-10-08 02:01:28 +00002838 CheckImplicitConversion(S, E, T, CC);
John McCall323ed742010-05-06 08:58:33 +00002839
2840 // Now continue drilling into this expression.
2841
2842 // Skip past explicit casts.
2843 if (isa<ExplicitCastExpr>(E)) {
2844 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallb4eb64d2010-10-08 02:01:28 +00002845 return AnalyzeImplicitConversions(S, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002846 }
2847
John McCallbeb22aa2010-11-09 23:24:47 +00002848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2849 // Do a somewhat different check with comparison operators.
2850 if (BO->isComparisonOp())
2851 return AnalyzeComparison(S, BO);
2852
2853 // And with assignments and compound assignments.
2854 if (BO->isAssignmentOp())
2855 return AnalyzeAssignment(S, BO);
2856 }
John McCall323ed742010-05-06 08:58:33 +00002857
2858 // These break the otherwise-useful invariant below. Fortunately,
2859 // we don't really need to recurse into them, because any internal
2860 // expressions should have been analyzed already when they were
2861 // built into statements.
2862 if (isa<StmtExpr>(E)) return;
2863
2864 // Don't descend into unevaluated contexts.
2865 if (isa<SizeOfAlignOfExpr>(E)) return;
2866
2867 // Now just recurse over the expression's children.
John McCallb4eb64d2010-10-08 02:01:28 +00002868 CC = E->getExprLoc();
John McCall323ed742010-05-06 08:58:33 +00002869 for (Stmt::child_iterator I = E->child_begin(), IE = E->child_end();
2870 I != IE; ++I)
John McCallb4eb64d2010-10-08 02:01:28 +00002871 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCall323ed742010-05-06 08:58:33 +00002872}
2873
2874} // end anonymous namespace
2875
2876/// Diagnoses "dangerous" implicit conversions within the given
2877/// expression (which is a full expression). Implements -Wconversion
2878/// and -Wsign-compare.
John McCallb4eb64d2010-10-08 02:01:28 +00002879///
2880/// \param CC the "context" location of the implicit conversion, i.e.
2881/// the most location of the syntactic entity requiring the implicit
2882/// conversion
2883void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCall323ed742010-05-06 08:58:33 +00002884 // Don't diagnose in unevaluated contexts.
2885 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
2886 return;
2887
2888 // Don't diagnose for value- or type-dependent expressions.
2889 if (E->isTypeDependent() || E->isValueDependent())
2890 return;
2891
John McCallb4eb64d2010-10-08 02:01:28 +00002892 // This is not the right CC for (e.g.) a variable initialization.
2893 AnalyzeImplicitConversions(*this, E, CC);
John McCall323ed742010-05-06 08:58:33 +00002894}
2895
John McCall15d7d122010-11-11 03:21:53 +00002896void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
2897 FieldDecl *BitField,
2898 Expr *Init) {
2899 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
2900}
2901
Mike Stumpf8c49212010-01-21 03:59:47 +00002902/// CheckParmsForFunctionDef - Check that the parameters of the given
2903/// function are appropriate for the definition of a function. This
2904/// takes care of any checks that cannot be performed on the
2905/// declaration itself, e.g., that the types of each of the function
2906/// parameters are complete.
Douglas Gregor82aa7132010-11-01 18:37:59 +00002907bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
2908 bool CheckParameterNames) {
Mike Stumpf8c49212010-01-21 03:59:47 +00002909 bool HasInvalidParm = false;
Douglas Gregor82aa7132010-11-01 18:37:59 +00002910 for (; P != PEnd; ++P) {
2911 ParmVarDecl *Param = *P;
2912
Mike Stumpf8c49212010-01-21 03:59:47 +00002913 // C99 6.7.5.3p4: the parameters in a parameter type list in a
2914 // function declarator that is part of a function definition of
2915 // that function shall not have incomplete type.
2916 //
2917 // This is also C++ [dcl.fct]p6.
2918 if (!Param->isInvalidDecl() &&
2919 RequireCompleteType(Param->getLocation(), Param->getType(),
2920 diag::err_typecheck_decl_incomplete_type)) {
2921 Param->setInvalidDecl();
2922 HasInvalidParm = true;
2923 }
2924
2925 // C99 6.9.1p5: If the declarator includes a parameter type list, the
2926 // declaration of each parameter shall include an identifier.
Douglas Gregor82aa7132010-11-01 18:37:59 +00002927 if (CheckParameterNames &&
2928 Param->getIdentifier() == 0 &&
Mike Stumpf8c49212010-01-21 03:59:47 +00002929 !Param->isImplicit() &&
2930 !getLangOptions().CPlusPlus)
2931 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigd17e3402010-02-01 05:02:49 +00002932
2933 // C99 6.7.5.3p12:
2934 // If the function declarator is not part of a definition of that
2935 // function, parameters may have incomplete type and may use the [*]
2936 // notation in their sequences of declarator specifiers to specify
2937 // variable length array types.
2938 QualType PType = Param->getOriginalType();
2939 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
2940 if (AT->getSizeModifier() == ArrayType::Star) {
2941 // FIXME: This diagnosic should point the the '[*]' if source-location
2942 // information is added for it.
2943 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
2944 }
2945 }
Mike Stumpf8c49212010-01-21 03:59:47 +00002946 }
2947
2948 return HasInvalidParm;
2949}
John McCallb7f4ffe2010-08-12 21:44:57 +00002950
2951/// CheckCastAlign - Implements -Wcast-align, which warns when a
2952/// pointer cast increases the alignment requirements.
2953void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
2954 // This is actually a lot of work to potentially be doing on every
2955 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
2956 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align)
2957 == Diagnostic::Ignored)
2958 return;
2959
2960 // Ignore dependent types.
2961 if (T->isDependentType() || Op->getType()->isDependentType())
2962 return;
2963
2964 // Require that the destination be a pointer type.
2965 const PointerType *DestPtr = T->getAs<PointerType>();
2966 if (!DestPtr) return;
2967
2968 // If the destination has alignment 1, we're done.
2969 QualType DestPointee = DestPtr->getPointeeType();
2970 if (DestPointee->isIncompleteType()) return;
2971 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
2972 if (DestAlign.isOne()) return;
2973
2974 // Require that the source be a pointer type.
2975 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
2976 if (!SrcPtr) return;
2977 QualType SrcPointee = SrcPtr->getPointeeType();
2978
2979 // Whitelist casts from cv void*. We already implicitly
2980 // whitelisted casts to cv void*, since they have alignment 1.
2981 // Also whitelist casts involving incomplete types, which implicitly
2982 // includes 'void'.
2983 if (SrcPointee->isIncompleteType()) return;
2984
2985 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
2986 if (SrcAlign >= DestAlign) return;
2987
2988 Diag(TRange.getBegin(), diag::warn_cast_align)
2989 << Op->getType() << T
2990 << static_cast<unsigned>(SrcAlign.getQuantity())
2991 << static_cast<unsigned>(DestAlign.getQuantity())
2992 << TRange << Op->getSourceRange();
2993}
2994