blob: de5a796410854bd70d7f7ce709cf2541bee48d82 [file] [log] [blame]
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001//===--- SemaChecking.cpp - Extra Semantic Checking -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnerb87b1b32007-08-10 20:18:51 +00007//
8//===----------------------------------------------------------------------===//
9//
Mike Stump11289f42009-09-09 15:08:12 +000010// This file implements extra semantic analysis beyond what is enforced
Chris Lattnerb87b1b32007-08-10 20:18:51 +000011// by the C type system.
12//
13//===----------------------------------------------------------------------===//
14
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Sema.h"
John McCall83024632010-08-25 22:03:47 +000016#include "clang/Sema/SemaInternal.h"
John McCallaab3e412010-08-25 08:40:02 +000017#include "clang/Sema/ScopeInfo.h"
Ted Kremenek02087932010-07-16 02:11:22 +000018#include "clang/Analysis/Analyses/FormatString.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000019#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000020#include "clang/AST/CharUnits.h"
John McCall28a0cf72010-08-25 07:42:41 +000021#include "clang/AST/DeclCXX.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000022#include "clang/AST/DeclObjC.h"
Ted Kremenekc81614d2007-08-20 16:18:38 +000023#include "clang/AST/ExprCXX.h"
Ted Kremenek34f664d2008-06-16 18:00:42 +000024#include "clang/AST/ExprObjC.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000025#include "clang/AST/DeclObjC.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/AST/StmtObjC.h"
Chris Lattnerb87b1b32007-08-10 20:18:51 +000028#include "clang/Lex/Preprocessor.h"
Mike Stump0c2ec772010-01-21 03:59:47 +000029#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/STLExtras.h"
Tom Careb7042702010-06-09 04:11:11 +000031#include "llvm/Support/raw_ostream.h"
Eric Christopher8d0c6212010-04-17 02:26:23 +000032#include "clang/Basic/TargetBuiltins.h"
Nate Begeman4904e322010-06-08 02:47:44 +000033#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian56603ef2010-09-07 19:38:13 +000034#include "clang/Basic/ConvertUTF.h"
Zhongxing Xu050379b2009-05-20 01:55:10 +000035#include <limits>
Chris Lattnerb87b1b32007-08-10 20:18:51 +000036using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000037using namespace sema;
Chris Lattnerb87b1b32007-08-10 20:18:51 +000038
Chris Lattnera26fb342009-02-18 17:49:48 +000039SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
40 unsigned ByteNo) const {
Chris Lattnere925d612010-11-17 07:37:15 +000041 return SL->getLocationOfByte(ByteNo, PP.getSourceManager(),
42 PP.getLangOptions(), PP.getTargetInfo());
Chris Lattnera26fb342009-02-18 17:49:48 +000043}
Chris Lattnere925d612010-11-17 07:37:15 +000044
Chris Lattnera26fb342009-02-18 17:49:48 +000045
Ryan Flynnaa5e5fd2009-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 Redl6eedcc12009-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 Flynnaa5e5fd2009-08-06 03:00:50 +000059 if (format_idx < TheCall->getNumArgs()) {
60 Expr *Format = TheCall->getArg(format_idx)->IgnoreParenCasts();
Ted Kremenekd1668192010-02-27 01:41:03 +000061 if (!Format->isNullPointerConstant(Context,
62 Expr::NPC_ValueDependentIsNull))
Ryan Flynnaa5e5fd2009-08-06 03:00:50 +000063 return true;
64 }
65 }
66 return false;
67}
Chris Lattnera26fb342009-02-18 17:49:48 +000068
John McCallbebede42011-02-26 05:39:39 +000069/// Checks that a call expression's argument count is the desired number.
70/// This is useful when doing custom type-checking. Returns true on error.
71static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
72 unsigned argCount = call->getNumArgs();
73 if (argCount == desiredArgCount) return false;
74
75 if (argCount < desiredArgCount)
76 return S.Diag(call->getLocEnd(), diag::err_typecheck_call_too_few_args)
77 << 0 /*function call*/ << desiredArgCount << argCount
78 << call->getSourceRange();
79
80 // Highlight all the excess arguments.
81 SourceRange range(call->getArg(desiredArgCount)->getLocStart(),
82 call->getArg(argCount - 1)->getLocEnd());
83
84 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
85 << 0 /*function call*/ << desiredArgCount << argCount
86 << call->getArg(1)->getSourceRange();
87}
88
John McCalldadc5752010-08-24 06:29:42 +000089ExprResult
Anders Carlssonbc4c1072009-08-16 01:56:34 +000090Sema::CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
John McCalldadc5752010-08-24 06:29:42 +000091 ExprResult TheCallResult(Owned(TheCall));
Douglas Gregorae2fbad2008-11-17 20:34:05 +000092
Chris Lattner3be167f2010-10-01 23:23:24 +000093 // Find out if any arguments are required to be integer constant expressions.
94 unsigned ICEArguments = 0;
95 ASTContext::GetBuiltinTypeError Error;
96 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
97 if (Error != ASTContext::GE_None)
98 ICEArguments = 0; // Don't diagnose previously diagnosed errors.
99
100 // If any arguments are required to be ICE's, check and diagnose.
101 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
102 // Skip arguments not required to be ICE's.
103 if ((ICEArguments & (1 << ArgNo)) == 0) continue;
104
105 llvm::APSInt Result;
106 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
107 return true;
108 ICEArguments &= ~(1 << ArgNo);
109 }
110
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000111 switch (BuiltinID) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000112 case Builtin::BI__builtin___CFStringMakeConstantString:
Chris Lattner08464942007-12-28 05:29:59 +0000113 assert(TheCall->getNumArgs() == 1 &&
Chris Lattner2da14fb2007-12-20 00:26:33 +0000114 "Wrong # arguments to builtin CFStringMakeConstantString");
Chris Lattner6436fb62009-02-18 06:01:06 +0000115 if (CheckObjCString(TheCall->getArg(0)))
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000116 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000117 break;
Ted Kremeneka174c522008-07-09 17:58:53 +0000118 case Builtin::BI__builtin_stdarg_start:
Chris Lattner43be2e62007-12-19 23:59:04 +0000119 case Builtin::BI__builtin_va_start:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000120 if (SemaBuiltinVAStart(TheCall))
121 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000122 break;
Chris Lattner2da14fb2007-12-20 00:26:33 +0000123 case Builtin::BI__builtin_isgreater:
124 case Builtin::BI__builtin_isgreaterequal:
125 case Builtin::BI__builtin_isless:
126 case Builtin::BI__builtin_islessequal:
127 case Builtin::BI__builtin_islessgreater:
128 case Builtin::BI__builtin_isunordered:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000129 if (SemaBuiltinUnorderedCompare(TheCall))
130 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000131 break;
Benjamin Kramer634fc102010-02-15 22:42:31 +0000132 case Builtin::BI__builtin_fpclassify:
133 if (SemaBuiltinFPClassification(TheCall, 6))
134 return ExprError();
135 break;
Eli Friedman7e4faac2009-08-31 20:06:00 +0000136 case Builtin::BI__builtin_isfinite:
137 case Builtin::BI__builtin_isinf:
138 case Builtin::BI__builtin_isinf_sign:
139 case Builtin::BI__builtin_isnan:
140 case Builtin::BI__builtin_isnormal:
Benjamin Kramer64aae502010-02-16 10:07:31 +0000141 if (SemaBuiltinFPClassification(TheCall, 1))
Eli Friedman7e4faac2009-08-31 20:06:00 +0000142 return ExprError();
143 break;
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000144 case Builtin::BI__builtin_shufflevector:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000145 return SemaBuiltinShuffleVector(TheCall);
146 // TheCall will be freed by the smart pointer here, but that's fine, since
147 // SemaBuiltinShuffleVector guts it, but then doesn't release it.
Daniel Dunbarb7257262008-07-21 22:59:13 +0000148 case Builtin::BI__builtin_prefetch:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000149 if (SemaBuiltinPrefetch(TheCall))
150 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000151 break;
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000152 case Builtin::BI__builtin_object_size:
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000153 if (SemaBuiltinObjectSize(TheCall))
154 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000155 break;
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000156 case Builtin::BI__builtin_longjmp:
157 if (SemaBuiltinLongjmp(TheCall))
158 return ExprError();
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000159 break;
John McCallbebede42011-02-26 05:39:39 +0000160
161 case Builtin::BI__builtin_classify_type:
162 if (checkArgCount(*this, TheCall, 1)) return true;
163 TheCall->setType(Context.IntTy);
164 break;
Chris Lattner17c0eac2010-10-12 17:47:42 +0000165 case Builtin::BI__builtin_constant_p:
John McCallbebede42011-02-26 05:39:39 +0000166 if (checkArgCount(*this, TheCall, 1)) return true;
167 TheCall->setType(Context.IntTy);
Chris Lattner17c0eac2010-10-12 17:47:42 +0000168 break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000169 case Builtin::BI__sync_fetch_and_add:
170 case Builtin::BI__sync_fetch_and_sub:
171 case Builtin::BI__sync_fetch_and_or:
172 case Builtin::BI__sync_fetch_and_and:
173 case Builtin::BI__sync_fetch_and_xor:
174 case Builtin::BI__sync_add_and_fetch:
175 case Builtin::BI__sync_sub_and_fetch:
176 case Builtin::BI__sync_and_and_fetch:
177 case Builtin::BI__sync_or_and_fetch:
178 case Builtin::BI__sync_xor_and_fetch:
179 case Builtin::BI__sync_val_compare_and_swap:
180 case Builtin::BI__sync_bool_compare_and_swap:
181 case Builtin::BI__sync_lock_test_and_set:
182 case Builtin::BI__sync_lock_release:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000183 return SemaBuiltinAtomicOverloaded(move(TheCallResult));
Nate Begeman4904e322010-06-08 02:47:44 +0000184 }
185
186 // Since the target specific builtins for each arch overlap, only check those
187 // of the arch we are compiling for.
188 if (BuiltinID >= Builtin::FirstTSBuiltin) {
189 switch (Context.Target.getTriple().getArch()) {
190 case llvm::Triple::arm:
191 case llvm::Triple::thumb:
192 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
193 return ExprError();
194 break;
Nate Begeman4904e322010-06-08 02:47:44 +0000195 default:
196 break;
197 }
198 }
199
200 return move(TheCallResult);
201}
202
Nate Begeman91e1fea2010-06-14 05:21:25 +0000203// Get the valid immediate range for the specified NEON type code.
204static unsigned RFT(unsigned t, bool shift = false) {
205 bool quad = t & 0x10;
206
207 switch (t & 0x7) {
208 case 0: // i8
Nate Begemandbafec12010-06-17 02:26:59 +0000209 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000210 case 1: // i16
Nate Begemandbafec12010-06-17 02:26:59 +0000211 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000212 case 2: // i32
Nate Begemandbafec12010-06-17 02:26:59 +0000213 return shift ? 31 : (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000214 case 3: // i64
Nate Begemandbafec12010-06-17 02:26:59 +0000215 return shift ? 63 : (1 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000216 case 4: // f32
217 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000218 return (2 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000219 case 5: // poly8
Bob Wilsona880fa02010-12-10 19:45:06 +0000220 return shift ? 7 : (8 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000221 case 6: // poly16
Bob Wilsona880fa02010-12-10 19:45:06 +0000222 return shift ? 15 : (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000223 case 7: // float16
224 assert(!shift && "cannot shift float types!");
Nate Begemandbafec12010-06-17 02:26:59 +0000225 return (4 << (int)quad) - 1;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000226 }
227 return 0;
228}
229
Nate Begeman4904e322010-06-08 02:47:44 +0000230bool Sema::CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
Nate Begeman55483092010-06-09 01:10:23 +0000231 llvm::APSInt Result;
232
Nate Begemand773fe62010-06-13 04:47:52 +0000233 unsigned mask = 0;
Nate Begeman91e1fea2010-06-14 05:21:25 +0000234 unsigned TV = 0;
Nate Begeman55483092010-06-09 01:10:23 +0000235 switch (BuiltinID) {
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000236#define GET_NEON_OVERLOAD_CHECK
237#include "clang/Basic/arm_neon.inc"
238#undef GET_NEON_OVERLOAD_CHECK
Nate Begeman55483092010-06-09 01:10:23 +0000239 }
240
Nate Begemand773fe62010-06-13 04:47:52 +0000241 // For NEON intrinsics which are overloaded on vector element type, validate
242 // the immediate which specifies which variant to emit.
243 if (mask) {
244 unsigned ArgNo = TheCall->getNumArgs()-1;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
246 return true;
247
Nate Begeman91e1fea2010-06-14 05:21:25 +0000248 TV = Result.getLimitedValue(32);
249 if ((TV > 31) || (mask & (1 << TV)) == 0)
Nate Begemand773fe62010-06-13 04:47:52 +0000250 return Diag(TheCall->getLocStart(), diag::err_invalid_neon_type_code)
251 << TheCall->getArg(ArgNo)->getSourceRange();
252 }
Nate Begeman55483092010-06-09 01:10:23 +0000253
Nate Begemand773fe62010-06-13 04:47:52 +0000254 // For NEON intrinsics which take an immediate value as part of the
255 // instruction, range check them here.
Nate Begeman91e1fea2010-06-14 05:21:25 +0000256 unsigned i = 0, l = 0, u = 0;
Nate Begemand773fe62010-06-13 04:47:52 +0000257 switch (BuiltinID) {
258 default: return false;
Nate Begeman1194bd22010-07-29 22:48:34 +0000259 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31; break;
260 case ARM::BI__builtin_arm_usat: i = 1; u = 31; break;
Nate Begemanf568b072010-08-03 21:32:34 +0000261 case ARM::BI__builtin_arm_vcvtr_f:
262 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1; break;
Nate Begeman35f4c1c2010-06-17 04:17:01 +0000263#define GET_NEON_IMMEDIATE_CHECK
264#include "clang/Basic/arm_neon.inc"
265#undef GET_NEON_IMMEDIATE_CHECK
Nate Begemand773fe62010-06-13 04:47:52 +0000266 };
267
Nate Begeman91e1fea2010-06-14 05:21:25 +0000268 // Check that the immediate argument is actually a constant.
Nate Begemand773fe62010-06-13 04:47:52 +0000269 if (SemaBuiltinConstantArg(TheCall, i, Result))
270 return true;
271
Nate Begeman91e1fea2010-06-14 05:21:25 +0000272 // Range check against the upper/lower values for this isntruction.
Nate Begemand773fe62010-06-13 04:47:52 +0000273 unsigned Val = Result.getZExtValue();
Nate Begeman91e1fea2010-06-14 05:21:25 +0000274 if (Val < l || Val > (u + l))
Nate Begemand773fe62010-06-13 04:47:52 +0000275 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Benjamin Kramere8394df2010-08-11 14:47:12 +0000276 << l << u+l << TheCall->getArg(i)->getSourceRange();
Nate Begemand773fe62010-06-13 04:47:52 +0000277
Nate Begemanf568b072010-08-03 21:32:34 +0000278 // FIXME: VFP Intrinsics should error if VFP not present.
Nate Begeman4904e322010-06-08 02:47:44 +0000279 return false;
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000280}
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000281
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000282/// CheckFunctionCall - Check a direct function call for various correctness
283/// and safety properties not strictly enforced by the C type system.
284bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall) {
285 // Get the IdentifierInfo* for the called function.
286 IdentifierInfo *FnInfo = FDecl->getIdentifier();
287
288 // None of the checks below are needed for functions that don't have
289 // simple names (e.g., C++ conversion functions).
290 if (!FnInfo)
291 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000292
Daniel Dunbardd9b2d12008-10-02 18:44:07 +0000293 // FIXME: This mechanism should be abstracted to be less fragile and
294 // more efficient. For example, just map function ids to custom
295 // handlers.
296
Ted Kremenekb8176da2010-09-09 04:33:05 +0000297 // Printf and scanf checking.
298 for (specific_attr_iterator<FormatAttr>
299 i = FDecl->specific_attr_begin<FormatAttr>(),
300 e = FDecl->specific_attr_end<FormatAttr>(); i != e ; ++i) {
301
302 const FormatAttr *Format = *i;
Ted Kremenek02087932010-07-16 02:11:22 +0000303 const bool b = Format->getType() == "scanf";
304 if (b || CheckablePrintfAttr(Format, TheCall)) {
Ted Kremenek9723bcf2009-02-27 17:58:43 +0000305 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000306 CheckPrintfScanfArguments(TheCall, HasVAListArg,
307 Format->getFormatIdx() - 1,
308 HasVAListArg ? 0 : Format->getFirstArg() - 1,
309 !b);
Douglas Gregore711f702009-02-14 18:57:46 +0000310 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000311 }
Mike Stump11289f42009-09-09 15:08:12 +0000312
Ted Kremenekb8176da2010-09-09 04:33:05 +0000313 for (specific_attr_iterator<NonNullAttr>
314 i = FDecl->specific_attr_begin<NonNullAttr>(),
315 e = FDecl->specific_attr_end<NonNullAttr>(); i != e; ++i) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000316 CheckNonNullArguments(*i, TheCall);
Ted Kremenekb8176da2010-09-09 04:33:05 +0000317 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000318
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000319 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000320}
321
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000322bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000323 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000324 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000325 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000326 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000327
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000328 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
329 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000330 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000331
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000332 QualType Ty = V->getType();
333 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000334 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000335
Ted Kremenek02087932010-07-16 02:11:22 +0000336 const bool b = Format->getType() == "scanf";
337 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000338 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000339
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000340 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000341 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
342 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000343
344 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000345}
346
Chris Lattnerdc046542009-05-08 06:58:22 +0000347/// SemaBuiltinAtomicOverloaded - We have a call to a function like
348/// __sync_fetch_and_add, which is an overloaded function based on the pointer
349/// type of its first argument. The main ActOnCallExpr routines have already
350/// promoted the types of arguments because all of these calls are prototyped as
351/// void(...).
352///
353/// This function goes through and does final semantic checking for these
354/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000355ExprResult
356Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000357 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000358 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
359 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
360
361 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000362 if (TheCall->getNumArgs() < 1) {
363 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
364 << 0 << 1 << TheCall->getNumArgs()
365 << TheCall->getCallee()->getSourceRange();
366 return ExprError();
367 }
Mike Stump11289f42009-09-09 15:08:12 +0000368
Chris Lattnerdc046542009-05-08 06:58:22 +0000369 // Inspect the first argument of the atomic builtin. This should always be
370 // a pointer type, whose element is an integral scalar or pointer type.
371 // Because it is a pointer type, we don't have to worry about any implicit
372 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000373 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000374 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000375 if (!FirstArg->getType()->isPointerType()) {
376 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
377 << FirstArg->getType() << FirstArg->getSourceRange();
378 return ExprError();
379 }
Mike Stump11289f42009-09-09 15:08:12 +0000380
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000381 QualType ValType =
382 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000383 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000384 !ValType->isBlockPointerType()) {
385 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
386 << FirstArg->getType() << FirstArg->getSourceRange();
387 return ExprError();
388 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000389
Chandler Carruth3973af72010-07-18 20:54:12 +0000390 // The majority of builtins return a value, but a few have special return
391 // types, so allow them to override appropriately below.
392 QualType ResultType = ValType;
393
Chris Lattnerdc046542009-05-08 06:58:22 +0000394 // We need to figure out which concrete builtin this maps onto. For example,
395 // __sync_fetch_and_add with a 2 byte object turns into
396 // __sync_fetch_and_add_2.
397#define BUILTIN_ROW(x) \
398 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
399 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
Chris Lattnerdc046542009-05-08 06:58:22 +0000401 static const unsigned BuiltinIndices[][5] = {
402 BUILTIN_ROW(__sync_fetch_and_add),
403 BUILTIN_ROW(__sync_fetch_and_sub),
404 BUILTIN_ROW(__sync_fetch_and_or),
405 BUILTIN_ROW(__sync_fetch_and_and),
406 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattnerdc046542009-05-08 06:58:22 +0000408 BUILTIN_ROW(__sync_add_and_fetch),
409 BUILTIN_ROW(__sync_sub_and_fetch),
410 BUILTIN_ROW(__sync_and_and_fetch),
411 BUILTIN_ROW(__sync_or_and_fetch),
412 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000413
Chris Lattnerdc046542009-05-08 06:58:22 +0000414 BUILTIN_ROW(__sync_val_compare_and_swap),
415 BUILTIN_ROW(__sync_bool_compare_and_swap),
416 BUILTIN_ROW(__sync_lock_test_and_set),
417 BUILTIN_ROW(__sync_lock_release)
418 };
Mike Stump11289f42009-09-09 15:08:12 +0000419#undef BUILTIN_ROW
420
Chris Lattnerdc046542009-05-08 06:58:22 +0000421 // Determine the index of the size.
422 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000423 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000424 case 1: SizeIndex = 0; break;
425 case 2: SizeIndex = 1; break;
426 case 4: SizeIndex = 2; break;
427 case 8: SizeIndex = 3; break;
428 case 16: SizeIndex = 4; break;
429 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000430 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
431 << FirstArg->getType() << FirstArg->getSourceRange();
432 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000433 }
Mike Stump11289f42009-09-09 15:08:12 +0000434
Chris Lattnerdc046542009-05-08 06:58:22 +0000435 // Each of these builtins has one pointer argument, followed by some number of
436 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
437 // that we ignore. Find out which row of BuiltinIndices to read from as well
438 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000439 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000440 unsigned BuiltinIndex, NumFixed = 1;
441 switch (BuiltinID) {
442 default: assert(0 && "Unknown overloaded atomic builtin!");
443 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
444 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
445 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
446 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
447 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump11289f42009-09-09 15:08:12 +0000448
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000449 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
450 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
451 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
452 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
453 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump11289f42009-09-09 15:08:12 +0000454
Chris Lattnerdc046542009-05-08 06:58:22 +0000455 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000456 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000457 NumFixed = 2;
458 break;
459 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000460 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000461 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000462 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000463 break;
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000464 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000465 case Builtin::BI__sync_lock_release:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000466 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000467 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000468 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000469 break;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattnerdc046542009-05-08 06:58:22 +0000472 // Now that we know how many fixed arguments we expect, first check that we
473 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000474 if (TheCall->getNumArgs() < 1+NumFixed) {
475 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
476 << 0 << 1+NumFixed << TheCall->getNumArgs()
477 << TheCall->getCallee()->getSourceRange();
478 return ExprError();
479 }
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner5b9241b2009-05-08 15:36:58 +0000481 // Get the decl for the concrete builtin from this, we can tell what the
482 // concrete integer type we should convert to is.
483 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
484 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
485 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000486 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000487 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
488 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000489
John McCallcf142162010-08-07 06:22:56 +0000490 // The first argument --- the pointer --- has a fixed type; we
491 // deduce the types of the rest of the arguments accordingly. Walk
492 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000493 for (unsigned i = 0; i != NumFixed; ++i) {
494 Expr *Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000495
Chris Lattnerdc046542009-05-08 06:58:22 +0000496 // If the argument is an implicit cast, then there was a promotion due to
497 // "...", just remove it now.
498 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) {
499 Arg = ICE->getSubExpr();
500 ICE->setSubExpr(0);
Chris Lattnerdc046542009-05-08 06:58:22 +0000501 TheCall->setArg(i+1, Arg);
502 }
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattnerdc046542009-05-08 06:58:22 +0000504 // GCC does an implicit conversion to the pointer or integer ValType. This
505 // can fail in some cases (1i -> int**), check for this error case now.
John McCall8cb679e2010-11-15 09:13:47 +0000506 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000507 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000508 CXXCastPath BasePath;
John McCall7decc9e2010-11-18 06:31:45 +0000509 if (CheckCastTypes(Arg->getSourceRange(), ValType, Arg, Kind, VK, BasePath))
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000510 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattnerdc046542009-05-08 06:58:22 +0000512 // Okay, we have something that *can* be converted to the right type. Check
513 // to see if there is a potentially weird extension going on here. This can
514 // happen when you do an atomic operation on something like an char* and
515 // pass in 42. The 42 gets converted to char. This is even more strange
516 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000517 // FIXME: Do this check.
John McCall7decc9e2010-11-18 06:31:45 +0000518 ImpCastExprToType(Arg, ValType, Kind, VK, &BasePath);
Chris Lattnerdc046542009-05-08 06:58:22 +0000519 TheCall->setArg(i+1, Arg);
520 }
Mike Stump11289f42009-09-09 15:08:12 +0000521
Chris Lattnerdc046542009-05-08 06:58:22 +0000522 // Switch the DeclRefExpr to refer to the new decl.
523 DRE->setDecl(NewBuiltinDecl);
524 DRE->setType(NewBuiltinDecl->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattnerdc046542009-05-08 06:58:22 +0000526 // Set the callee in the CallExpr.
527 // FIXME: This leaks the original parens and implicit casts.
528 Expr *PromotedCall = DRE;
529 UsualUnaryConversions(PromotedCall);
530 TheCall->setCallee(PromotedCall);
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000532 // Change the result type of the call to match the original value type. This
533 // is arbitrary, but the codegen for these builtins ins design to handle it
534 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000535 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000536
537 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +0000538}
539
540
Chris Lattner6436fb62009-02-18 06:01:06 +0000541/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000542/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000543/// Note: It might also make sense to do the UTF-16 conversion here (would
544/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000545bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000546 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000547 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
548
549 if (!Literal || Literal->isWide()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000550 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
551 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000552 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000553 }
Mike Stump11289f42009-09-09 15:08:12 +0000554
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000555 if (Literal->containsNonAsciiOrNull()) {
556 llvm::StringRef String = Literal->getString();
557 unsigned NumBytes = String.size();
558 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
559 const UTF8 *FromPtr = (UTF8 *)String.data();
560 UTF16 *ToPtr = &ToBuf[0];
561
562 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
563 &ToPtr, ToPtr + NumBytes,
564 strictConversion);
565 // Check for conversion failure.
566 if (Result != conversionOK)
567 Diag(Arg->getLocStart(),
568 diag::warn_cfstring_truncated) << Arg->getSourceRange();
569 }
Anders Carlssona3a9c432007-08-17 15:44:17 +0000570 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000571}
572
Chris Lattnere202e6a2007-12-20 00:05:45 +0000573/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
574/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000575bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
576 Expr *Fn = TheCall->getCallee();
577 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000578 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000579 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000580 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
581 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000582 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000583 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000584 return true;
585 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000586
587 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +0000588 return Diag(TheCall->getLocEnd(),
589 diag::err_typecheck_call_too_few_args_at_least)
590 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000591 }
592
Chris Lattnere202e6a2007-12-20 00:05:45 +0000593 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000594 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +0000595 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000596 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +0000597 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +0000598 else if (FunctionDecl *FD = getCurFunctionDecl())
599 isVariadic = FD->isVariadic();
600 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000601 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000602
Chris Lattnere202e6a2007-12-20 00:05:45 +0000603 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000604 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
605 return true;
606 }
Mike Stump11289f42009-09-09 15:08:12 +0000607
Chris Lattner43be2e62007-12-19 23:59:04 +0000608 // Verify that the second argument to the builtin is the last argument of the
609 // current function or method.
610 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000611 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000612
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000613 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
614 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000615 // FIXME: This isn't correct for methods (results in bogus warning).
616 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000617 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000618 if (CurBlock)
619 LastArg = *(CurBlock->TheDecl->param_end()-1);
620 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000621 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000622 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000623 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000624 SecondArgIsLastNamedArgument = PV == LastArg;
625 }
626 }
Mike Stump11289f42009-09-09 15:08:12 +0000627
Chris Lattner43be2e62007-12-19 23:59:04 +0000628 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000629 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +0000630 diag::warn_second_parameter_of_va_start_not_last_named_argument);
631 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +0000632}
Chris Lattner43be2e62007-12-19 23:59:04 +0000633
Chris Lattner2da14fb2007-12-20 00:26:33 +0000634/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
635/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +0000636bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
637 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000638 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000639 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +0000640 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +0000641 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000642 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000643 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +0000644 << SourceRange(TheCall->getArg(2)->getLocStart(),
645 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000646
Chris Lattner08464942007-12-28 05:29:59 +0000647 Expr *OrigArg0 = TheCall->getArg(0);
648 Expr *OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000649
Chris Lattner2da14fb2007-12-20 00:26:33 +0000650 // Do standard promotions between the two arguments, returning their common
651 // type.
Chris Lattner08464942007-12-28 05:29:59 +0000652 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
Daniel Dunbar96f86772009-02-19 19:28:43 +0000653
654 // Make sure any conversions are pushed back into the call; this is
655 // type safe since unordered compare builtins are declared as "_Bool
656 // foo(...)".
657 TheCall->setArg(0, OrigArg0);
658 TheCall->setArg(1, OrigArg1);
Mike Stump11289f42009-09-09 15:08:12 +0000659
Douglas Gregorc25f7662009-05-19 22:10:17 +0000660 if (OrigArg0->isTypeDependent() || OrigArg1->isTypeDependent())
661 return false;
662
Chris Lattner2da14fb2007-12-20 00:26:33 +0000663 // If the common type isn't a real floating type, then the arguments were
664 // invalid for this operation.
665 if (!Res->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000666 return Diag(OrigArg0->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000667 diag::err_typecheck_call_invalid_ordered_compare)
Chris Lattner1e5665e2008-11-24 06:25:27 +0000668 << OrigArg0->getType() << OrigArg1->getType()
Chris Lattner3b054132008-11-19 05:08:23 +0000669 << SourceRange(OrigArg0->getLocStart(), OrigArg1->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000670
Chris Lattner2da14fb2007-12-20 00:26:33 +0000671 return false;
672}
673
Benjamin Kramer634fc102010-02-15 22:42:31 +0000674/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
675/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +0000676/// to check everything. We expect the last argument to be a floating point
677/// value.
678bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
679 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +0000680 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000681 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +0000682 if (TheCall->getNumArgs() > NumArgs)
683 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000684 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000685 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +0000686 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000687 (*(TheCall->arg_end()-1))->getLocEnd());
688
Benjamin Kramer64aae502010-02-16 10:07:31 +0000689 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +0000690
Eli Friedman7e4faac2009-08-31 20:06:00 +0000691 if (OrigArg->isTypeDependent())
692 return false;
693
Chris Lattner68784ef2010-05-06 05:50:07 +0000694 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +0000695 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000696 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000697 diag::err_typecheck_call_invalid_unary_fp)
698 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000699
Chris Lattner68784ef2010-05-06 05:50:07 +0000700 // If this is an implicit conversion from float -> double, remove it.
701 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
702 Expr *CastArg = Cast->getSubExpr();
703 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
704 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
705 "promotion from float to double is the only expected cast here");
706 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +0000707 TheCall->setArg(NumArgs-1, CastArg);
708 OrigArg = CastArg;
709 }
710 }
711
Eli Friedman7e4faac2009-08-31 20:06:00 +0000712 return false;
713}
714
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000715/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
716// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +0000717ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +0000718 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000719 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +0000720 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +0000721 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +0000722 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000723
Nate Begemana0110022010-06-08 00:16:34 +0000724 // Determine which of the following types of shufflevector we're checking:
725 // 1) unary, vector mask: (lhs, mask)
726 // 2) binary, vector mask: (lhs, rhs, mask)
727 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
728 QualType resType = TheCall->getArg(0)->getType();
729 unsigned numElements = 0;
730
Douglas Gregorc25f7662009-05-19 22:10:17 +0000731 if (!TheCall->getArg(0)->isTypeDependent() &&
732 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +0000733 QualType LHSType = TheCall->getArg(0)->getType();
734 QualType RHSType = TheCall->getArg(1)->getType();
735
736 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000737 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000738 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000739 TheCall->getArg(1)->getLocEnd());
740 return ExprError();
741 }
Nate Begemana0110022010-06-08 00:16:34 +0000742
743 numElements = LHSType->getAs<VectorType>()->getNumElements();
744 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +0000745
Nate Begemana0110022010-06-08 00:16:34 +0000746 // Check to see if we have a call with 2 vector arguments, the unary shuffle
747 // with mask. If so, verify that RHS is an integer vector type with the
748 // same number of elts as lhs.
749 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +0000750 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +0000751 RHSType->getAs<VectorType>()->getNumElements() != numElements)
752 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
753 << SourceRange(TheCall->getArg(1)->getLocStart(),
754 TheCall->getArg(1)->getLocEnd());
755 numResElements = numElements;
756 }
757 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000758 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000759 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000760 TheCall->getArg(1)->getLocEnd());
761 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +0000762 } else if (numElements != numResElements) {
763 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +0000764 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000765 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000766 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000767 }
768
769 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000770 if (TheCall->getArg(i)->isTypeDependent() ||
771 TheCall->getArg(i)->isValueDependent())
772 continue;
773
Nate Begemana0110022010-06-08 00:16:34 +0000774 llvm::APSInt Result(32);
775 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
776 return ExprError(Diag(TheCall->getLocStart(),
777 diag::err_shufflevector_nonconstant_argument)
778 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000779
Chris Lattner7ab824e2008-08-10 02:05:13 +0000780 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000781 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000782 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000783 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000784 }
785
786 llvm::SmallVector<Expr*, 32> exprs;
787
Chris Lattner7ab824e2008-08-10 02:05:13 +0000788 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000789 exprs.push_back(TheCall->getArg(i));
790 TheCall->setArg(i, 0);
791 }
792
Nate Begemanf485fb52009-08-12 02:10:25 +0000793 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +0000794 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +0000795 TheCall->getCallee()->getLocStart(),
796 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000797}
Chris Lattner43be2e62007-12-19 23:59:04 +0000798
Daniel Dunbarb7257262008-07-21 22:59:13 +0000799/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
800// This is declared to take (const void*, ...) and can take two
801// optional constant int args.
802bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +0000803 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804
Chris Lattner3b054132008-11-19 05:08:23 +0000805 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000806 return Diag(TheCall->getLocEnd(),
807 diag::err_typecheck_call_too_many_args_at_most)
808 << 0 /*function call*/ << 3 << NumArgs
809 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000810
811 // Argument 0 is checked for us and the remaining arguments must be
812 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +0000813 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +0000814 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000815
Eli Friedman5efba262009-12-04 00:30:06 +0000816 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +0000817 if (SemaBuiltinConstantArg(TheCall, i, Result))
818 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000819
Daniel Dunbarb7257262008-07-21 22:59:13 +0000820 // FIXME: gcc issues a warning and rewrites these to 0. These
821 // seems especially odd for the third argument since the default
822 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +0000823 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +0000824 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +0000825 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000826 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000827 } else {
Eli Friedman5efba262009-12-04 00:30:06 +0000828 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +0000829 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000830 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000831 }
832 }
833
Chris Lattner3b054132008-11-19 05:08:23 +0000834 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +0000835}
836
Eric Christopher8d0c6212010-04-17 02:26:23 +0000837/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
838/// TheCall is a constant expression.
839bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
840 llvm::APSInt &Result) {
841 Expr *Arg = TheCall->getArg(ArgNum);
842 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
843 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
844
845 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
846
847 if (!Arg->isIntegerConstantExpr(Result, Context))
848 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +0000849 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +0000850
Chris Lattnerd545ad12009-09-23 06:06:36 +0000851 return false;
852}
853
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000854/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
855/// int type). This simply type checks that type is one of the defined
856/// constants (0-3).
Eric Christopherc8791562009-12-23 03:49:37 +0000857// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000858bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +0000859 llvm::APSInt Result;
860
861 // Check constant-ness first.
862 if (SemaBuiltinConstantArg(TheCall, 1, Result))
863 return true;
864
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000865 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000866 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +0000867 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
868 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000869 }
870
871 return false;
872}
873
Eli Friedmanc97d0142009-05-03 06:04:26 +0000874/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000875/// This checks that val is a constant 1.
876bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
877 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000878 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +0000879
Eric Christopher8d0c6212010-04-17 02:26:23 +0000880 // TODO: This is less than ideal. Overload this to take a value.
881 if (SemaBuiltinConstantArg(TheCall, 1, Result))
882 return true;
883
884 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000885 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
886 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
887
888 return false;
889}
890
Ted Kremeneka8890832011-02-24 23:03:04 +0000891// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000892bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
893 bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000894 unsigned format_idx, unsigned firstDataArg,
895 bool isPrintf) {
Ted Kremenek808829352010-09-09 03:51:39 +0000896 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +0000897 if (E->isTypeDependent() || E->isValueDependent())
898 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000899
900 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +0000901 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000902 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +0000903 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek02087932010-07-16 02:11:22 +0000904 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
905 format_idx, firstDataArg, isPrintf)
John McCallc07a0c72011-02-17 10:25:35 +0000906 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000907 format_idx, firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000908 }
909
Ted Kremenek1520dae2010-09-09 03:51:42 +0000910 case Stmt::IntegerLiteralClass:
911 // Technically -Wformat-nonliteral does not warn about this case.
912 // The behavior of printf and friends in this case is implementation
913 // dependent. Ideally if the format string cannot be null then
914 // it should have a 'nonnull' attribute in the function prototype.
915 return true;
916
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000917 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000918 E = cast<ImplicitCastExpr>(E)->getSubExpr();
919 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000920 }
921
922 case Stmt::ParenExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000923 E = cast<ParenExpr>(E)->getSubExpr();
924 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000925 }
Mike Stump11289f42009-09-09 15:08:12 +0000926
John McCallc07a0c72011-02-17 10:25:35 +0000927 case Stmt::OpaqueValueExprClass:
928 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
929 E = src;
930 goto tryAgain;
931 }
932 return false;
933
Ted Kremeneka8890832011-02-24 23:03:04 +0000934 case Stmt::PredefinedExprClass:
935 // While __func__, etc., are technically not string literals, they
936 // cannot contain format specifiers and thus are not a security
937 // liability.
938 return true;
939
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000940 case Stmt::DeclRefExprClass: {
941 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000942
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000943 // As an exception, do not flag errors for variables binding to
944 // const string literals.
945 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
946 bool isConstant = false;
947 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000948
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000949 if (const ArrayType *AT = Context.getAsArrayType(T)) {
950 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +0000951 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000952 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000953 PT->getPointeeType().isConstant(Context);
954 }
Mike Stump11289f42009-09-09 15:08:12 +0000955
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000956 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000957 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000958 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek02087932010-07-16 02:11:22 +0000959 HasVAListArg, format_idx, firstDataArg,
960 isPrintf);
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000961 }
Mike Stump11289f42009-09-09 15:08:12 +0000962
Anders Carlssonb012ca92009-06-28 19:55:58 +0000963 // For vprintf* functions (i.e., HasVAListArg==true), we add a
964 // special check to see if the format string is a function parameter
965 // of the function calling the printf function. If the function
966 // has an attribute indicating it is a printf-like function, then we
967 // should suppress warnings concerning non-literals being used in a call
968 // to a vprintf function. For example:
969 //
970 // void
971 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
972 // va_list ap;
973 // va_start(ap, fmt);
974 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
975 // ...
976 //
977 //
978 // FIXME: We don't have full attribute support yet, so just check to see
979 // if the argument is a DeclRefExpr that references a parameter. We'll
980 // add proper support for checking the attribute later.
981 if (HasVAListArg)
982 if (isa<ParmVarDecl>(VD))
983 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000984 }
Mike Stump11289f42009-09-09 15:08:12 +0000985
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000986 return false;
987 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000988
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000989 case Stmt::CallExprClass: {
990 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000991 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000992 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
993 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
994 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000995 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000996 unsigned ArgIndex = FA->getFormatIdx();
997 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +0000998
999 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001000 format_idx, firstDataArg, isPrintf);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001001 }
1002 }
1003 }
1004 }
Mike Stump11289f42009-09-09 15:08:12 +00001005
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001006 return false;
1007 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001008 case Stmt::ObjCStringLiteralClass:
1009 case Stmt::StringLiteralClass: {
1010 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001011
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001012 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001013 StrE = ObjCFExpr->getString();
1014 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001015 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001016
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001017 if (StrE) {
Ted Kremenek02087932010-07-16 02:11:22 +00001018 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1019 firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001020 return true;
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001023 return false;
1024 }
Mike Stump11289f42009-09-09 15:08:12 +00001025
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001026 default:
1027 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001028 }
1029}
1030
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001031void
Mike Stump11289f42009-09-09 15:08:12 +00001032Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
1033 const CallExpr *TheCall) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001034 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1035 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001036 i != e; ++i) {
Chris Lattner23464b82009-05-25 18:23:36 +00001037 const Expr *ArgExpr = TheCall->getArg(*i);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001038 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001039 Expr::NPC_ValueDependentIsNotNull))
Chris Lattner23464b82009-05-25 18:23:36 +00001040 Diag(TheCall->getCallee()->getLocStart(), diag::warn_null_arg)
1041 << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001042 }
1043}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001044
Ted Kremenek02087932010-07-16 02:11:22 +00001045/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1046/// functions) for correct use of format strings.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001047void
Ted Kremenek02087932010-07-16 02:11:22 +00001048Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1049 unsigned format_idx, unsigned firstDataArg,
1050 bool isPrintf) {
1051
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001052 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +00001053
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001054 // The way the format attribute works in GCC, the implicit this argument
1055 // of member functions is counted. However, it doesn't appear in our own
1056 // lists, so decrement format_idx in that case.
1057 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth1c8383d2010-11-16 08:49:43 +00001058 const CXXMethodDecl *method_decl =
1059 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1060 if (method_decl && method_decl->isInstance()) {
1061 // Catch a format attribute mistakenly referring to the object argument.
1062 if (format_idx == 0)
1063 return;
1064 --format_idx;
1065 if(firstDataArg != 0)
1066 --firstDataArg;
1067 }
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001068 }
1069
Ted Kremenek02087932010-07-16 02:11:22 +00001070 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +00001071 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001072 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerf490e152008-11-19 05:27:50 +00001073 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001074 return;
1075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001077 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001078
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001079 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001080 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001081 // Dynamically generated format strings are difficult to
1082 // automatically vet at compile time. Requiring that format strings
1083 // are string literals: (1) permits the checking of format strings by
1084 // the compiler and thereby (2) can practically remove the source of
1085 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001086
Mike Stump11289f42009-09-09 15:08:12 +00001087 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001088 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001089 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001090 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001091 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek02087932010-07-16 02:11:22 +00001092 firstDataArg, isPrintf))
Chris Lattnere009a882009-04-29 04:49:34 +00001093 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001094
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001095 // If there are no arguments specified, warn with -Wformat-security, otherwise
1096 // warn only with -Wformat-nonliteral.
1097 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001098 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001099 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001100 << OrigFormatExpr->getSourceRange();
1101 else
Mike Stump11289f42009-09-09 15:08:12 +00001102 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001103 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001104 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001105}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001106
Ted Kremenekab278de2010-01-28 23:39:18 +00001107namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001108class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1109protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001110 Sema &S;
1111 const StringLiteral *FExpr;
1112 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001113 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001114 const unsigned NumDataArgs;
1115 const bool IsObjCLiteral;
1116 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001117 const bool HasVAListArg;
1118 const CallExpr *TheCall;
1119 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001120 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001121 bool usesPositionalArgs;
1122 bool atFirstArg;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001123public:
Ted Kremenek02087932010-07-16 02:11:22 +00001124 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001125 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001126 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001127 const char *beg, bool hasVAListArg,
1128 const CallExpr *theCall, unsigned formatIdx)
Ted Kremenekab278de2010-01-28 23:39:18 +00001129 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001130 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001131 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001132 IsObjCLiteral(isObjCLiteral), Beg(beg),
1133 HasVAListArg(hasVAListArg),
Ted Kremenekd1668192010-02-27 01:41:03 +00001134 TheCall(theCall), FormatIdx(formatIdx),
1135 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001136 CoveredArgs.resize(numDataArgs);
1137 CoveredArgs.reset();
1138 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001139
Ted Kremenek019d2242010-01-29 01:50:07 +00001140 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001141
Ted Kremenek02087932010-07-16 02:11:22 +00001142 void HandleIncompleteSpecifier(const char *startSpecifier,
1143 unsigned specifierLen);
1144
Ted Kremenekd1668192010-02-27 01:41:03 +00001145 virtual void HandleInvalidPosition(const char *startSpecifier,
1146 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001147 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001148
1149 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1150
Ted Kremenekab278de2010-01-28 23:39:18 +00001151 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001152
Ted Kremenek02087932010-07-16 02:11:22 +00001153protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001154 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1155 const char *startSpec,
1156 unsigned specifierLen,
1157 const char *csStart, unsigned csLen);
1158
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001159 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001160 CharSourceRange getSpecifierRange(const char *startSpecifier,
1161 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001162 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001163
Ted Kremenek5739de72010-01-29 01:06:55 +00001164 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001165
1166 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1167 const analyze_format_string::ConversionSpecifier &CS,
1168 const char *startSpecifier, unsigned specifierLen,
1169 unsigned argIndex);
Ted Kremenekab278de2010-01-28 23:39:18 +00001170};
1171}
1172
Ted Kremenek02087932010-07-16 02:11:22 +00001173SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001174 return OrigFormatExpr->getSourceRange();
1175}
1176
Ted Kremenek02087932010-07-16 02:11:22 +00001177CharSourceRange CheckFormatHandler::
1178getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001179 SourceLocation Start = getLocationOfByte(startSpecifier);
1180 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1181
1182 // Advance the end SourceLocation by one due to half-open ranges.
1183 End = End.getFileLocWithOffset(1);
1184
1185 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001186}
1187
Ted Kremenek02087932010-07-16 02:11:22 +00001188SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001189 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001190}
1191
Ted Kremenek02087932010-07-16 02:11:22 +00001192void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1193 unsigned specifierLen){
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001194 SourceLocation Loc = getLocationOfByte(startSpecifier);
1195 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek02087932010-07-16 02:11:22 +00001196 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001197}
1198
Ted Kremenekd1668192010-02-27 01:41:03 +00001199void
Ted Kremenek02087932010-07-16 02:11:22 +00001200CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1201 analyze_format_string::PositionContext p) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001202 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001203 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1204 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001205}
1206
Ted Kremenek02087932010-07-16 02:11:22 +00001207void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001208 unsigned posLen) {
1209 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001210 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1211 << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001212}
1213
Ted Kremenek02087932010-07-16 02:11:22 +00001214void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001215 if (!IsObjCLiteral) {
1216 // The presence of a null character is likely an error.
1217 S.Diag(getLocationOfByte(nullCharacter),
1218 diag::warn_printf_format_string_contains_null_char)
1219 << getFormatStringRange();
1220 }
Ted Kremenek02087932010-07-16 02:11:22 +00001221}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001222
Ted Kremenek02087932010-07-16 02:11:22 +00001223const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1224 return TheCall->getArg(FirstDataArg + i);
1225}
1226
1227void CheckFormatHandler::DoneProcessing() {
1228 // Does the number of data arguments exceed the number of
1229 // format conversions in the format string?
1230 if (!HasVAListArg) {
1231 // Find any arguments that weren't covered.
1232 CoveredArgs.flip();
1233 signed notCoveredArg = CoveredArgs.find_first();
1234 if (notCoveredArg >= 0) {
1235 assert((unsigned)notCoveredArg < NumDataArgs);
1236 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1237 diag::warn_printf_data_arg_not_used)
1238 << getFormatStringRange();
1239 }
1240 }
1241}
1242
Ted Kremenekce815422010-07-19 21:25:57 +00001243bool
1244CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1245 SourceLocation Loc,
1246 const char *startSpec,
1247 unsigned specifierLen,
1248 const char *csStart,
1249 unsigned csLen) {
1250
1251 bool keepGoing = true;
1252 if (argIndex < NumDataArgs) {
1253 // Consider the argument coverered, even though the specifier doesn't
1254 // make sense.
1255 CoveredArgs.set(argIndex);
1256 }
1257 else {
1258 // If argIndex exceeds the number of data arguments we
1259 // don't issue a warning because that is just a cascade of warnings (and
1260 // they may have intended '%%' anyway). We don't want to continue processing
1261 // the format string after this point, however, as we will like just get
1262 // gibberish when trying to match arguments.
1263 keepGoing = false;
1264 }
1265
1266 S.Diag(Loc, diag::warn_format_invalid_conversion)
1267 << llvm::StringRef(csStart, csLen)
1268 << getSpecifierRange(startSpec, specifierLen);
1269
1270 return keepGoing;
1271}
1272
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001273bool
1274CheckFormatHandler::CheckNumArgs(
1275 const analyze_format_string::FormatSpecifier &FS,
1276 const analyze_format_string::ConversionSpecifier &CS,
1277 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1278
1279 if (argIndex >= NumDataArgs) {
1280 if (FS.usesPositionalArg()) {
1281 S.Diag(getLocationOfByte(CS.getStart()),
1282 diag::warn_printf_positional_arg_exceeds_data_args)
1283 << (argIndex+1) << NumDataArgs
1284 << getSpecifierRange(startSpecifier, specifierLen);
1285 }
1286 else {
1287 S.Diag(getLocationOfByte(CS.getStart()),
1288 diag::warn_printf_insufficient_data_args)
1289 << getSpecifierRange(startSpecifier, specifierLen);
1290 }
1291
1292 return false;
1293 }
1294 return true;
1295}
1296
Ted Kremenek02087932010-07-16 02:11:22 +00001297//===--- CHECK: Printf format string checking ------------------------------===//
1298
1299namespace {
1300class CheckPrintfHandler : public CheckFormatHandler {
1301public:
1302 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1303 const Expr *origFormatExpr, unsigned firstDataArg,
1304 unsigned numDataArgs, bool isObjCLiteral,
1305 const char *beg, bool hasVAListArg,
1306 const CallExpr *theCall, unsigned formatIdx)
1307 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1308 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1309 theCall, formatIdx) {}
1310
1311
1312 bool HandleInvalidPrintfConversionSpecifier(
1313 const analyze_printf::PrintfSpecifier &FS,
1314 const char *startSpecifier,
1315 unsigned specifierLen);
1316
1317 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1318 const char *startSpecifier,
1319 unsigned specifierLen);
1320
1321 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1322 const char *startSpecifier, unsigned specifierLen);
1323 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1324 const analyze_printf::OptionalAmount &Amt,
1325 unsigned type,
1326 const char *startSpecifier, unsigned specifierLen);
1327 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1328 const analyze_printf::OptionalFlag &flag,
1329 const char *startSpecifier, unsigned specifierLen);
1330 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1331 const analyze_printf::OptionalFlag &ignoredFlag,
1332 const analyze_printf::OptionalFlag &flag,
1333 const char *startSpecifier, unsigned specifierLen);
1334};
1335}
1336
1337bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1338 const analyze_printf::PrintfSpecifier &FS,
1339 const char *startSpecifier,
1340 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001341 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001342 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001343
Ted Kremenekce815422010-07-19 21:25:57 +00001344 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1345 getLocationOfByte(CS.getStart()),
1346 startSpecifier, specifierLen,
1347 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001348}
1349
Ted Kremenek02087932010-07-16 02:11:22 +00001350bool CheckPrintfHandler::HandleAmount(
1351 const analyze_format_string::OptionalAmount &Amt,
1352 unsigned k, const char *startSpecifier,
1353 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001354
1355 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001356 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001357 unsigned argIndex = Amt.getArgIndex();
1358 if (argIndex >= NumDataArgs) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001359 S.Diag(getLocationOfByte(Amt.getStart()),
1360 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek02087932010-07-16 02:11:22 +00001361 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001362 // Don't do any more checking. We will just emit
1363 // spurious errors.
1364 return false;
1365 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001366
Ted Kremenek5739de72010-01-29 01:06:55 +00001367 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001368 // Although not in conformance with C99, we also allow the argument to be
1369 // an 'unsigned int' as that is a reasonably safe case. GCC also
1370 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001371 CoveredArgs.set(argIndex);
1372 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001373 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001374
1375 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1376 assert(ATR.isValid());
1377
1378 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001379 S.Diag(getLocationOfByte(Amt.getStart()),
1380 diag::warn_printf_asterisk_wrong_type)
1381 << k
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001382 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek02087932010-07-16 02:11:22 +00001383 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001384 << Arg->getSourceRange();
Ted Kremenek5739de72010-01-29 01:06:55 +00001385 // Don't do any more checking. We will just emit
1386 // spurious errors.
1387 return false;
1388 }
1389 }
1390 }
1391 return true;
1392}
Ted Kremenek5739de72010-01-29 01:06:55 +00001393
Tom Careb49ec692010-06-17 19:00:27 +00001394void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001395 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001396 const analyze_printf::OptionalAmount &Amt,
1397 unsigned type,
1398 const char *startSpecifier,
1399 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001400 const analyze_printf::PrintfConversionSpecifier &CS =
1401 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001402 switch (Amt.getHowSpecified()) {
1403 case analyze_printf::OptionalAmount::Constant:
1404 S.Diag(getLocationOfByte(Amt.getStart()),
1405 diag::warn_printf_nonsensical_optional_amount)
1406 << type
1407 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001408 << getSpecifierRange(startSpecifier, specifierLen)
1409 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001410 Amt.getConstantLength()));
1411 break;
1412
1413 default:
1414 S.Diag(getLocationOfByte(Amt.getStart()),
1415 diag::warn_printf_nonsensical_optional_amount)
1416 << type
1417 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001418 << getSpecifierRange(startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001419 break;
1420 }
1421}
1422
Ted Kremenek02087932010-07-16 02:11:22 +00001423void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001424 const analyze_printf::OptionalFlag &flag,
1425 const char *startSpecifier,
1426 unsigned specifierLen) {
1427 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001428 const analyze_printf::PrintfConversionSpecifier &CS =
1429 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001430 S.Diag(getLocationOfByte(flag.getPosition()),
1431 diag::warn_printf_nonsensical_flag)
1432 << flag.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001433 << getSpecifierRange(startSpecifier, specifierLen)
1434 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Careb49ec692010-06-17 19:00:27 +00001435}
1436
1437void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00001438 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001439 const analyze_printf::OptionalFlag &ignoredFlag,
1440 const analyze_printf::OptionalFlag &flag,
1441 const char *startSpecifier,
1442 unsigned specifierLen) {
1443 // Warn about ignored flag with a fixit removal.
1444 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1445 diag::warn_printf_ignored_flag)
1446 << ignoredFlag.toString() << flag.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001447 << getSpecifierRange(startSpecifier, specifierLen)
1448 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Careb49ec692010-06-17 19:00:27 +00001449 ignoredFlag.getPosition(), 1));
1450}
1451
Ted Kremenekab278de2010-01-28 23:39:18 +00001452bool
Ted Kremenek02087932010-07-16 02:11:22 +00001453CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00001454 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001455 const char *startSpecifier,
1456 unsigned specifierLen) {
1457
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001458 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00001459 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001460 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00001461
Ted Kremenek6cd69422010-07-19 22:01:06 +00001462 if (FS.consumesDataArgument()) {
1463 if (atFirstArg) {
1464 atFirstArg = false;
1465 usesPositionalArgs = FS.usesPositionalArg();
1466 }
1467 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1468 // Cannot mix-and-match positional and non-positional arguments.
1469 S.Diag(getLocationOfByte(CS.getStart()),
1470 diag::warn_format_mix_positional_nonpositional_args)
1471 << getSpecifierRange(startSpecifier, specifierLen);
1472 return false;
1473 }
Ted Kremenek5739de72010-01-29 01:06:55 +00001474 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001475
Ted Kremenekd1668192010-02-27 01:41:03 +00001476 // First check if the field width, precision, and conversion specifier
1477 // have matching data arguments.
1478 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1479 startSpecifier, specifierLen)) {
1480 return false;
1481 }
1482
1483 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1484 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001485 return false;
1486 }
1487
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001488 if (!CS.consumesDataArgument()) {
1489 // FIXME: Technically specifying a precision or field width here
1490 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001491 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001492 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001493
Ted Kremenek4a49d982010-02-26 19:18:41 +00001494 // Consume the argument.
1495 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00001496 if (argIndex < NumDataArgs) {
1497 // The check to see if the argIndex is valid will come later.
1498 // We set the bit here because we may exit early from this
1499 // function if we encounter some other error.
1500 CoveredArgs.set(argIndex);
1501 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00001502
1503 // Check for using an Objective-C specific conversion specifier
1504 // in a non-ObjC literal.
1505 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001506 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1507 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00001508 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001509
Tom Careb49ec692010-06-17 19:00:27 +00001510 // Check for invalid use of field width
1511 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00001512 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00001513 startSpecifier, specifierLen);
1514 }
1515
1516 // Check for invalid use of precision
1517 if (!FS.hasValidPrecision()) {
1518 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1519 startSpecifier, specifierLen);
1520 }
1521
1522 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00001523 if (!FS.hasValidThousandsGroupingPrefix())
1524 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001525 if (!FS.hasValidLeadingZeros())
1526 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1527 if (!FS.hasValidPlusPrefix())
1528 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00001529 if (!FS.hasValidSpacePrefix())
1530 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001531 if (!FS.hasValidAlternativeForm())
1532 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1533 if (!FS.hasValidLeftJustified())
1534 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1535
1536 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00001537 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1538 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1539 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001540 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1541 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1542 startSpecifier, specifierLen);
1543
1544 // Check the length modifier is valid with the given conversion specifier.
1545 const LengthModifier &LM = FS.getLengthModifier();
1546 if (!FS.hasValidLengthModifier())
1547 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenekb65a9d52010-07-20 20:03:43 +00001548 diag::warn_format_nonsensical_length)
Tom Careb49ec692010-06-17 19:00:27 +00001549 << LM.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001550 << getSpecifierRange(startSpecifier, specifierLen)
1551 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001552 LM.getLength()));
1553
1554 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00001555 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00001556 // Issue a warning about this being a possible security issue.
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001557 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek02087932010-07-16 02:11:22 +00001558 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001559 // Continue checking the other format specifiers.
1560 return true;
1561 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00001562
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001563 // The remaining checks depend on the data arguments.
1564 if (HasVAListArg)
1565 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001566
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001567 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001568 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001569
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001570 // Now type check the data expression that matches the
1571 // format specifier.
1572 const Expr *Ex = getDataArg(argIndex);
1573 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1574 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1575 // Check if we didn't match because of an implicit cast from a 'char'
1576 // or 'short' to an 'int'. This is done because printf is a varargs
1577 // function.
1578 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00001579 if (ICE->getType() == S.Context.IntTy) {
1580 // All further checking is done on the subexpression.
1581 Ex = ICE->getSubExpr();
1582 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001583 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00001584 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001585
1586 // We may be able to offer a FixItHint if it is a supported type.
1587 PrintfSpecifier fixedFS = FS;
1588 bool success = fixedFS.fixType(Ex->getType());
1589
1590 if (success) {
1591 // Get the fix string from the fixed format specifier
1592 llvm::SmallString<128> buf;
1593 llvm::raw_svector_ostream os(buf);
1594 fixedFS.toString(os);
1595
Ted Kremenek5f0c0662010-08-24 22:24:51 +00001596 // FIXME: getRepresentativeType() perhaps should return a string
1597 // instead of a QualType to better handle when the representative
1598 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001599 S.Diag(getLocationOfByte(CS.getStart()),
1600 diag::warn_printf_conversion_argument_type_mismatch)
1601 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1602 << getSpecifierRange(startSpecifier, specifierLen)
1603 << Ex->getSourceRange()
1604 << FixItHint::CreateReplacement(
1605 getSpecifierRange(startSpecifier, specifierLen),
1606 os.str());
1607 }
1608 else {
1609 S.Diag(getLocationOfByte(CS.getStart()),
1610 diag::warn_printf_conversion_argument_type_mismatch)
1611 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1612 << getSpecifierRange(startSpecifier, specifierLen)
1613 << Ex->getSourceRange();
1614 }
1615 }
1616
Ted Kremenekab278de2010-01-28 23:39:18 +00001617 return true;
1618}
1619
Ted Kremenek02087932010-07-16 02:11:22 +00001620//===--- CHECK: Scanf format string checking ------------------------------===//
1621
1622namespace {
1623class CheckScanfHandler : public CheckFormatHandler {
1624public:
1625 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1626 const Expr *origFormatExpr, unsigned firstDataArg,
1627 unsigned numDataArgs, bool isObjCLiteral,
1628 const char *beg, bool hasVAListArg,
1629 const CallExpr *theCall, unsigned formatIdx)
1630 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1631 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1632 theCall, formatIdx) {}
1633
1634 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1635 const char *startSpecifier,
1636 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001637
1638 bool HandleInvalidScanfConversionSpecifier(
1639 const analyze_scanf::ScanfSpecifier &FS,
1640 const char *startSpecifier,
1641 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001642
1643 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00001644};
Ted Kremenek019d2242010-01-29 01:50:07 +00001645}
Ted Kremenekab278de2010-01-28 23:39:18 +00001646
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001647void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1648 const char *end) {
1649 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1650 << getSpecifierRange(start, end - start);
1651}
1652
Ted Kremenekce815422010-07-19 21:25:57 +00001653bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1654 const analyze_scanf::ScanfSpecifier &FS,
1655 const char *startSpecifier,
1656 unsigned specifierLen) {
1657
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001658 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001659 FS.getConversionSpecifier();
1660
1661 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1662 getLocationOfByte(CS.getStart()),
1663 startSpecifier, specifierLen,
1664 CS.getStart(), CS.getLength());
1665}
1666
Ted Kremenek02087932010-07-16 02:11:22 +00001667bool CheckScanfHandler::HandleScanfSpecifier(
1668 const analyze_scanf::ScanfSpecifier &FS,
1669 const char *startSpecifier,
1670 unsigned specifierLen) {
1671
1672 using namespace analyze_scanf;
1673 using namespace analyze_format_string;
1674
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001675 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001676
Ted Kremenek6cd69422010-07-19 22:01:06 +00001677 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1678 // be used to decide if we are using positional arguments consistently.
1679 if (FS.consumesDataArgument()) {
1680 if (atFirstArg) {
1681 atFirstArg = false;
1682 usesPositionalArgs = FS.usesPositionalArg();
1683 }
1684 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1685 // Cannot mix-and-match positional and non-positional arguments.
1686 S.Diag(getLocationOfByte(CS.getStart()),
1687 diag::warn_format_mix_positional_nonpositional_args)
1688 << getSpecifierRange(startSpecifier, specifierLen);
1689 return false;
1690 }
Ted Kremenek02087932010-07-16 02:11:22 +00001691 }
1692
1693 // Check if the field with is non-zero.
1694 const OptionalAmount &Amt = FS.getFieldWidth();
1695 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1696 if (Amt.getConstantAmount() == 0) {
1697 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1698 Amt.getConstantLength());
1699 S.Diag(getLocationOfByte(Amt.getStart()),
1700 diag::warn_scanf_nonzero_width)
1701 << R << FixItHint::CreateRemoval(R);
1702 }
1703 }
1704
1705 if (!FS.consumesDataArgument()) {
1706 // FIXME: Technically specifying a precision or field width here
1707 // makes no sense. Worth issuing a warning at some point.
1708 return true;
1709 }
1710
1711 // Consume the argument.
1712 unsigned argIndex = FS.getArgIndex();
1713 if (argIndex < NumDataArgs) {
1714 // The check to see if the argIndex is valid will come later.
1715 // We set the bit here because we may exit early from this
1716 // function if we encounter some other error.
1717 CoveredArgs.set(argIndex);
1718 }
1719
Ted Kremenek4407ea42010-07-20 20:04:47 +00001720 // Check the length modifier is valid with the given conversion specifier.
1721 const LengthModifier &LM = FS.getLengthModifier();
1722 if (!FS.hasValidLengthModifier()) {
1723 S.Diag(getLocationOfByte(LM.getStart()),
1724 diag::warn_format_nonsensical_length)
1725 << LM.toString() << CS.toString()
1726 << getSpecifierRange(startSpecifier, specifierLen)
1727 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1728 LM.getLength()));
1729 }
1730
Ted Kremenek02087932010-07-16 02:11:22 +00001731 // The remaining checks depend on the data arguments.
1732 if (HasVAListArg)
1733 return true;
1734
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001735 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00001736 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00001737
1738 // FIXME: Check that the argument type matches the format specifier.
1739
1740 return true;
1741}
1742
1743void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001744 const Expr *OrigFormatExpr,
1745 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001746 unsigned format_idx, unsigned firstDataArg,
1747 bool isPrintf) {
1748
Ted Kremenekab278de2010-01-28 23:39:18 +00001749 // CHECK: is the format string a wide literal?
1750 if (FExpr->isWide()) {
1751 Diag(FExpr->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001752 diag::warn_format_string_is_wide_literal)
Ted Kremenekab278de2010-01-28 23:39:18 +00001753 << OrigFormatExpr->getSourceRange();
1754 return;
1755 }
Ted Kremenek02087932010-07-16 02:11:22 +00001756
Ted Kremenekab278de2010-01-28 23:39:18 +00001757 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001758 llvm::StringRef StrRef = FExpr->getString();
1759 const char *Str = StrRef.data();
1760 unsigned StrLen = StrRef.size();
Ted Kremenek02087932010-07-16 02:11:22 +00001761
Ted Kremenekab278de2010-01-28 23:39:18 +00001762 // CHECK: empty format string?
Ted Kremenekab278de2010-01-28 23:39:18 +00001763 if (StrLen == 0) {
Ted Kremenek02087932010-07-16 02:11:22 +00001764 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremenekab278de2010-01-28 23:39:18 +00001765 << OrigFormatExpr->getSourceRange();
1766 return;
1767 }
Ted Kremenek02087932010-07-16 02:11:22 +00001768
1769 if (isPrintf) {
1770 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1771 TheCall->getNumArgs() - firstDataArg,
1772 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1773 HasVAListArg, TheCall, format_idx);
1774
1775 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1776 H.DoneProcessing();
1777 }
1778 else {
1779 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1780 TheCall->getNumArgs() - firstDataArg,
1781 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1782 HasVAListArg, TheCall, format_idx);
1783
1784 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1785 H.DoneProcessing();
1786 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00001787}
1788
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001789//===--- CHECK: Return Address of Stack Variable --------------------------===//
1790
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001791static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1792static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001793
1794/// CheckReturnStackAddr - Check if a return statement returns the address
1795/// of a stack variable.
1796void
1797Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1798 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001799
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001800 Expr *stackE = 0;
1801 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1802
1803 // Perform checking for returned stack addresses, local blocks,
1804 // label addresses or references to temporaries.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001805 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001806 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00001807 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001808 stackE = EvalVal(RetValExp, refVars);
1809 }
1810
1811 if (stackE == 0)
1812 return; // Nothing suspicious was found.
1813
1814 SourceLocation diagLoc;
1815 SourceRange diagRange;
1816 if (refVars.empty()) {
1817 diagLoc = stackE->getLocStart();
1818 diagRange = stackE->getSourceRange();
1819 } else {
1820 // We followed through a reference variable. 'stackE' contains the
1821 // problematic expression but we will warn at the return statement pointing
1822 // at the reference variable. We will later display the "trail" of
1823 // reference variables using notes.
1824 diagLoc = refVars[0]->getLocStart();
1825 diagRange = refVars[0]->getSourceRange();
1826 }
1827
1828 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1829 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1830 : diag::warn_ret_stack_addr)
1831 << DR->getDecl()->getDeclName() << diagRange;
1832 } else if (isa<BlockExpr>(stackE)) { // local block.
1833 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1834 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1835 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1836 } else { // local temporary.
1837 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1838 : diag::warn_ret_local_temp_addr)
1839 << diagRange;
1840 }
1841
1842 // Display the "trail" of reference variables that we followed until we
1843 // found the problematic expression using notes.
1844 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1845 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1846 // If this var binds to another reference var, show the range of the next
1847 // var, otherwise the var binds to the problematic expression, in which case
1848 // show the range of the expression.
1849 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1850 : stackE->getSourceRange();
1851 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1852 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001853 }
1854}
1855
1856/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1857/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001858/// to a location on the stack, a local block, an address of a label, or a
1859/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001860/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001861/// encounter a subexpression that (1) clearly does not lead to one of the
1862/// above problematic expressions (2) is something we cannot determine leads to
1863/// a problematic expression based on such local checking.
1864///
1865/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1866/// the expression that they point to. Such variables are added to the
1867/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001868///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001869/// EvalAddr processes expressions that are pointers that are used as
1870/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001871/// At the base case of the recursion is a check for the above problematic
1872/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001873///
1874/// This implementation handles:
1875///
1876/// * pointer-to-pointer casts
1877/// * implicit conversions from array references to pointers
1878/// * taking the address of fields
1879/// * arbitrary interplay between "&" and "*" operators
1880/// * pointer arithmetic from an address of a stack variable
1881/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001882static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1883 if (E->isTypeDependent())
1884 return NULL;
1885
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001886 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00001887 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001888 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001889 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00001890 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00001891
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001892 // Our "symbolic interpreter" is just a dispatch off the currently
1893 // viewed AST node. We then recursively traverse the AST by calling
1894 // EvalAddr and EvalVal appropriately.
1895 switch (E->getStmtClass()) {
Chris Lattner934edb22007-12-28 05:31:15 +00001896 case Stmt::ParenExprClass:
1897 // Ignore parentheses.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001898 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1899
1900 case Stmt::DeclRefExprClass: {
1901 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1902
1903 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1904 // If this is a reference variable, follow through to the expression that
1905 // it points to.
1906 if (V->hasLocalStorage() &&
1907 V->getType()->isReferenceType() && V->hasInit()) {
1908 // Add the reference variable to the "trail".
1909 refVars.push_back(DR);
1910 return EvalAddr(V->getInit(), refVars);
1911 }
1912
1913 return NULL;
1914 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001915
Chris Lattner934edb22007-12-28 05:31:15 +00001916 case Stmt::UnaryOperatorClass: {
1917 // The only unary operator that make sense to handle here
1918 // is AddrOf. All others don't make sense as pointers.
1919 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001920
John McCalle3027922010-08-25 11:45:40 +00001921 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001922 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001923 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001924 return NULL;
1925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
Chris Lattner934edb22007-12-28 05:31:15 +00001927 case Stmt::BinaryOperatorClass: {
1928 // Handle pointer arithmetic. All other binary operators are not valid
1929 // in this context.
1930 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00001931 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00001932
John McCalle3027922010-08-25 11:45:40 +00001933 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00001934 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001935
Chris Lattner934edb22007-12-28 05:31:15 +00001936 Expr *Base = B->getLHS();
1937
1938 // Determine which argument is the real pointer base. It could be
1939 // the RHS argument instead of the LHS.
1940 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00001941
Chris Lattner934edb22007-12-28 05:31:15 +00001942 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001943 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001944 }
Steve Naroff2752a172008-09-10 19:17:48 +00001945
Chris Lattner934edb22007-12-28 05:31:15 +00001946 // For conditional operators we need to see if either the LHS or RHS are
1947 // valid DeclRefExpr*s. If one of them is valid, we return it.
1948 case Stmt::ConditionalOperatorClass: {
1949 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Chris Lattner934edb22007-12-28 05:31:15 +00001951 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001952 if (Expr *lhsExpr = C->getLHS()) {
1953 // In C++, we can have a throw-expression, which has 'void' type.
1954 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001955 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001956 return LHS;
1957 }
Chris Lattner934edb22007-12-28 05:31:15 +00001958
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001959 // In C++, we can have a throw-expression, which has 'void' type.
1960 if (C->getRHS()->getType()->isVoidType())
1961 return NULL;
1962
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001963 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001964 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001965
1966 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00001967 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001968 return E; // local block.
1969 return NULL;
1970
1971 case Stmt::AddrLabelExprClass:
1972 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00001973
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001974 // For casts, we need to handle conversions from arrays to
1975 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00001976 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00001977 case Stmt::CStyleCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001978 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001979 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001980 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001981
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001982 if (SubExpr->getType()->isPointerType() ||
1983 SubExpr->getType()->isBlockPointerType() ||
1984 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001985 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001986 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001987 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001988 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001989 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00001990 }
Mike Stump11289f42009-09-09 15:08:12 +00001991
Chris Lattner934edb22007-12-28 05:31:15 +00001992 // C++ casts. For dynamic casts, static casts, and const casts, we
1993 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00001994 // through the cast. In the case the dynamic cast doesn't fail (and
1995 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00001996 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00001997 // FIXME: The comment about is wrong; we're not always converting
1998 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00001999 // handle references to objects.
2000 case Stmt::CXXStaticCastExprClass:
2001 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00002002 case Stmt::CXXConstCastExprClass:
2003 case Stmt::CXXReinterpretCastExprClass: {
2004 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002005 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002006 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002007 else
2008 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00002009 }
Mike Stump11289f42009-09-09 15:08:12 +00002010
Chris Lattner934edb22007-12-28 05:31:15 +00002011 // Everything else: we simply don't reason about them.
2012 default:
2013 return NULL;
2014 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002015}
Mike Stump11289f42009-09-09 15:08:12 +00002016
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002017
2018/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2019/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002020static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002021do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002022 // We should only be called for evaluating non-pointer expressions, or
2023 // expressions with a pointer type that are not used as references but instead
2024 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00002025
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002026 // Our "symbolic interpreter" is just a dispatch off the currently
2027 // viewed AST node. We then recursively traverse the AST by calling
2028 // EvalAddr and EvalVal appropriately.
2029 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002030 case Stmt::ImplicitCastExprClass: {
2031 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002032 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002033 E = IE->getSubExpr();
2034 continue;
2035 }
2036 return NULL;
2037 }
2038
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002039 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002040 // When we hit a DeclRefExpr we are looking at code that refers to a
2041 // variable's name. If it's not a reference variable we check if it has
2042 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002043 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002044
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002045 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002046 if (V->hasLocalStorage()) {
2047 if (!V->getType()->isReferenceType())
2048 return DR;
2049
2050 // Reference variable, follow through to the expression that
2051 // it points to.
2052 if (V->hasInit()) {
2053 // Add the reference variable to the "trail".
2054 refVars.push_back(DR);
2055 return EvalVal(V->getInit(), refVars);
2056 }
2057 }
Mike Stump11289f42009-09-09 15:08:12 +00002058
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002059 return NULL;
2060 }
Mike Stump11289f42009-09-09 15:08:12 +00002061
Ted Kremenekb7861562010-08-04 20:01:07 +00002062 case Stmt::ParenExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002063 // Ignore parentheses.
Ted Kremenekb7861562010-08-04 20:01:07 +00002064 E = cast<ParenExpr>(E)->getSubExpr();
2065 continue;
2066 }
Mike Stump11289f42009-09-09 15:08:12 +00002067
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002068 case Stmt::UnaryOperatorClass: {
2069 // The only unary operator that make sense to handle here
2070 // is Deref. All others don't resolve to a "name." This includes
2071 // handling all sorts of rvalues passed to a unary operator.
2072 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002073
John McCalle3027922010-08-25 11:45:40 +00002074 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002075 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002076
2077 return NULL;
2078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002080 case Stmt::ArraySubscriptExprClass: {
2081 // Array subscripts are potential references to data on the stack. We
2082 // retrieve the DeclRefExpr* for the array variable if it indeed
2083 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002084 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002085 }
Mike Stump11289f42009-09-09 15:08:12 +00002086
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002087 case Stmt::ConditionalOperatorClass: {
2088 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002089 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002090 ConditionalOperator *C = cast<ConditionalOperator>(E);
2091
Anders Carlsson801c5c72007-11-30 19:04:31 +00002092 // Handle the GNU extension for missing LHS.
2093 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002094 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002095 return LHS;
2096
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002097 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002098 }
Mike Stump11289f42009-09-09 15:08:12 +00002099
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002100 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002101 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002102 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002103
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002104 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002105 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002106 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002107
2108 // Check whether the member type is itself a reference, in which case
2109 // we're not going to refer to the member, but to what the member refers to.
2110 if (M->getMemberDecl()->getType()->isReferenceType())
2111 return NULL;
2112
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002113 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002114 }
Mike Stump11289f42009-09-09 15:08:12 +00002115
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002116 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002117 // Check that we don't return or take the address of a reference to a
2118 // temporary. This is only useful in C++.
2119 if (!E->isTypeDependent() && E->isRValue())
2120 return E;
2121
2122 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002123 return NULL;
2124 }
Ted Kremenekb7861562010-08-04 20:01:07 +00002125} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002126}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002127
2128//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2129
2130/// Check for comparisons of floating point operands using != and ==.
2131/// Issue a warning if these are no self-comparisons, as they are not likely
2132/// to do what the programmer intended.
2133void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2134 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00002135
John McCall34376a62010-12-04 03:47:34 +00002136 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2137 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002138
2139 // Special case: check for x == x (which is OK).
2140 // Do not emit warnings for such cases.
2141 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2142 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2143 if (DRL->getDecl() == DRR->getDecl())
2144 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002145
2146
Ted Kremenekeda40e22007-11-29 00:59:04 +00002147 // Special case: check for comparisons against literals that can be exactly
2148 // represented by APFloat. In such cases, do not emit a warning. This
2149 // is a heuristic: often comparison against such literals are used to
2150 // detect if a value in a variable has not changed. This clearly can
2151 // lead to false negatives.
2152 if (EmitWarning) {
2153 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2154 if (FLL->isExact())
2155 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00002156 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00002157 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2158 if (FLR->isExact())
2159 EmitWarning = false;
2160 }
2161 }
Mike Stump11289f42009-09-09 15:08:12 +00002162
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002163 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002164 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002165 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002166 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002167 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002168
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002169 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002170 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002171 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002172 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002174 // Emit the diagnostic.
2175 if (EmitWarning)
Chris Lattner3b054132008-11-19 05:08:23 +00002176 Diag(loc, diag::warn_floatingpoint_eq)
2177 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002178}
John McCallca01b222010-01-04 23:21:16 +00002179
John McCall70aa5392010-01-06 05:24:50 +00002180//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2181//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00002182
John McCall70aa5392010-01-06 05:24:50 +00002183namespace {
John McCallca01b222010-01-04 23:21:16 +00002184
John McCall70aa5392010-01-06 05:24:50 +00002185/// Structure recording the 'active' range of an integer-valued
2186/// expression.
2187struct IntRange {
2188 /// The number of bits active in the int.
2189 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00002190
John McCall70aa5392010-01-06 05:24:50 +00002191 /// True if the int is known not to have negative values.
2192 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00002193
John McCall70aa5392010-01-06 05:24:50 +00002194 IntRange(unsigned Width, bool NonNegative)
2195 : Width(Width), NonNegative(NonNegative)
2196 {}
John McCallca01b222010-01-04 23:21:16 +00002197
John McCall817d4af2010-11-10 23:38:19 +00002198 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00002199 static IntRange forBoolType() {
2200 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00002201 }
2202
John McCall817d4af2010-11-10 23:38:19 +00002203 /// Returns the range of an opaque value of the given integral type.
2204 static IntRange forValueOfType(ASTContext &C, QualType T) {
2205 return forValueOfCanonicalType(C,
2206 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00002207 }
2208
John McCall817d4af2010-11-10 23:38:19 +00002209 /// Returns the range of an opaque value of a canonical integral type.
2210 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00002211 assert(T->isCanonicalUnqualified());
2212
2213 if (const VectorType *VT = dyn_cast<VectorType>(T))
2214 T = VT->getElementType().getTypePtr();
2215 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2216 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00002217
John McCall18a2c2c2010-11-09 22:22:12 +00002218 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00002219 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2220 EnumDecl *Enum = ET->getDecl();
John McCall18a2c2c2010-11-09 22:22:12 +00002221 if (!Enum->isDefinition())
2222 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2223
John McCallcc7e5bf2010-05-06 08:58:33 +00002224 unsigned NumPositive = Enum->getNumPositiveBits();
2225 unsigned NumNegative = Enum->getNumNegativeBits();
2226
2227 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2228 }
John McCall70aa5392010-01-06 05:24:50 +00002229
2230 const BuiltinType *BT = cast<BuiltinType>(T);
2231 assert(BT->isInteger());
2232
2233 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2234 }
2235
John McCall817d4af2010-11-10 23:38:19 +00002236 /// Returns the "target" range of a canonical integral type, i.e.
2237 /// the range of values expressible in the type.
2238 ///
2239 /// This matches forValueOfCanonicalType except that enums have the
2240 /// full range of their type, not the range of their enumerators.
2241 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2242 assert(T->isCanonicalUnqualified());
2243
2244 if (const VectorType *VT = dyn_cast<VectorType>(T))
2245 T = VT->getElementType().getTypePtr();
2246 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2247 T = CT->getElementType().getTypePtr();
2248 if (const EnumType *ET = dyn_cast<EnumType>(T))
2249 T = ET->getDecl()->getIntegerType().getTypePtr();
2250
2251 const BuiltinType *BT = cast<BuiltinType>(T);
2252 assert(BT->isInteger());
2253
2254 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2255 }
2256
2257 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00002258 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00002259 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00002260 L.NonNegative && R.NonNegative);
2261 }
2262
John McCall817d4af2010-11-10 23:38:19 +00002263 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00002264 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00002265 return IntRange(std::min(L.Width, R.Width),
2266 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00002267 }
2268};
2269
2270IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2271 if (value.isSigned() && value.isNegative())
2272 return IntRange(value.getMinSignedBits(), false);
2273
2274 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002275 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002276
2277 // isNonNegative() just checks the sign bit without considering
2278 // signedness.
2279 return IntRange(value.getActiveBits(), true);
2280}
2281
John McCall74430522010-01-06 22:57:21 +00002282IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00002283 unsigned MaxWidth) {
2284 if (result.isInt())
2285 return GetValueRange(C, result.getInt(), MaxWidth);
2286
2287 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00002288 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2289 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2290 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2291 R = IntRange::join(R, El);
2292 }
John McCall70aa5392010-01-06 05:24:50 +00002293 return R;
2294 }
2295
2296 if (result.isComplexInt()) {
2297 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2298 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2299 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00002300 }
2301
2302 // This can happen with lossless casts to intptr_t of "based" lvalues.
2303 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00002304 // FIXME: The only reason we need to pass the type in here is to get
2305 // the sign right on this one case. It would be nice if APValue
2306 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00002307 assert(result.isLValue());
John McCall74430522010-01-06 22:57:21 +00002308 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall263a48b2010-01-04 23:31:57 +00002309}
John McCall70aa5392010-01-06 05:24:50 +00002310
2311/// Pseudo-evaluate the given integer expression, estimating the
2312/// range of values it might take.
2313///
2314/// \param MaxWidth - the width to which the value will be truncated
2315IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2316 E = E->IgnoreParens();
2317
2318 // Try a full evaluation first.
2319 Expr::EvalResult result;
2320 if (E->Evaluate(result, C))
John McCall74430522010-01-06 22:57:21 +00002321 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002322
2323 // I think we only want to look through implicit casts here; if the
2324 // user has an explicit widening cast, we should treat the value as
2325 // being of the new, wider type.
2326 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002327 if (CE->getCastKind() == CK_NoOp)
John McCall70aa5392010-01-06 05:24:50 +00002328 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2329
John McCall817d4af2010-11-10 23:38:19 +00002330 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00002331
John McCalle3027922010-08-25 11:45:40 +00002332 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00002333
John McCall70aa5392010-01-06 05:24:50 +00002334 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00002335 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00002336 return OutputTypeRange;
2337
2338 IntRange SubRange
2339 = GetExprRange(C, CE->getSubExpr(),
2340 std::min(MaxWidth, OutputTypeRange.Width));
2341
2342 // Bail out if the subexpr's range is as wide as the cast type.
2343 if (SubRange.Width >= OutputTypeRange.Width)
2344 return OutputTypeRange;
2345
2346 // Otherwise, we take the smaller width, and we're non-negative if
2347 // either the output type or the subexpr is.
2348 return IntRange(SubRange.Width,
2349 SubRange.NonNegative || OutputTypeRange.NonNegative);
2350 }
2351
2352 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2353 // If we can fold the condition, just take that operand.
2354 bool CondResult;
2355 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2356 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2357 : CO->getFalseExpr(),
2358 MaxWidth);
2359
2360 // Otherwise, conservatively merge.
2361 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2362 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2363 return IntRange::join(L, R);
2364 }
2365
2366 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2367 switch (BO->getOpcode()) {
2368
2369 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00002370 case BO_LAnd:
2371 case BO_LOr:
2372 case BO_LT:
2373 case BO_GT:
2374 case BO_LE:
2375 case BO_GE:
2376 case BO_EQ:
2377 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00002378 return IntRange::forBoolType();
2379
John McCallff96ccd2010-02-23 19:22:29 +00002380 // The type of these compound assignments is the type of the LHS,
2381 // so the RHS is not necessarily an integer.
John McCalle3027922010-08-25 11:45:40 +00002382 case BO_MulAssign:
2383 case BO_DivAssign:
2384 case BO_RemAssign:
2385 case BO_AddAssign:
2386 case BO_SubAssign:
John McCall817d4af2010-11-10 23:38:19 +00002387 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00002388
John McCall70aa5392010-01-06 05:24:50 +00002389 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002390 case BO_PtrMemD:
2391 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00002392 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002393
John McCall2ce81ad2010-01-06 22:07:33 +00002394 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00002395 case BO_And:
2396 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00002397 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2398 GetExprRange(C, BO->getRHS(), MaxWidth));
2399
John McCall70aa5392010-01-06 05:24:50 +00002400 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00002401 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00002402 // ...except that we want to treat '1 << (blah)' as logically
2403 // positive. It's an important idiom.
2404 if (IntegerLiteral *I
2405 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2406 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00002407 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00002408 return IntRange(R.Width, /*NonNegative*/ true);
2409 }
2410 }
2411 // fallthrough
2412
John McCalle3027922010-08-25 11:45:40 +00002413 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00002414 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002415
John McCall2ce81ad2010-01-06 22:07:33 +00002416 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00002417 case BO_Shr:
2418 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00002419 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2420
2421 // If the shift amount is a positive constant, drop the width by
2422 // that much.
2423 llvm::APSInt shift;
2424 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2425 shift.isNonNegative()) {
2426 unsigned zext = shift.getZExtValue();
2427 if (zext >= L.Width)
2428 L.Width = (L.NonNegative ? 0 : 1);
2429 else
2430 L.Width -= zext;
2431 }
2432
2433 return L;
2434 }
2435
2436 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00002437 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00002438 return GetExprRange(C, BO->getRHS(), MaxWidth);
2439
John McCall2ce81ad2010-01-06 22:07:33 +00002440 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00002441 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00002442 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00002443 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002444 // fallthrough
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002445
John McCall70aa5392010-01-06 05:24:50 +00002446 default:
2447 break;
2448 }
2449
2450 // Treat every other operator as if it were closed on the
2451 // narrowest type that encompasses both operands.
2452 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2453 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2454 return IntRange::join(L, R);
2455 }
2456
2457 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2458 switch (UO->getOpcode()) {
2459 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00002460 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00002461 return IntRange::forBoolType();
2462
2463 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002464 case UO_Deref:
2465 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00002466 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002467
2468 default:
2469 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2470 }
2471 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002472
2473 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00002474 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00002475 }
John McCall70aa5392010-01-06 05:24:50 +00002476
2477 FieldDecl *BitField = E->getBitField();
2478 if (BitField) {
2479 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2480 unsigned BitWidth = BitWidthAP.getZExtValue();
2481
2482 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2483 }
2484
John McCall817d4af2010-11-10 23:38:19 +00002485 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002486}
John McCall263a48b2010-01-04 23:31:57 +00002487
John McCallcc7e5bf2010-05-06 08:58:33 +00002488IntRange GetExprRange(ASTContext &C, Expr *E) {
2489 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2490}
2491
John McCall263a48b2010-01-04 23:31:57 +00002492/// Checks whether the given value, which currently has the given
2493/// source semantics, has the same value when coerced through the
2494/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00002495bool IsSameFloatAfterCast(const llvm::APFloat &value,
2496 const llvm::fltSemantics &Src,
2497 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002498 llvm::APFloat truncated = value;
2499
2500 bool ignored;
2501 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2502 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2503
2504 return truncated.bitwiseIsEqual(value);
2505}
2506
2507/// Checks whether the given value, which currently has the given
2508/// source semantics, has the same value when coerced through the
2509/// target semantics.
2510///
2511/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00002512bool IsSameFloatAfterCast(const APValue &value,
2513 const llvm::fltSemantics &Src,
2514 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002515 if (value.isFloat())
2516 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2517
2518 if (value.isVector()) {
2519 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2520 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2521 return false;
2522 return true;
2523 }
2524
2525 assert(value.isComplexFloat());
2526 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2527 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2528}
2529
John McCallacf0ee52010-10-08 02:01:28 +00002530void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002531
Ted Kremenek6274be42010-09-23 21:43:44 +00002532static bool IsZero(Sema &S, Expr *E) {
2533 // Suppress cases where we are comparing against an enum constant.
2534 if (const DeclRefExpr *DR =
2535 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2536 if (isa<EnumConstantDecl>(DR->getDecl()))
2537 return false;
2538
2539 // Suppress cases where the '0' value is expanded from a macro.
2540 if (E->getLocStart().isMacroID())
2541 return false;
2542
John McCallcc7e5bf2010-05-06 08:58:33 +00002543 llvm::APSInt Value;
2544 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2545}
2546
John McCall2551c1b2010-10-06 00:25:24 +00002547static bool HasEnumType(Expr *E) {
2548 // Strip off implicit integral promotions.
2549 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002550 if (ICE->getCastKind() != CK_IntegralCast &&
2551 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00002552 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002553 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00002554 }
2555
2556 return E->getType()->isEnumeralType();
2557}
2558
John McCallcc7e5bf2010-05-06 08:58:33 +00002559void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002560 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00002561 if (E->isValueDependent())
2562 return;
2563
John McCalle3027922010-08-25 11:45:40 +00002564 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002565 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002566 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002567 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002568 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002569 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002570 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002571 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002572 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002573 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002574 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002575 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002576 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002577 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002578 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002579 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2580 }
2581}
2582
2583/// Analyze the operands of the given comparison. Implements the
2584/// fallback case from AnalyzeComparison.
2585void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00002586 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2587 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00002588}
John McCall263a48b2010-01-04 23:31:57 +00002589
John McCallca01b222010-01-04 23:21:16 +00002590/// \brief Implements -Wsign-compare.
2591///
2592/// \param lex the left-hand expression
2593/// \param rex the right-hand expression
2594/// \param OpLoc the location of the joining operator
John McCall71d8d9b2010-03-11 19:43:18 +00002595/// \param BinOpc binary opcode or 0
John McCallcc7e5bf2010-05-06 08:58:33 +00002596void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2597 // The type the comparison is being performed in.
2598 QualType T = E->getLHS()->getType();
2599 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2600 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00002601
John McCallcc7e5bf2010-05-06 08:58:33 +00002602 // We don't do anything special if this isn't an unsigned integral
2603 // comparison: we're only interested in integral comparisons, and
2604 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00002605 //
2606 // We also don't care about value-dependent expressions or expressions
2607 // whose result is a constant.
2608 if (!T->hasUnsignedIntegerRepresentation()
2609 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00002610 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00002611
John McCallcc7e5bf2010-05-06 08:58:33 +00002612 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2613 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00002614
John McCallcc7e5bf2010-05-06 08:58:33 +00002615 // Check to see if one of the (unmodified) operands is of different
2616 // signedness.
2617 Expr *signedOperand, *unsignedOperand;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002618 if (lex->getType()->hasSignedIntegerRepresentation()) {
2619 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00002620 "unsigned comparison between two signed integer expressions?");
2621 signedOperand = lex;
2622 unsignedOperand = rex;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002623 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002624 signedOperand = rex;
2625 unsignedOperand = lex;
John McCallca01b222010-01-04 23:21:16 +00002626 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00002627 CheckTrivialUnsignedComparison(S, E);
2628 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002629 }
2630
John McCallcc7e5bf2010-05-06 08:58:33 +00002631 // Otherwise, calculate the effective range of the signed operand.
2632 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00002633
John McCallcc7e5bf2010-05-06 08:58:33 +00002634 // Go ahead and analyze implicit conversions in the operands. Note
2635 // that we skip the implicit conversions on both sides.
John McCallacf0ee52010-10-08 02:01:28 +00002636 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2637 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00002638
John McCallcc7e5bf2010-05-06 08:58:33 +00002639 // If the signed range is non-negative, -Wsign-compare won't fire,
2640 // but we should still check for comparisons which are always true
2641 // or false.
2642 if (signedRange.NonNegative)
2643 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002644
2645 // For (in)equality comparisons, if the unsigned operand is a
2646 // constant which cannot collide with a overflowed signed operand,
2647 // then reinterpreting the signed operand as unsigned will not
2648 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00002649 if (E->isEqualityOp()) {
2650 unsigned comparisonWidth = S.Context.getIntWidth(T);
2651 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00002652
John McCallcc7e5bf2010-05-06 08:58:33 +00002653 // We should never be unable to prove that the unsigned operand is
2654 // non-negative.
2655 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2656
2657 if (unsignedRange.Width < comparisonWidth)
2658 return;
2659 }
2660
2661 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2662 << lex->getType() << rex->getType()
2663 << lex->getSourceRange() << rex->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00002664}
2665
John McCall1f425642010-11-11 03:21:53 +00002666/// Analyzes an attempt to assign the given value to a bitfield.
2667///
2668/// Returns true if there was something fishy about the attempt.
2669bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2670 SourceLocation InitLoc) {
2671 assert(Bitfield->isBitField());
2672 if (Bitfield->isInvalidDecl())
2673 return false;
2674
John McCalldeebbcf2010-11-11 05:33:51 +00002675 // White-list bool bitfields.
2676 if (Bitfield->getType()->isBooleanType())
2677 return false;
2678
Douglas Gregor789adec2011-02-04 13:09:01 +00002679 // Ignore value- or type-dependent expressions.
2680 if (Bitfield->getBitWidth()->isValueDependent() ||
2681 Bitfield->getBitWidth()->isTypeDependent() ||
2682 Init->isValueDependent() ||
2683 Init->isTypeDependent())
2684 return false;
2685
John McCall1f425642010-11-11 03:21:53 +00002686 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2687
2688 llvm::APSInt Width(32);
2689 Expr::EvalResult InitValue;
2690 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCalldeebbcf2010-11-11 05:33:51 +00002691 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall1f425642010-11-11 03:21:53 +00002692 !InitValue.Val.isInt())
2693 return false;
2694
2695 const llvm::APSInt &Value = InitValue.Val.getInt();
2696 unsigned OriginalWidth = Value.getBitWidth();
2697 unsigned FieldWidth = Width.getZExtValue();
2698
2699 if (OriginalWidth <= FieldWidth)
2700 return false;
2701
Jay Foad6d4db0c2010-12-07 08:25:34 +00002702 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall1f425642010-11-11 03:21:53 +00002703
2704 // It's fairly common to write values into signed bitfields
2705 // that, if sign-extended, would end up becoming a different
2706 // value. We don't want to warn about that.
2707 if (Value.isSigned() && Value.isNegative())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002708 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00002709 else
Jay Foad6d4db0c2010-12-07 08:25:34 +00002710 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00002711
2712 if (Value == TruncatedValue)
2713 return false;
2714
2715 std::string PrettyValue = Value.toString(10);
2716 std::string PrettyTrunc = TruncatedValue.toString(10);
2717
2718 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2719 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2720 << Init->getSourceRange();
2721
2722 return true;
2723}
2724
John McCalld2a53122010-11-09 23:24:47 +00002725/// Analyze the given simple or compound assignment for warning-worthy
2726/// operations.
2727void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2728 // Just recurse on the LHS.
2729 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2730
2731 // We want to recurse on the RHS as normal unless we're assigning to
2732 // a bitfield.
2733 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00002734 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2735 E->getOperatorLoc())) {
2736 // Recurse, ignoring any implicit conversions on the RHS.
2737 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2738 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00002739 }
2740 }
2741
2742 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2743}
2744
John McCall263a48b2010-01-04 23:31:57 +00002745/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
John McCallacf0ee52010-10-08 02:01:28 +00002746void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2747 unsigned diag) {
2748 S.Diag(E->getExprLoc(), diag)
2749 << E->getType() << T << E->getSourceRange() << SourceRange(CContext);
John McCall263a48b2010-01-04 23:31:57 +00002750}
2751
Douglas Gregor364f7db2011-03-12 00:14:31 +00002752/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2753void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2754 SourceLocation CContext, unsigned diag) {
2755 S.Diag(E->getExprLoc(), diag)
2756 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2757}
2758
John McCall18a2c2c2010-11-09 22:22:12 +00002759std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2760 if (!Range.Width) return "0";
2761
2762 llvm::APSInt ValueInRange = Value;
2763 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002764 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00002765 return ValueInRange.toString(10);
2766}
2767
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002768static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2769 SourceManager &smgr = S.Context.getSourceManager();
2770 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2771}
2772
John McCallcc7e5bf2010-05-06 08:58:33 +00002773void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002774 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002775 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00002776
John McCallcc7e5bf2010-05-06 08:58:33 +00002777 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2778 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2779 if (Source == Target) return;
2780 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00002781
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002782 // If the conversion context location is invalid don't complain.
2783 // We also don't want to emit a warning if the issue occurs from the
2784 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2785 // is slow, so we delay this check as long as possible. Once we detect
2786 // we are in that scenario, we just return.
2787 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00002788 return;
2789
John McCall263a48b2010-01-04 23:31:57 +00002790 // Never diagnose implicit casts to bool.
2791 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2792 return;
2793
2794 // Strip vector types.
2795 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002796 if (!isa<VectorType>(Target)) {
2797 if (isFromSystemMacro(S, CC))
2798 return;
John McCallacf0ee52010-10-08 02:01:28 +00002799 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002800 }
John McCall263a48b2010-01-04 23:31:57 +00002801
2802 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2803 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2804 }
2805
2806 // Strip complex types.
2807 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002808 if (!isa<ComplexType>(Target)) {
2809 if (isFromSystemMacro(S, CC))
2810 return;
2811
John McCallacf0ee52010-10-08 02:01:28 +00002812 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002813 }
John McCall263a48b2010-01-04 23:31:57 +00002814
2815 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2816 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2817 }
2818
2819 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2820 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2821
2822 // If the source is floating point...
2823 if (SourceBT && SourceBT->isFloatingPoint()) {
2824 // ...and the target is floating point...
2825 if (TargetBT && TargetBT->isFloatingPoint()) {
2826 // ...then warn if we're dropping FP rank.
2827
2828 // Builtin FP kinds are ordered by increasing FP rank.
2829 if (SourceBT->getKind() > TargetBT->getKind()) {
2830 // Don't warn about float constants that are precisely
2831 // representable in the target type.
2832 Expr::EvalResult result;
John McCallcc7e5bf2010-05-06 08:58:33 +00002833 if (E->Evaluate(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00002834 // Value might be a float, a float vector, or a float complex.
2835 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00002836 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2837 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00002838 return;
2839 }
2840
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002841 if (isFromSystemMacro(S, CC))
2842 return;
2843
John McCallacf0ee52010-10-08 02:01:28 +00002844 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00002845 }
2846 return;
2847 }
2848
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002849 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00002850 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002851 if (isFromSystemMacro(S, CC))
2852 return;
2853
Chandler Carruth22c7a792011-02-17 11:05:49 +00002854 Expr *InnerE = E->IgnoreParenImpCasts();
2855 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2856 DiagnoseImpCast(S, LiteralExpr, T, CC,
2857 diag::warn_impcast_literal_float_to_integer);
2858 } else {
2859 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2860 }
2861 }
John McCall263a48b2010-01-04 23:31:57 +00002862
2863 return;
2864 }
2865
John McCall70aa5392010-01-06 05:24:50 +00002866 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00002867 return;
2868
John McCallcc7e5bf2010-05-06 08:58:33 +00002869 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00002870 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00002871
2872 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00002873 // If the source is a constant, use a default-on diagnostic.
2874 // TODO: this should happen for bitfield stores, too.
2875 llvm::APSInt Value(32);
2876 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002877 if (isFromSystemMacro(S, CC))
2878 return;
2879
John McCall18a2c2c2010-11-09 22:22:12 +00002880 std::string PrettySourceValue = Value.toString(10);
2881 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2882
2883 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2884 << PrettySourceValue << PrettyTargetValue
2885 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2886 return;
2887 }
2888
John McCall263a48b2010-01-04 23:31:57 +00002889 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2890 // and by god we'll let them.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002891
2892 if (isFromSystemMacro(S, CC))
2893 return;
2894
John McCall70aa5392010-01-06 05:24:50 +00002895 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00002896 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2897 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00002898 }
2899
2900 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2901 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2902 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002903
2904 if (isFromSystemMacro(S, CC))
2905 return;
2906
John McCallcc7e5bf2010-05-06 08:58:33 +00002907 unsigned DiagID = diag::warn_impcast_integer_sign;
2908
2909 // Traditionally, gcc has warned about this under -Wsign-compare.
2910 // We also want to warn about it in -Wconversion.
2911 // So if -Wconversion is off, use a completely identical diagnostic
2912 // in the sign-compare group.
2913 // The conditional-checking code will
2914 if (ICContext) {
2915 DiagID = diag::warn_impcast_integer_sign_conditional;
2916 *ICContext = true;
2917 }
2918
John McCallacf0ee52010-10-08 02:01:28 +00002919 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00002920 }
2921
Douglas Gregora78f1932011-02-22 02:45:07 +00002922 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00002923 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2924 // type, to give us better diagnostics.
2925 QualType SourceType = E->getType();
2926 if (!S.getLangOptions().CPlusPlus) {
2927 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2928 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2929 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2930 SourceType = S.Context.getTypeDeclType(Enum);
2931 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2932 }
2933 }
2934
Douglas Gregora78f1932011-02-22 02:45:07 +00002935 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2936 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2937 if ((SourceEnum->getDecl()->getIdentifier() ||
2938 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2939 (TargetEnum->getDecl()->getIdentifier() ||
2940 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002941 SourceEnum != TargetEnum) {
2942 if (isFromSystemMacro(S, CC))
2943 return;
2944
Douglas Gregor364f7db2011-03-12 00:14:31 +00002945 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00002946 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002947 }
Douglas Gregora78f1932011-02-22 02:45:07 +00002948
John McCall263a48b2010-01-04 23:31:57 +00002949 return;
2950}
2951
John McCallcc7e5bf2010-05-06 08:58:33 +00002952void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2953
2954void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002955 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002956 E = E->IgnoreParenImpCasts();
2957
2958 if (isa<ConditionalOperator>(E))
2959 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2960
John McCallacf0ee52010-10-08 02:01:28 +00002961 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002962 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00002963 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00002964 return;
2965}
2966
2967void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00002968 SourceLocation CC = E->getQuestionLoc();
2969
2970 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002971
2972 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00002973 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2974 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002975
2976 // If -Wconversion would have warned about either of the candidates
2977 // for a signedness conversion to the context type...
2978 if (!Suspicious) return;
2979
2980 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002981 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2982 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00002983 return;
2984
2985 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002986 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00002987 return;
2988
2989 // ...then check whether it would have warned about either of the
2990 // candidates for a signedness conversion to the condition type.
2991 if (E->getType() != T) {
2992 Suspicious = false;
2993 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00002994 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002995 if (!Suspicious)
2996 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00002997 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002998 if (!Suspicious)
2999 return;
3000 }
3001
3002 // If so, emit a diagnostic under -Wsign-compare.
3003 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3004 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3005 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3006 << lex->getType() << rex->getType()
3007 << lex->getSourceRange() << rex->getSourceRange();
3008}
3009
3010/// AnalyzeImplicitConversions - Find and report any interesting
3011/// implicit conversions in the given expression. There are a couple
3012/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003013void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003014 QualType T = OrigE->getType();
3015 Expr *E = OrigE->IgnoreParenImpCasts();
3016
3017 // For conditional operators, we analyze the arguments as if they
3018 // were being fed directly into the output.
3019 if (isa<ConditionalOperator>(E)) {
3020 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3021 CheckConditionalOperator(S, CO, T);
3022 return;
3023 }
3024
3025 // Go ahead and check any implicit conversions we might have skipped.
3026 // The non-canonical typecheck is just an optimization;
3027 // CheckImplicitConversion will filter out dead implicit conversions.
3028 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003029 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003030
3031 // Now continue drilling into this expression.
3032
3033 // Skip past explicit casts.
3034 if (isa<ExplicitCastExpr>(E)) {
3035 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00003036 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003037 }
3038
John McCalld2a53122010-11-09 23:24:47 +00003039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3040 // Do a somewhat different check with comparison operators.
3041 if (BO->isComparisonOp())
3042 return AnalyzeComparison(S, BO);
3043
3044 // And with assignments and compound assignments.
3045 if (BO->isAssignmentOp())
3046 return AnalyzeAssignment(S, BO);
3047 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003048
3049 // These break the otherwise-useful invariant below. Fortunately,
3050 // we don't really need to recurse into them, because any internal
3051 // expressions should have been analyzed already when they were
3052 // built into statements.
3053 if (isa<StmtExpr>(E)) return;
3054
3055 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003056 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00003057
3058 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00003059 CC = E->getExprLoc();
John McCall8322c3a2011-02-13 04:07:26 +00003060 for (Stmt::child_range I = E->children(); I; ++I)
John McCallacf0ee52010-10-08 02:01:28 +00003061 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003062}
3063
3064} // end anonymous namespace
3065
3066/// Diagnoses "dangerous" implicit conversions within the given
3067/// expression (which is a full expression). Implements -Wconversion
3068/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003069///
3070/// \param CC the "context" location of the implicit conversion, i.e.
3071/// the most location of the syntactic entity requiring the implicit
3072/// conversion
3073void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003074 // Don't diagnose in unevaluated contexts.
3075 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3076 return;
3077
3078 // Don't diagnose for value- or type-dependent expressions.
3079 if (E->isTypeDependent() || E->isValueDependent())
3080 return;
3081
John McCallacf0ee52010-10-08 02:01:28 +00003082 // This is not the right CC for (e.g.) a variable initialization.
3083 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003084}
3085
John McCall1f425642010-11-11 03:21:53 +00003086void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3087 FieldDecl *BitField,
3088 Expr *Init) {
3089 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3090}
3091
Mike Stump0c2ec772010-01-21 03:59:47 +00003092/// CheckParmsForFunctionDef - Check that the parameters of the given
3093/// function are appropriate for the definition of a function. This
3094/// takes care of any checks that cannot be performed on the
3095/// declaration itself, e.g., that the types of each of the function
3096/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00003097bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3098 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00003099 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00003100 for (; P != PEnd; ++P) {
3101 ParmVarDecl *Param = *P;
3102
Mike Stump0c2ec772010-01-21 03:59:47 +00003103 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3104 // function declarator that is part of a function definition of
3105 // that function shall not have incomplete type.
3106 //
3107 // This is also C++ [dcl.fct]p6.
3108 if (!Param->isInvalidDecl() &&
3109 RequireCompleteType(Param->getLocation(), Param->getType(),
3110 diag::err_typecheck_decl_incomplete_type)) {
3111 Param->setInvalidDecl();
3112 HasInvalidParm = true;
3113 }
3114
3115 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3116 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00003117 if (CheckParameterNames &&
3118 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00003119 !Param->isImplicit() &&
3120 !getLangOptions().CPlusPlus)
3121 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00003122
3123 // C99 6.7.5.3p12:
3124 // If the function declarator is not part of a definition of that
3125 // function, parameters may have incomplete type and may use the [*]
3126 // notation in their sequences of declarator specifiers to specify
3127 // variable length array types.
3128 QualType PType = Param->getOriginalType();
3129 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3130 if (AT->getSizeModifier() == ArrayType::Star) {
3131 // FIXME: This diagnosic should point the the '[*]' if source-location
3132 // information is added for it.
3133 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3134 }
3135 }
Mike Stump0c2ec772010-01-21 03:59:47 +00003136 }
3137
3138 return HasInvalidParm;
3139}
John McCall2b5c1b22010-08-12 21:44:57 +00003140
3141/// CheckCastAlign - Implements -Wcast-align, which warns when a
3142/// pointer cast increases the alignment requirements.
3143void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3144 // This is actually a lot of work to potentially be doing on every
3145 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003146 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3147 TRange.getBegin())
John McCall2b5c1b22010-08-12 21:44:57 +00003148 == Diagnostic::Ignored)
3149 return;
3150
3151 // Ignore dependent types.
3152 if (T->isDependentType() || Op->getType()->isDependentType())
3153 return;
3154
3155 // Require that the destination be a pointer type.
3156 const PointerType *DestPtr = T->getAs<PointerType>();
3157 if (!DestPtr) return;
3158
3159 // If the destination has alignment 1, we're done.
3160 QualType DestPointee = DestPtr->getPointeeType();
3161 if (DestPointee->isIncompleteType()) return;
3162 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3163 if (DestAlign.isOne()) return;
3164
3165 // Require that the source be a pointer type.
3166 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3167 if (!SrcPtr) return;
3168 QualType SrcPointee = SrcPtr->getPointeeType();
3169
3170 // Whitelist casts from cv void*. We already implicitly
3171 // whitelisted casts to cv void*, since they have alignment 1.
3172 // Also whitelist casts involving incomplete types, which implicitly
3173 // includes 'void'.
3174 if (SrcPointee->isIncompleteType()) return;
3175
3176 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3177 if (SrcAlign >= DestAlign) return;
3178
3179 Diag(TRange.getBegin(), diag::warn_cast_align)
3180 << Op->getType() << T
3181 << static_cast<unsigned>(SrcAlign.getQuantity())
3182 << static_cast<unsigned>(DestAlign.getQuantity())
3183 << TRange << Op->getSourceRange();
3184}
3185
Ted Kremenekdf26df72011-03-01 18:41:00 +00003186static void CheckArrayAccess_Check(Sema &S,
3187 const clang::ArraySubscriptExpr *E) {
Chandler Carruth1af88f12011-02-17 21:10:52 +00003188 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003189 const ConstantArrayType *ArrayTy =
Ted Kremenekdf26df72011-03-01 18:41:00 +00003190 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003191 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00003192 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00003193
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003194 const Expr *IndexExpr = E->getIdx();
3195 if (IndexExpr->isValueDependent())
Ted Kremenek64699be2011-02-16 01:57:07 +00003196 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003197 llvm::APSInt index;
Ted Kremenekdf26df72011-03-01 18:41:00 +00003198 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00003199 return;
Ted Kremenek108b2d52011-02-16 04:01:44 +00003200
Ted Kremeneke4b316c2011-02-23 23:06:04 +00003201 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003202 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00003203 if (!size.isStrictlyPositive())
3204 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003205 if (size.getBitWidth() > index.getBitWidth())
3206 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003207 else if (size.getBitWidth() < index.getBitWidth())
3208 size = size.sext(index.getBitWidth());
3209
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003210 if (index.slt(size))
Ted Kremenek108b2d52011-02-16 04:01:44 +00003211 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003212
Ted Kremenekdf26df72011-03-01 18:41:00 +00003213 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3214 S.PDiag(diag::warn_array_index_exceeds_bounds)
3215 << index.toString(10, true)
3216 << size.toString(10, true)
3217 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003218 } else {
Ted Kremenekdf26df72011-03-01 18:41:00 +00003219 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3220 S.PDiag(diag::warn_array_index_precedes_bounds)
3221 << index.toString(10, true)
3222 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00003223 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00003224
3225 const NamedDecl *ND = NULL;
3226 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3227 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3228 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3229 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3230 if (ND)
Ted Kremenekdf26df72011-03-01 18:41:00 +00003231 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3232 S.PDiag(diag::note_array_index_out_of_bounds)
3233 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00003234}
3235
Ted Kremenekdf26df72011-03-01 18:41:00 +00003236void Sema::CheckArrayAccess(const Expr *expr) {
3237 while (true)
3238 switch (expr->getStmtClass()) {
3239 case Stmt::ParenExprClass:
3240 expr = cast<ParenExpr>(expr)->getSubExpr();
3241 continue;
3242 case Stmt::ArraySubscriptExprClass:
3243 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3244 return;
3245 case Stmt::ConditionalOperatorClass: {
3246 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3247 if (const Expr *lhs = cond->getLHS())
3248 CheckArrayAccess(lhs);
3249 if (const Expr *rhs = cond->getRHS())
3250 CheckArrayAccess(rhs);
3251 return;
3252 }
3253 default:
3254 return;
3255 }
3256}