blob: 105fb52ddb55bf4ba59807fedf6d7a8f148b52ec [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) {
Nick Lewyckyd4693212011-03-25 01:44:32 +0000316 CheckNonNullArguments(*i, TheCall->getArgs(),
317 TheCall->getCallee()->getLocStart());
Ted Kremenekb8176da2010-09-09 04:33:05 +0000318 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000319
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000320 return false;
Anders Carlsson98f07902007-08-17 05:31:46 +0000321}
322
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000323bool Sema::CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall) {
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000324 // Printf checking.
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000325 const FormatAttr *Format = NDecl->getAttr<FormatAttr>();
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000326 if (!Format)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000327 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000328
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000329 const VarDecl *V = dyn_cast<VarDecl>(NDecl);
330 if (!V)
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000331 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000332
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000333 QualType Ty = V->getType();
334 if (!Ty->isBlockPointerType())
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000335 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000336
Ted Kremenek02087932010-07-16 02:11:22 +0000337 const bool b = Format->getType() == "scanf";
338 if (!b && !CheckablePrintfAttr(Format, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000339 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000340
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000341 bool HasVAListArg = Format->getFirstArg() == 0;
Ted Kremenek02087932010-07-16 02:11:22 +0000342 CheckPrintfScanfArguments(TheCall, HasVAListArg, Format->getFormatIdx() - 1,
343 HasVAListArg ? 0 : Format->getFirstArg() - 1, !b);
Anders Carlssonbc4c1072009-08-16 01:56:34 +0000344
345 return false;
Fariborz Jahanianc1585be2009-05-18 21:05:18 +0000346}
347
Chris Lattnerdc046542009-05-08 06:58:22 +0000348/// SemaBuiltinAtomicOverloaded - We have a call to a function like
349/// __sync_fetch_and_add, which is an overloaded function based on the pointer
350/// type of its first argument. The main ActOnCallExpr routines have already
351/// promoted the types of arguments because all of these calls are prototyped as
352/// void(...).
353///
354/// This function goes through and does final semantic checking for these
355/// builtins,
John McCalldadc5752010-08-24 06:29:42 +0000356ExprResult
357Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000358 CallExpr *TheCall = (CallExpr *)TheCallResult.get();
Chris Lattnerdc046542009-05-08 06:58:22 +0000359 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
360 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
361
362 // Ensure that we have at least one argument to do type inference from.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000363 if (TheCall->getNumArgs() < 1) {
364 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
365 << 0 << 1 << TheCall->getNumArgs()
366 << TheCall->getCallee()->getSourceRange();
367 return ExprError();
368 }
Mike Stump11289f42009-09-09 15:08:12 +0000369
Chris Lattnerdc046542009-05-08 06:58:22 +0000370 // Inspect the first argument of the atomic builtin. This should always be
371 // a pointer type, whose element is an integral scalar or pointer type.
372 // Because it is a pointer type, we don't have to worry about any implicit
373 // casts here.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000374 // FIXME: We don't allow floating point scalars as input.
Chris Lattnerdc046542009-05-08 06:58:22 +0000375 Expr *FirstArg = TheCall->getArg(0);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000376 if (!FirstArg->getType()->isPointerType()) {
377 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
378 << FirstArg->getType() << FirstArg->getSourceRange();
379 return ExprError();
380 }
Mike Stump11289f42009-09-09 15:08:12 +0000381
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000382 QualType ValType =
383 FirstArg->getType()->getAs<PointerType>()->getPointeeType();
Chris Lattnerbb3bcd82010-09-17 21:12:38 +0000384 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000385 !ValType->isBlockPointerType()) {
386 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
387 << FirstArg->getType() << FirstArg->getSourceRange();
388 return ExprError();
389 }
Chris Lattnerdc046542009-05-08 06:58:22 +0000390
Chandler Carruth3973af72010-07-18 20:54:12 +0000391 // The majority of builtins return a value, but a few have special return
392 // types, so allow them to override appropriately below.
393 QualType ResultType = ValType;
394
Chris Lattnerdc046542009-05-08 06:58:22 +0000395 // We need to figure out which concrete builtin this maps onto. For example,
396 // __sync_fetch_and_add with a 2 byte object turns into
397 // __sync_fetch_and_add_2.
398#define BUILTIN_ROW(x) \
399 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
400 Builtin::BI##x##_8, Builtin::BI##x##_16 }
Mike Stump11289f42009-09-09 15:08:12 +0000401
Chris Lattnerdc046542009-05-08 06:58:22 +0000402 static const unsigned BuiltinIndices[][5] = {
403 BUILTIN_ROW(__sync_fetch_and_add),
404 BUILTIN_ROW(__sync_fetch_and_sub),
405 BUILTIN_ROW(__sync_fetch_and_or),
406 BUILTIN_ROW(__sync_fetch_and_and),
407 BUILTIN_ROW(__sync_fetch_and_xor),
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattnerdc046542009-05-08 06:58:22 +0000409 BUILTIN_ROW(__sync_add_and_fetch),
410 BUILTIN_ROW(__sync_sub_and_fetch),
411 BUILTIN_ROW(__sync_and_and_fetch),
412 BUILTIN_ROW(__sync_or_and_fetch),
413 BUILTIN_ROW(__sync_xor_and_fetch),
Mike Stump11289f42009-09-09 15:08:12 +0000414
Chris Lattnerdc046542009-05-08 06:58:22 +0000415 BUILTIN_ROW(__sync_val_compare_and_swap),
416 BUILTIN_ROW(__sync_bool_compare_and_swap),
417 BUILTIN_ROW(__sync_lock_test_and_set),
418 BUILTIN_ROW(__sync_lock_release)
419 };
Mike Stump11289f42009-09-09 15:08:12 +0000420#undef BUILTIN_ROW
421
Chris Lattnerdc046542009-05-08 06:58:22 +0000422 // Determine the index of the size.
423 unsigned SizeIndex;
Ken Dyck40775002010-01-11 17:06:35 +0000424 switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000425 case 1: SizeIndex = 0; break;
426 case 2: SizeIndex = 1; break;
427 case 4: SizeIndex = 2; break;
428 case 8: SizeIndex = 3; break;
429 case 16: SizeIndex = 4; break;
430 default:
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000431 Diag(DRE->getLocStart(), diag::err_atomic_builtin_pointer_size)
432 << FirstArg->getType() << FirstArg->getSourceRange();
433 return ExprError();
Chris Lattnerdc046542009-05-08 06:58:22 +0000434 }
Mike Stump11289f42009-09-09 15:08:12 +0000435
Chris Lattnerdc046542009-05-08 06:58:22 +0000436 // Each of these builtins has one pointer argument, followed by some number of
437 // values (0, 1 or 2) followed by a potentially empty varags list of stuff
438 // that we ignore. Find out which row of BuiltinIndices to read from as well
439 // as the number of fixed args.
Douglas Gregor15fc9562009-09-12 00:22:50 +0000440 unsigned BuiltinID = FDecl->getBuiltinID();
Chris Lattnerdc046542009-05-08 06:58:22 +0000441 unsigned BuiltinIndex, NumFixed = 1;
442 switch (BuiltinID) {
443 default: assert(0 && "Unknown overloaded atomic builtin!");
444 case Builtin::BI__sync_fetch_and_add: BuiltinIndex = 0; break;
445 case Builtin::BI__sync_fetch_and_sub: BuiltinIndex = 1; break;
446 case Builtin::BI__sync_fetch_and_or: BuiltinIndex = 2; break;
447 case Builtin::BI__sync_fetch_and_and: BuiltinIndex = 3; break;
448 case Builtin::BI__sync_fetch_and_xor: BuiltinIndex = 4; break;
Mike Stump11289f42009-09-09 15:08:12 +0000449
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000450 case Builtin::BI__sync_add_and_fetch: BuiltinIndex = 5; break;
451 case Builtin::BI__sync_sub_and_fetch: BuiltinIndex = 6; break;
452 case Builtin::BI__sync_and_and_fetch: BuiltinIndex = 7; break;
453 case Builtin::BI__sync_or_and_fetch: BuiltinIndex = 8; break;
454 case Builtin::BI__sync_xor_and_fetch: BuiltinIndex = 9; break;
Mike Stump11289f42009-09-09 15:08:12 +0000455
Chris Lattnerdc046542009-05-08 06:58:22 +0000456 case Builtin::BI__sync_val_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000457 BuiltinIndex = 10;
Chris Lattnerdc046542009-05-08 06:58:22 +0000458 NumFixed = 2;
459 break;
460 case Builtin::BI__sync_bool_compare_and_swap:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000461 BuiltinIndex = 11;
Chris Lattnerdc046542009-05-08 06:58:22 +0000462 NumFixed = 2;
Chandler Carruth3973af72010-07-18 20:54:12 +0000463 ResultType = Context.BoolTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000464 break;
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000465 case Builtin::BI__sync_lock_test_and_set: BuiltinIndex = 12; break;
Chris Lattnerdc046542009-05-08 06:58:22 +0000466 case Builtin::BI__sync_lock_release:
Daniel Dunbar3f540c0d2010-03-25 17:13:09 +0000467 BuiltinIndex = 13;
Chris Lattnerdc046542009-05-08 06:58:22 +0000468 NumFixed = 0;
Chandler Carruth3973af72010-07-18 20:54:12 +0000469 ResultType = Context.VoidTy;
Chris Lattnerdc046542009-05-08 06:58:22 +0000470 break;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Chris Lattnerdc046542009-05-08 06:58:22 +0000473 // Now that we know how many fixed arguments we expect, first check that we
474 // have at least that many.
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000475 if (TheCall->getNumArgs() < 1+NumFixed) {
476 Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
477 << 0 << 1+NumFixed << TheCall->getNumArgs()
478 << TheCall->getCallee()->getSourceRange();
479 return ExprError();
480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner5b9241b2009-05-08 15:36:58 +0000482 // Get the decl for the concrete builtin from this, we can tell what the
483 // concrete integer type we should convert to is.
484 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
485 const char *NewBuiltinName = Context.BuiltinInfo.GetName(NewBuiltinID);
486 IdentifierInfo *NewBuiltinII = PP.getIdentifierInfo(NewBuiltinName);
Mike Stump11289f42009-09-09 15:08:12 +0000487 FunctionDecl *NewBuiltinDecl =
Chris Lattner5b9241b2009-05-08 15:36:58 +0000488 cast<FunctionDecl>(LazilyCreateBuiltin(NewBuiltinII, NewBuiltinID,
489 TUScope, false, DRE->getLocStart()));
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000490
John McCallcf142162010-08-07 06:22:56 +0000491 // The first argument --- the pointer --- has a fixed type; we
492 // deduce the types of the rest of the arguments accordingly. Walk
493 // the remaining arguments, converting them to the deduced value type.
Chris Lattnerdc046542009-05-08 06:58:22 +0000494 for (unsigned i = 0; i != NumFixed; ++i) {
John Wiegley01296292011-04-08 18:41:53 +0000495 ExprResult Arg = TheCall->getArg(i+1);
Mike Stump11289f42009-09-09 15:08:12 +0000496
Chris Lattnerdc046542009-05-08 06:58:22 +0000497 // If the argument is an implicit cast, then there was a promotion due to
498 // "...", just remove it now.
John Wiegley01296292011-04-08 18:41:53 +0000499 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg.get())) {
Chris Lattnerdc046542009-05-08 06:58:22 +0000500 Arg = ICE->getSubExpr();
501 ICE->setSubExpr(0);
John Wiegley01296292011-04-08 18:41:53 +0000502 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +0000503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Chris Lattnerdc046542009-05-08 06:58:22 +0000505 // GCC does an implicit conversion to the pointer or integer ValType. This
506 // can fail in some cases (1i -> int**), check for this error case now.
John McCall8cb679e2010-11-15 09:13:47 +0000507 CastKind Kind = CK_Invalid;
John McCall7decc9e2010-11-18 06:31:45 +0000508 ExprValueKind VK = VK_RValue;
John McCallcf142162010-08-07 06:22:56 +0000509 CXXCastPath BasePath;
John Wiegley01296292011-04-08 18:41:53 +0000510 Arg = CheckCastTypes(Arg.get()->getSourceRange(), ValType, Arg.take(), Kind, VK, BasePath);
511 if (Arg.isInvalid())
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000512 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +0000513
Chris Lattnerdc046542009-05-08 06:58:22 +0000514 // Okay, we have something that *can* be converted to the right type. Check
515 // to see if there is a potentially weird extension going on here. This can
516 // happen when you do an atomic operation on something like an char* and
517 // pass in 42. The 42 gets converted to char. This is even more strange
518 // for things like 45.123 -> char, etc.
Mike Stump11289f42009-09-09 15:08:12 +0000519 // FIXME: Do this check.
John Wiegley01296292011-04-08 18:41:53 +0000520 Arg = ImpCastExprToType(Arg.take(), ValType, Kind, VK, &BasePath);
521 TheCall->setArg(i+1, Arg.get());
Chris Lattnerdc046542009-05-08 06:58:22 +0000522 }
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnerdc046542009-05-08 06:58:22 +0000524 // Switch the DeclRefExpr to refer to the new decl.
525 DRE->setDecl(NewBuiltinDecl);
526 DRE->setType(NewBuiltinDecl->getType());
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattnerdc046542009-05-08 06:58:22 +0000528 // Set the callee in the CallExpr.
529 // FIXME: This leaks the original parens and implicit casts.
John Wiegley01296292011-04-08 18:41:53 +0000530 ExprResult PromotedCall = UsualUnaryConversions(DRE);
531 if (PromotedCall.isInvalid())
532 return ExprError();
533 TheCall->setCallee(PromotedCall.take());
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chandler Carruthbc8cab12010-07-18 07:23:17 +0000535 // Change the result type of the call to match the original value type. This
536 // is arbitrary, but the codegen for these builtins ins design to handle it
537 // gracefully.
Chandler Carruth3973af72010-07-18 20:54:12 +0000538 TheCall->setType(ResultType);
Chandler Carruth741e5ce2010-07-09 18:59:35 +0000539
540 return move(TheCallResult);
Chris Lattnerdc046542009-05-08 06:58:22 +0000541}
542
543
Chris Lattner6436fb62009-02-18 06:01:06 +0000544/// CheckObjCString - Checks that the argument to the builtin
Anders Carlsson98f07902007-08-17 05:31:46 +0000545/// CFString constructor is correct
Steve Narofffb46e862009-04-13 20:26:29 +0000546/// Note: It might also make sense to do the UTF-16 conversion here (would
547/// simplify the backend).
Chris Lattner6436fb62009-02-18 06:01:06 +0000548bool Sema::CheckObjCString(Expr *Arg) {
Chris Lattnerf2660962008-02-13 01:02:39 +0000549 Arg = Arg->IgnoreParenCasts();
Anders Carlsson98f07902007-08-17 05:31:46 +0000550 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
551
552 if (!Literal || Literal->isWide()) {
Chris Lattner3b054132008-11-19 05:08:23 +0000553 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
554 << Arg->getSourceRange();
Anders Carlssona3a9c432007-08-17 15:44:17 +0000555 return true;
Anders Carlsson98f07902007-08-17 05:31:46 +0000556 }
Mike Stump11289f42009-09-09 15:08:12 +0000557
Fariborz Jahanian56603ef2010-09-07 19:38:13 +0000558 if (Literal->containsNonAsciiOrNull()) {
559 llvm::StringRef String = Literal->getString();
560 unsigned NumBytes = String.size();
561 llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
562 const UTF8 *FromPtr = (UTF8 *)String.data();
563 UTF16 *ToPtr = &ToBuf[0];
564
565 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
566 &ToPtr, ToPtr + NumBytes,
567 strictConversion);
568 // Check for conversion failure.
569 if (Result != conversionOK)
570 Diag(Arg->getLocStart(),
571 diag::warn_cfstring_truncated) << Arg->getSourceRange();
572 }
Anders Carlssona3a9c432007-08-17 15:44:17 +0000573 return false;
Chris Lattnerb87b1b32007-08-10 20:18:51 +0000574}
575
Chris Lattnere202e6a2007-12-20 00:05:45 +0000576/// SemaBuiltinVAStart - Check the arguments to __builtin_va_start for validity.
577/// Emit an error and return true on failure, return false on success.
Chris Lattner08464942007-12-28 05:29:59 +0000578bool Sema::SemaBuiltinVAStart(CallExpr *TheCall) {
579 Expr *Fn = TheCall->getCallee();
580 if (TheCall->getNumArgs() > 2) {
Chris Lattnercedef8d2008-11-21 18:44:24 +0000581 Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000582 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000583 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
584 << Fn->getSourceRange()
Mike Stump11289f42009-09-09 15:08:12 +0000585 << SourceRange(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000586 (*(TheCall->arg_end()-1))->getLocEnd());
Chris Lattner43be2e62007-12-19 23:59:04 +0000587 return true;
588 }
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000589
590 if (TheCall->getNumArgs() < 2) {
Eric Christopherabf1e182010-04-16 04:48:22 +0000591 return Diag(TheCall->getLocEnd(),
592 diag::err_typecheck_call_too_few_args_at_least)
593 << 0 /*function call*/ << 2 << TheCall->getNumArgs();
Eli Friedmanbb2b3be2008-12-15 22:05:35 +0000594 }
595
Chris Lattnere202e6a2007-12-20 00:05:45 +0000596 // Determine whether the current function is variadic or not.
Douglas Gregor9a28e842010-03-01 23:15:13 +0000597 BlockScopeInfo *CurBlock = getCurBlock();
Chris Lattnere202e6a2007-12-20 00:05:45 +0000598 bool isVariadic;
Steve Naroff439a3e42009-04-15 19:33:47 +0000599 if (CurBlock)
John McCall8e346702010-06-04 19:02:56 +0000600 isVariadic = CurBlock->TheDecl->isVariadic();
Ted Kremenek186a0742010-04-29 16:49:01 +0000601 else if (FunctionDecl *FD = getCurFunctionDecl())
602 isVariadic = FD->isVariadic();
603 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000604 isVariadic = getCurMethodDecl()->isVariadic();
Mike Stump11289f42009-09-09 15:08:12 +0000605
Chris Lattnere202e6a2007-12-20 00:05:45 +0000606 if (!isVariadic) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000607 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
608 return true;
609 }
Mike Stump11289f42009-09-09 15:08:12 +0000610
Chris Lattner43be2e62007-12-19 23:59:04 +0000611 // Verify that the second argument to the builtin is the last argument of the
612 // current function or method.
613 bool SecondArgIsLastNamedArgument = false;
Anders Carlsson73cc5072008-02-13 01:22:59 +0000614 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +0000615
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000616 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
617 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
Chris Lattner43be2e62007-12-19 23:59:04 +0000618 // FIXME: This isn't correct for methods (results in bogus warning).
619 // Get the last formal in the current function.
Anders Carlsson6a8350b2008-02-11 04:20:54 +0000620 const ParmVarDecl *LastArg;
Steve Naroff439a3e42009-04-15 19:33:47 +0000621 if (CurBlock)
622 LastArg = *(CurBlock->TheDecl->param_end()-1);
623 else if (FunctionDecl *FD = getCurFunctionDecl())
Chris Lattner79413952008-12-04 23:50:19 +0000624 LastArg = *(FD->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000625 else
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +0000626 LastArg = *(getCurMethodDecl()->param_end()-1);
Chris Lattner43be2e62007-12-19 23:59:04 +0000627 SecondArgIsLastNamedArgument = PV == LastArg;
628 }
629 }
Mike Stump11289f42009-09-09 15:08:12 +0000630
Chris Lattner43be2e62007-12-19 23:59:04 +0000631 if (!SecondArgIsLastNamedArgument)
Mike Stump11289f42009-09-09 15:08:12 +0000632 Diag(TheCall->getArg(1)->getLocStart(),
Chris Lattner43be2e62007-12-19 23:59:04 +0000633 diag::warn_second_parameter_of_va_start_not_last_named_argument);
634 return false;
Eli Friedmanf8353032008-05-20 08:23:37 +0000635}
Chris Lattner43be2e62007-12-19 23:59:04 +0000636
Chris Lattner2da14fb2007-12-20 00:26:33 +0000637/// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
638/// friends. This is declared to take (...), so we have to check everything.
Chris Lattner08464942007-12-28 05:29:59 +0000639bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
640 if (TheCall->getNumArgs() < 2)
Chris Lattnercedef8d2008-11-21 18:44:24 +0000641 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000642 << 0 << 2 << TheCall->getNumArgs()/*function call*/;
Chris Lattner08464942007-12-28 05:29:59 +0000643 if (TheCall->getNumArgs() > 2)
Mike Stump11289f42009-09-09 15:08:12 +0000644 return Diag(TheCall->getArg(2)->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000645 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000646 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Chris Lattner3b054132008-11-19 05:08:23 +0000647 << SourceRange(TheCall->getArg(2)->getLocStart(),
648 (*(TheCall->arg_end()-1))->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000649
John Wiegley01296292011-04-08 18:41:53 +0000650 ExprResult OrigArg0 = TheCall->getArg(0);
651 ExprResult OrigArg1 = TheCall->getArg(1);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000652
Chris Lattner2da14fb2007-12-20 00:26:33 +0000653 // Do standard promotions between the two arguments, returning their common
654 // type.
Chris Lattner08464942007-12-28 05:29:59 +0000655 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1, false);
John Wiegley01296292011-04-08 18:41:53 +0000656 if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
657 return true;
Daniel Dunbar96f86772009-02-19 19:28:43 +0000658
659 // Make sure any conversions are pushed back into the call; this is
660 // type safe since unordered compare builtins are declared as "_Bool
661 // foo(...)".
John Wiegley01296292011-04-08 18:41:53 +0000662 TheCall->setArg(0, OrigArg0.get());
663 TheCall->setArg(1, OrigArg1.get());
Mike Stump11289f42009-09-09 15:08:12 +0000664
John Wiegley01296292011-04-08 18:41:53 +0000665 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
Douglas Gregorc25f7662009-05-19 22:10:17 +0000666 return false;
667
Chris Lattner2da14fb2007-12-20 00:26:33 +0000668 // If the common type isn't a real floating type, then the arguments were
669 // invalid for this operation.
670 if (!Res->isRealFloatingType())
John Wiegley01296292011-04-08 18:41:53 +0000671 return Diag(OrigArg0.get()->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000672 diag::err_typecheck_call_invalid_ordered_compare)
John Wiegley01296292011-04-08 18:41:53 +0000673 << OrigArg0.get()->getType() << OrigArg1.get()->getType()
674 << SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.get()->getLocEnd());
Mike Stump11289f42009-09-09 15:08:12 +0000675
Chris Lattner2da14fb2007-12-20 00:26:33 +0000676 return false;
677}
678
Benjamin Kramer634fc102010-02-15 22:42:31 +0000679/// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
680/// __builtin_isnan and friends. This is declared to take (...), so we have
Benjamin Kramer64aae502010-02-16 10:07:31 +0000681/// to check everything. We expect the last argument to be a floating point
682/// value.
683bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
684 if (TheCall->getNumArgs() < NumArgs)
Eli Friedman7e4faac2009-08-31 20:06:00 +0000685 return Diag(TheCall->getLocEnd(), diag::err_typecheck_call_too_few_args)
Eric Christopherabf1e182010-04-16 04:48:22 +0000686 << 0 << NumArgs << TheCall->getNumArgs()/*function call*/;
Benjamin Kramer64aae502010-02-16 10:07:31 +0000687 if (TheCall->getNumArgs() > NumArgs)
688 return Diag(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000689 diag::err_typecheck_call_too_many_args)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000690 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs()
Benjamin Kramer64aae502010-02-16 10:07:31 +0000691 << SourceRange(TheCall->getArg(NumArgs)->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000692 (*(TheCall->arg_end()-1))->getLocEnd());
693
Benjamin Kramer64aae502010-02-16 10:07:31 +0000694 Expr *OrigArg = TheCall->getArg(NumArgs-1);
Mike Stump11289f42009-09-09 15:08:12 +0000695
Eli Friedman7e4faac2009-08-31 20:06:00 +0000696 if (OrigArg->isTypeDependent())
697 return false;
698
Chris Lattner68784ef2010-05-06 05:50:07 +0000699 // This operation requires a non-_Complex floating-point number.
Eli Friedman7e4faac2009-08-31 20:06:00 +0000700 if (!OrigArg->getType()->isRealFloatingType())
Mike Stump11289f42009-09-09 15:08:12 +0000701 return Diag(OrigArg->getLocStart(),
Eli Friedman7e4faac2009-08-31 20:06:00 +0000702 diag::err_typecheck_call_invalid_unary_fp)
703 << OrigArg->getType() << OrigArg->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +0000704
Chris Lattner68784ef2010-05-06 05:50:07 +0000705 // If this is an implicit conversion from float -> double, remove it.
706 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(OrigArg)) {
707 Expr *CastArg = Cast->getSubExpr();
708 if (CastArg->getType()->isSpecificBuiltinType(BuiltinType::Float)) {
709 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
710 "promotion from float to double is the only expected cast here");
711 Cast->setSubExpr(0);
Chris Lattner68784ef2010-05-06 05:50:07 +0000712 TheCall->setArg(NumArgs-1, CastArg);
713 OrigArg = CastArg;
714 }
715 }
716
Eli Friedman7e4faac2009-08-31 20:06:00 +0000717 return false;
718}
719
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000720/// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
721// This is declared to take (...), so we have to check everything.
John McCalldadc5752010-08-24 06:29:42 +0000722ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
Nate Begemana0110022010-06-08 00:16:34 +0000723 if (TheCall->getNumArgs() < 2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000724 return ExprError(Diag(TheCall->getLocEnd(),
Eric Christopherabf1e182010-04-16 04:48:22 +0000725 diag::err_typecheck_call_too_few_args_at_least)
Nate Begemana0110022010-06-08 00:16:34 +0000726 << 0 /*function call*/ << 2 << TheCall->getNumArgs()
Eric Christopherabf1e182010-04-16 04:48:22 +0000727 << TheCall->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000728
Nate Begemana0110022010-06-08 00:16:34 +0000729 // Determine which of the following types of shufflevector we're checking:
730 // 1) unary, vector mask: (lhs, mask)
731 // 2) binary, vector mask: (lhs, rhs, mask)
732 // 3) binary, scalar mask: (lhs, rhs, index, ..., index)
733 QualType resType = TheCall->getArg(0)->getType();
734 unsigned numElements = 0;
735
Douglas Gregorc25f7662009-05-19 22:10:17 +0000736 if (!TheCall->getArg(0)->isTypeDependent() &&
737 !TheCall->getArg(1)->isTypeDependent()) {
Nate Begemana0110022010-06-08 00:16:34 +0000738 QualType LHSType = TheCall->getArg(0)->getType();
739 QualType RHSType = TheCall->getArg(1)->getType();
740
741 if (!LHSType->isVectorType() || !RHSType->isVectorType()) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000742 Diag(TheCall->getLocStart(), diag::err_shufflevector_non_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000743 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000744 TheCall->getArg(1)->getLocEnd());
745 return ExprError();
746 }
Nate Begemana0110022010-06-08 00:16:34 +0000747
748 numElements = LHSType->getAs<VectorType>()->getNumElements();
749 unsigned numResElements = TheCall->getNumArgs() - 2;
Mike Stump11289f42009-09-09 15:08:12 +0000750
Nate Begemana0110022010-06-08 00:16:34 +0000751 // Check to see if we have a call with 2 vector arguments, the unary shuffle
752 // with mask. If so, verify that RHS is an integer vector type with the
753 // same number of elts as lhs.
754 if (TheCall->getNumArgs() == 2) {
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +0000755 if (!RHSType->hasIntegerRepresentation() ||
Nate Begemana0110022010-06-08 00:16:34 +0000756 RHSType->getAs<VectorType>()->getNumElements() != numElements)
757 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
758 << SourceRange(TheCall->getArg(1)->getLocStart(),
759 TheCall->getArg(1)->getLocEnd());
760 numResElements = numElements;
761 }
762 else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000763 Diag(TheCall->getLocStart(), diag::err_shufflevector_incompatible_vector)
Mike Stump11289f42009-09-09 15:08:12 +0000764 << SourceRange(TheCall->getArg(0)->getLocStart(),
Douglas Gregorc25f7662009-05-19 22:10:17 +0000765 TheCall->getArg(1)->getLocEnd());
766 return ExprError();
Nate Begemana0110022010-06-08 00:16:34 +0000767 } else if (numElements != numResElements) {
768 QualType eltType = LHSType->getAs<VectorType>()->getElementType();
Chris Lattner37141f42010-06-23 06:00:24 +0000769 resType = Context.getVectorType(eltType, numResElements,
Bob Wilsonaeb56442010-11-10 21:56:12 +0000770 VectorType::GenericVector);
Douglas Gregorc25f7662009-05-19 22:10:17 +0000771 }
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000772 }
773
774 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
Douglas Gregorc25f7662009-05-19 22:10:17 +0000775 if (TheCall->getArg(i)->isTypeDependent() ||
776 TheCall->getArg(i)->isValueDependent())
777 continue;
778
Nate Begemana0110022010-06-08 00:16:34 +0000779 llvm::APSInt Result(32);
780 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context))
781 return ExprError(Diag(TheCall->getLocStart(),
782 diag::err_shufflevector_nonconstant_argument)
783 << TheCall->getArg(i)->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000784
Chris Lattner7ab824e2008-08-10 02:05:13 +0000785 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000786 return ExprError(Diag(TheCall->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +0000787 diag::err_shufflevector_argument_too_large)
Sebastian Redlc215cfc2009-01-19 00:08:26 +0000788 << TheCall->getArg(i)->getSourceRange());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000789 }
790
791 llvm::SmallVector<Expr*, 32> exprs;
792
Chris Lattner7ab824e2008-08-10 02:05:13 +0000793 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000794 exprs.push_back(TheCall->getArg(i));
795 TheCall->setArg(i, 0);
796 }
797
Nate Begemanf485fb52009-08-12 02:10:25 +0000798 return Owned(new (Context) ShuffleVectorExpr(Context, exprs.begin(),
Nate Begemana0110022010-06-08 00:16:34 +0000799 exprs.size(), resType,
Ted Kremenek5a201952009-02-07 01:47:29 +0000800 TheCall->getCallee()->getLocStart(),
801 TheCall->getRParenLoc()));
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000802}
Chris Lattner43be2e62007-12-19 23:59:04 +0000803
Daniel Dunbarb7257262008-07-21 22:59:13 +0000804/// SemaBuiltinPrefetch - Handle __builtin_prefetch.
805// This is declared to take (const void*, ...) and can take two
806// optional constant int args.
807bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
Chris Lattner3b054132008-11-19 05:08:23 +0000808 unsigned NumArgs = TheCall->getNumArgs();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000809
Chris Lattner3b054132008-11-19 05:08:23 +0000810 if (NumArgs > 3)
Eric Christopher2a5aaff2010-04-16 04:56:46 +0000811 return Diag(TheCall->getLocEnd(),
812 diag::err_typecheck_call_too_many_args_at_most)
813 << 0 /*function call*/ << 3 << NumArgs
814 << TheCall->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000815
816 // Argument 0 is checked for us and the remaining arguments must be
817 // constant integers.
Chris Lattner3b054132008-11-19 05:08:23 +0000818 for (unsigned i = 1; i != NumArgs; ++i) {
Daniel Dunbarb7257262008-07-21 22:59:13 +0000819 Expr *Arg = TheCall->getArg(i);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000820
Eli Friedman5efba262009-12-04 00:30:06 +0000821 llvm::APSInt Result;
Eric Christopher8d0c6212010-04-17 02:26:23 +0000822 if (SemaBuiltinConstantArg(TheCall, i, Result))
823 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000824
Daniel Dunbarb7257262008-07-21 22:59:13 +0000825 // FIXME: gcc issues a warning and rewrites these to 0. These
826 // seems especially odd for the third argument since the default
827 // is 3.
Chris Lattner3b054132008-11-19 05:08:23 +0000828 if (i == 1) {
Eli Friedman5efba262009-12-04 00:30:06 +0000829 if (Result.getLimitedValue() > 1)
Chris Lattner3b054132008-11-19 05:08:23 +0000830 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000831 << "0" << "1" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000832 } else {
Eli Friedman5efba262009-12-04 00:30:06 +0000833 if (Result.getLimitedValue() > 3)
Chris Lattner3b054132008-11-19 05:08:23 +0000834 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
Chris Lattnerd545ad12009-09-23 06:06:36 +0000835 << "0" << "3" << Arg->getSourceRange();
Daniel Dunbarb7257262008-07-21 22:59:13 +0000836 }
837 }
838
Chris Lattner3b054132008-11-19 05:08:23 +0000839 return false;
Daniel Dunbarb7257262008-07-21 22:59:13 +0000840}
841
Eric Christopher8d0c6212010-04-17 02:26:23 +0000842/// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
843/// TheCall is a constant expression.
844bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
845 llvm::APSInt &Result) {
846 Expr *Arg = TheCall->getArg(ArgNum);
847 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
848 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
849
850 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
851
852 if (!Arg->isIntegerConstantExpr(Result, Context))
853 return Diag(TheCall->getLocStart(), diag::err_constant_integer_arg_type)
Eric Christopher63448c32010-04-19 18:23:02 +0000854 << FDecl->getDeclName() << Arg->getSourceRange();
Eric Christopher8d0c6212010-04-17 02:26:23 +0000855
Chris Lattnerd545ad12009-09-23 06:06:36 +0000856 return false;
857}
858
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000859/// SemaBuiltinObjectSize - Handle __builtin_object_size(void *ptr,
860/// int type). This simply type checks that type is one of the defined
861/// constants (0-3).
Eric Christopherc8791562009-12-23 03:49:37 +0000862// For compatability check 0-3, llvm only handles 0 and 2.
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000863bool Sema::SemaBuiltinObjectSize(CallExpr *TheCall) {
Eric Christopher8d0c6212010-04-17 02:26:23 +0000864 llvm::APSInt Result;
865
866 // Check constant-ness first.
867 if (SemaBuiltinConstantArg(TheCall, 1, Result))
868 return true;
869
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000870 Expr *Arg = TheCall->getArg(1);
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000871 if (Result.getSExtValue() < 0 || Result.getSExtValue() > 3) {
Chris Lattner3b054132008-11-19 05:08:23 +0000872 return Diag(TheCall->getLocStart(), diag::err_argument_invalid_range)
873 << "0" << "3" << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
Daniel Dunbarb0d34c82008-09-03 21:13:56 +0000874 }
875
876 return false;
877}
878
Eli Friedmanc97d0142009-05-03 06:04:26 +0000879/// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000880/// This checks that val is a constant 1.
881bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
882 Expr *Arg = TheCall->getArg(1);
Eric Christopher8d0c6212010-04-17 02:26:23 +0000883 llvm::APSInt Result;
Douglas Gregorc25f7662009-05-19 22:10:17 +0000884
Eric Christopher8d0c6212010-04-17 02:26:23 +0000885 // TODO: This is less than ideal. Overload this to take a value.
886 if (SemaBuiltinConstantArg(TheCall, 1, Result))
887 return true;
888
889 if (Result != 1)
Eli Friedmaneed8ad22009-05-03 04:46:36 +0000890 return Diag(TheCall->getLocStart(), diag::err_builtin_longjmp_invalid_val)
891 << SourceRange(Arg->getLocStart(), Arg->getLocEnd());
892
893 return false;
894}
895
Ted Kremeneka8890832011-02-24 23:03:04 +0000896// Handle i > 1 ? "x" : "y", recursively.
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000897bool Sema::SemaCheckStringLiteral(const Expr *E, const CallExpr *TheCall,
898 bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000899 unsigned format_idx, unsigned firstDataArg,
900 bool isPrintf) {
Ted Kremenek808829352010-09-09 03:51:39 +0000901 tryAgain:
Douglas Gregorc25f7662009-05-19 22:10:17 +0000902 if (E->isTypeDependent() || E->isValueDependent())
903 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000904
905 switch (E->getStmtClass()) {
John McCallc07a0c72011-02-17 10:25:35 +0000906 case Stmt::BinaryConditionalOperatorClass:
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000907 case Stmt::ConditionalOperatorClass: {
John McCallc07a0c72011-02-17 10:25:35 +0000908 const AbstractConditionalOperator *C = cast<AbstractConditionalOperator>(E);
Ted Kremenek02087932010-07-16 02:11:22 +0000909 return SemaCheckStringLiteral(C->getTrueExpr(), TheCall, HasVAListArg,
910 format_idx, firstDataArg, isPrintf)
John McCallc07a0c72011-02-17 10:25:35 +0000911 && SemaCheckStringLiteral(C->getFalseExpr(), TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +0000912 format_idx, firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000913 }
914
Ted Kremenek1520dae2010-09-09 03:51:42 +0000915 case Stmt::IntegerLiteralClass:
916 // Technically -Wformat-nonliteral does not warn about this case.
917 // The behavior of printf and friends in this case is implementation
918 // dependent. Ideally if the format string cannot be null then
919 // it should have a 'nonnull' attribute in the function prototype.
920 return true;
921
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000922 case Stmt::ImplicitCastExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000923 E = cast<ImplicitCastExpr>(E)->getSubExpr();
924 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000925 }
926
927 case Stmt::ParenExprClass: {
Ted Kremenek808829352010-09-09 03:51:39 +0000928 E = cast<ParenExpr>(E)->getSubExpr();
929 goto tryAgain;
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000930 }
Mike Stump11289f42009-09-09 15:08:12 +0000931
John McCallc07a0c72011-02-17 10:25:35 +0000932 case Stmt::OpaqueValueExprClass:
933 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
934 E = src;
935 goto tryAgain;
936 }
937 return false;
938
Ted Kremeneka8890832011-02-24 23:03:04 +0000939 case Stmt::PredefinedExprClass:
940 // While __func__, etc., are technically not string literals, they
941 // cannot contain format specifiers and thus are not a security
942 // liability.
943 return true;
944
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000945 case Stmt::DeclRefExprClass: {
946 const DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000947
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000948 // As an exception, do not flag errors for variables binding to
949 // const string literals.
950 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
951 bool isConstant = false;
952 QualType T = DR->getType();
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000953
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000954 if (const ArrayType *AT = Context.getAsArrayType(T)) {
955 isConstant = AT->getElementType().isConstant(Context);
Mike Stump12b8ce12009-08-04 21:02:39 +0000956 } else if (const PointerType *PT = T->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000957 isConstant = T.isConstant(Context) &&
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000958 PT->getPointeeType().isConstant(Context);
959 }
Mike Stump11289f42009-09-09 15:08:12 +0000960
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000961 if (isConstant) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000962 if (const Expr *Init = VD->getAnyInitializer())
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000963 return SemaCheckStringLiteral(Init, TheCall,
Ted Kremenek02087932010-07-16 02:11:22 +0000964 HasVAListArg, format_idx, firstDataArg,
965 isPrintf);
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000966 }
Mike Stump11289f42009-09-09 15:08:12 +0000967
Anders Carlssonb012ca92009-06-28 19:55:58 +0000968 // For vprintf* functions (i.e., HasVAListArg==true), we add a
969 // special check to see if the format string is a function parameter
970 // of the function calling the printf function. If the function
971 // has an attribute indicating it is a printf-like function, then we
972 // should suppress warnings concerning non-literals being used in a call
973 // to a vprintf function. For example:
974 //
975 // void
976 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
977 // va_list ap;
978 // va_start(ap, fmt);
979 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt".
980 // ...
981 //
982 //
983 // FIXME: We don't have full attribute support yet, so just check to see
984 // if the argument is a DeclRefExpr that references a parameter. We'll
985 // add proper support for checking the attribute later.
986 if (HasVAListArg)
987 if (isa<ParmVarDecl>(VD))
988 return true;
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000989 }
Mike Stump11289f42009-09-09 15:08:12 +0000990
Ted Kremenekdfd72c22009-03-20 21:35:28 +0000991 return false;
992 }
Ted Kremenek6dfeb552009-01-12 23:09:09 +0000993
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000994 case Stmt::CallExprClass: {
995 const CallExpr *CE = cast<CallExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +0000996 if (const ImplicitCastExpr *ICE
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +0000997 = dyn_cast<ImplicitCastExpr>(CE->getCallee())) {
998 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) {
999 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00001000 if (const FormatArgAttr *FA = FD->getAttr<FormatArgAttr>()) {
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001001 unsigned ArgIndex = FA->getFormatIdx();
1002 const Expr *Arg = CE->getArg(ArgIndex - 1);
Mike Stump11289f42009-09-09 15:08:12 +00001003
1004 return SemaCheckStringLiteral(Arg, TheCall, HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001005 format_idx, firstDataArg, isPrintf);
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001006 }
1007 }
1008 }
1009 }
Mike Stump11289f42009-09-09 15:08:12 +00001010
Anders Carlssonf0a7f3b2009-06-27 04:05:33 +00001011 return false;
1012 }
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001013 case Stmt::ObjCStringLiteralClass:
1014 case Stmt::StringLiteralClass: {
1015 const StringLiteral *StrE = NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001016
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001017 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001018 StrE = ObjCFExpr->getString();
1019 else
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001020 StrE = cast<StringLiteral>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001021
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001022 if (StrE) {
Ted Kremenek02087932010-07-16 02:11:22 +00001023 CheckFormatString(StrE, E, TheCall, HasVAListArg, format_idx,
1024 firstDataArg, isPrintf);
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001025 return true;
1026 }
Mike Stump11289f42009-09-09 15:08:12 +00001027
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001028 return false;
1029 }
Mike Stump11289f42009-09-09 15:08:12 +00001030
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001031 default:
1032 return false;
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001033 }
1034}
1035
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001036void
Mike Stump11289f42009-09-09 15:08:12 +00001037Sema::CheckNonNullArguments(const NonNullAttr *NonNull,
Nick Lewyckyd4693212011-03-25 01:44:32 +00001038 const Expr * const *ExprArgs,
1039 SourceLocation CallSiteLoc) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001040 for (NonNullAttr::args_iterator i = NonNull->args_begin(),
1041 e = NonNull->args_end();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001042 i != e; ++i) {
Nick Lewyckyd4693212011-03-25 01:44:32 +00001043 const Expr *ArgExpr = ExprArgs[*i];
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001044 if (ArgExpr->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001045 Expr::NPC_ValueDependentIsNotNull))
Nick Lewyckyd4693212011-03-25 01:44:32 +00001046 Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
Fariborz Jahaniancd1a88d2009-05-21 18:48:51 +00001047 }
1048}
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001049
Ted Kremenek02087932010-07-16 02:11:22 +00001050/// CheckPrintfScanfArguments - Check calls to printf and scanf (and similar
1051/// functions) for correct use of format strings.
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001052void
Ted Kremenek02087932010-07-16 02:11:22 +00001053Sema::CheckPrintfScanfArguments(const CallExpr *TheCall, bool HasVAListArg,
1054 unsigned format_idx, unsigned firstDataArg,
1055 bool isPrintf) {
1056
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001057 const Expr *Fn = TheCall->getCallee();
Chris Lattner08464942007-12-28 05:29:59 +00001058
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001059 // The way the format attribute works in GCC, the implicit this argument
1060 // of member functions is counted. However, it doesn't appear in our own
1061 // lists, so decrement format_idx in that case.
1062 if (isa<CXXMemberCallExpr>(TheCall)) {
Chandler Carruth1c8383d2010-11-16 08:49:43 +00001063 const CXXMethodDecl *method_decl =
1064 dyn_cast<CXXMethodDecl>(TheCall->getCalleeDecl());
1065 if (method_decl && method_decl->isInstance()) {
1066 // Catch a format attribute mistakenly referring to the object argument.
1067 if (format_idx == 0)
1068 return;
1069 --format_idx;
1070 if(firstDataArg != 0)
1071 --firstDataArg;
1072 }
Sebastian Redl6eedcc12009-11-17 18:02:24 +00001073 }
1074
Ted Kremenek02087932010-07-16 02:11:22 +00001075 // CHECK: printf/scanf-like function is called with no format string.
Chris Lattner08464942007-12-28 05:29:59 +00001076 if (format_idx >= TheCall->getNumArgs()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001077 Diag(TheCall->getRParenLoc(), diag::warn_missing_format_string)
Chris Lattnerf490e152008-11-19 05:27:50 +00001078 << Fn->getSourceRange();
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001079 return;
1080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Ted Kremenekdfd72c22009-03-20 21:35:28 +00001082 const Expr *OrigFormatExpr = TheCall->getArg(format_idx)->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00001083
Chris Lattnerb87b1b32007-08-10 20:18:51 +00001084 // CHECK: format string is not a string literal.
Mike Stump11289f42009-09-09 15:08:12 +00001085 //
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001086 // Dynamically generated format strings are difficult to
1087 // automatically vet at compile time. Requiring that format strings
1088 // are string literals: (1) permits the checking of format strings by
1089 // the compiler and thereby (2) can practically remove the source of
1090 // many format string exploits.
Ted Kremenek34f664d2008-06-16 18:00:42 +00001091
Mike Stump11289f42009-09-09 15:08:12 +00001092 // Format string can be either ObjC string (e.g. @"%d") or
Ted Kremenek34f664d2008-06-16 18:00:42 +00001093 // C string (e.g. "%d")
Mike Stump11289f42009-09-09 15:08:12 +00001094 // ObjC string uses the same format specifiers as C string, so we can use
Ted Kremenek34f664d2008-06-16 18:00:42 +00001095 // the same format string checking logic for both ObjC and C strings.
Chris Lattnere009a882009-04-29 04:49:34 +00001096 if (SemaCheckStringLiteral(OrigFormatExpr, TheCall, HasVAListArg, format_idx,
Ted Kremenek02087932010-07-16 02:11:22 +00001097 firstDataArg, isPrintf))
Chris Lattnere009a882009-04-29 04:49:34 +00001098 return; // Literal format string found, check done!
Ted Kremenek34f664d2008-06-16 18:00:42 +00001099
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001100 // If there are no arguments specified, warn with -Wformat-security, otherwise
1101 // warn only with -Wformat-nonliteral.
1102 if (TheCall->getNumArgs() == format_idx+1)
Mike Stump11289f42009-09-09 15:08:12 +00001103 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001104 diag::warn_format_nonliteral_noargs)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001105 << OrigFormatExpr->getSourceRange();
1106 else
Mike Stump11289f42009-09-09 15:08:12 +00001107 Diag(TheCall->getArg(format_idx)->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001108 diag::warn_format_nonliteral)
Chris Lattnercc5d1c22009-04-29 04:59:47 +00001109 << OrigFormatExpr->getSourceRange();
Ted Kremenek6dfeb552009-01-12 23:09:09 +00001110}
Ted Kremeneke68f1aa2007-08-14 17:39:48 +00001111
Ted Kremenekab278de2010-01-28 23:39:18 +00001112namespace {
Ted Kremenek02087932010-07-16 02:11:22 +00001113class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
1114protected:
Ted Kremenekab278de2010-01-28 23:39:18 +00001115 Sema &S;
1116 const StringLiteral *FExpr;
1117 const Expr *OrigFormatExpr;
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001118 const unsigned FirstDataArg;
Ted Kremenekab278de2010-01-28 23:39:18 +00001119 const unsigned NumDataArgs;
1120 const bool IsObjCLiteral;
1121 const char *Beg; // Start of format string.
Ted Kremenek5739de72010-01-29 01:06:55 +00001122 const bool HasVAListArg;
1123 const CallExpr *TheCall;
1124 unsigned FormatIdx;
Ted Kremenek4a49d982010-02-26 19:18:41 +00001125 llvm::BitVector CoveredArgs;
Ted Kremenekd1668192010-02-27 01:41:03 +00001126 bool usesPositionalArgs;
1127 bool atFirstArg;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001128public:
Ted Kremenek02087932010-07-16 02:11:22 +00001129 CheckFormatHandler(Sema &s, const StringLiteral *fexpr,
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001130 const Expr *origFormatExpr, unsigned firstDataArg,
Ted Kremenekab278de2010-01-28 23:39:18 +00001131 unsigned numDataArgs, bool isObjCLiteral,
Ted Kremenek5739de72010-01-29 01:06:55 +00001132 const char *beg, bool hasVAListArg,
1133 const CallExpr *theCall, unsigned formatIdx)
Ted Kremenekab278de2010-01-28 23:39:18 +00001134 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
Ted Kremenek4d745dd2010-03-25 03:59:12 +00001135 FirstDataArg(firstDataArg),
Ted Kremenek4a49d982010-02-26 19:18:41 +00001136 NumDataArgs(numDataArgs),
Ted Kremenek5739de72010-01-29 01:06:55 +00001137 IsObjCLiteral(isObjCLiteral), Beg(beg),
1138 HasVAListArg(hasVAListArg),
Ted Kremenekd1668192010-02-27 01:41:03 +00001139 TheCall(theCall), FormatIdx(formatIdx),
1140 usesPositionalArgs(false), atFirstArg(true) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001141 CoveredArgs.resize(numDataArgs);
1142 CoveredArgs.reset();
1143 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001144
Ted Kremenek019d2242010-01-29 01:50:07 +00001145 void DoneProcessing();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001146
Ted Kremenek02087932010-07-16 02:11:22 +00001147 void HandleIncompleteSpecifier(const char *startSpecifier,
1148 unsigned specifierLen);
1149
Ted Kremenekd1668192010-02-27 01:41:03 +00001150 virtual void HandleInvalidPosition(const char *startSpecifier,
1151 unsigned specifierLen,
Ted Kremenek02087932010-07-16 02:11:22 +00001152 analyze_format_string::PositionContext p);
Ted Kremenekd1668192010-02-27 01:41:03 +00001153
1154 virtual void HandleZeroPosition(const char *startPos, unsigned posLen);
1155
Ted Kremenekab278de2010-01-28 23:39:18 +00001156 void HandleNullChar(const char *nullCharacter);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001157
Ted Kremenek02087932010-07-16 02:11:22 +00001158protected:
Ted Kremenekce815422010-07-19 21:25:57 +00001159 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
1160 const char *startSpec,
1161 unsigned specifierLen,
1162 const char *csStart, unsigned csLen);
1163
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001164 SourceRange getFormatStringRange();
Ted Kremenek02087932010-07-16 02:11:22 +00001165 CharSourceRange getSpecifierRange(const char *startSpecifier,
1166 unsigned specifierLen);
Ted Kremenekab278de2010-01-28 23:39:18 +00001167 SourceLocation getLocationOfByte(const char *x);
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001168
Ted Kremenek5739de72010-01-29 01:06:55 +00001169 const Expr *getDataArg(unsigned i) const;
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001170
1171 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
1172 const analyze_format_string::ConversionSpecifier &CS,
1173 const char *startSpecifier, unsigned specifierLen,
1174 unsigned argIndex);
Ted Kremenekab278de2010-01-28 23:39:18 +00001175};
1176}
1177
Ted Kremenek02087932010-07-16 02:11:22 +00001178SourceRange CheckFormatHandler::getFormatStringRange() {
Ted Kremenekab278de2010-01-28 23:39:18 +00001179 return OrigFormatExpr->getSourceRange();
1180}
1181
Ted Kremenek02087932010-07-16 02:11:22 +00001182CharSourceRange CheckFormatHandler::
1183getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
Tom Care3f272b82010-06-21 21:21:01 +00001184 SourceLocation Start = getLocationOfByte(startSpecifier);
1185 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
1186
1187 // Advance the end SourceLocation by one due to half-open ranges.
1188 End = End.getFileLocWithOffset(1);
1189
1190 return CharSourceRange::getCharRange(Start, End);
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001191}
1192
Ted Kremenek02087932010-07-16 02:11:22 +00001193SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001194 return S.getLocationOfStringLiteralByte(FExpr, x - Beg);
Ted Kremenekab278de2010-01-28 23:39:18 +00001195}
1196
Ted Kremenek02087932010-07-16 02:11:22 +00001197void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
1198 unsigned specifierLen){
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001199 SourceLocation Loc = getLocationOfByte(startSpecifier);
1200 S.Diag(Loc, diag::warn_printf_incomplete_specifier)
Ted Kremenek02087932010-07-16 02:11:22 +00001201 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekc22f78d2010-01-29 03:16:21 +00001202}
1203
Ted Kremenekd1668192010-02-27 01:41:03 +00001204void
Ted Kremenek02087932010-07-16 02:11:22 +00001205CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
1206 analyze_format_string::PositionContext p) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001207 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001208 S.Diag(Loc, diag::warn_format_invalid_positional_specifier)
1209 << (unsigned) p << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001210}
1211
Ted Kremenek02087932010-07-16 02:11:22 +00001212void CheckFormatHandler::HandleZeroPosition(const char *startPos,
Ted Kremenekd1668192010-02-27 01:41:03 +00001213 unsigned posLen) {
1214 SourceLocation Loc = getLocationOfByte(startPos);
Ted Kremenek02087932010-07-16 02:11:22 +00001215 S.Diag(Loc, diag::warn_format_zero_positional_specifier)
1216 << getSpecifierRange(startPos, posLen);
Ted Kremenekd1668192010-02-27 01:41:03 +00001217}
1218
Ted Kremenek02087932010-07-16 02:11:22 +00001219void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
Ted Kremenek0d5b9ef2011-03-15 21:18:48 +00001220 if (!IsObjCLiteral) {
1221 // The presence of a null character is likely an error.
1222 S.Diag(getLocationOfByte(nullCharacter),
1223 diag::warn_printf_format_string_contains_null_char)
1224 << getFormatStringRange();
1225 }
Ted Kremenek02087932010-07-16 02:11:22 +00001226}
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001227
Ted Kremenek02087932010-07-16 02:11:22 +00001228const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
1229 return TheCall->getArg(FirstDataArg + i);
1230}
1231
1232void CheckFormatHandler::DoneProcessing() {
1233 // Does the number of data arguments exceed the number of
1234 // format conversions in the format string?
1235 if (!HasVAListArg) {
1236 // Find any arguments that weren't covered.
1237 CoveredArgs.flip();
1238 signed notCoveredArg = CoveredArgs.find_first();
1239 if (notCoveredArg >= 0) {
1240 assert((unsigned)notCoveredArg < NumDataArgs);
1241 S.Diag(getDataArg((unsigned) notCoveredArg)->getLocStart(),
1242 diag::warn_printf_data_arg_not_used)
1243 << getFormatStringRange();
1244 }
1245 }
1246}
1247
Ted Kremenekce815422010-07-19 21:25:57 +00001248bool
1249CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
1250 SourceLocation Loc,
1251 const char *startSpec,
1252 unsigned specifierLen,
1253 const char *csStart,
1254 unsigned csLen) {
1255
1256 bool keepGoing = true;
1257 if (argIndex < NumDataArgs) {
1258 // Consider the argument coverered, even though the specifier doesn't
1259 // make sense.
1260 CoveredArgs.set(argIndex);
1261 }
1262 else {
1263 // If argIndex exceeds the number of data arguments we
1264 // don't issue a warning because that is just a cascade of warnings (and
1265 // they may have intended '%%' anyway). We don't want to continue processing
1266 // the format string after this point, however, as we will like just get
1267 // gibberish when trying to match arguments.
1268 keepGoing = false;
1269 }
1270
1271 S.Diag(Loc, diag::warn_format_invalid_conversion)
1272 << llvm::StringRef(csStart, csLen)
1273 << getSpecifierRange(startSpec, specifierLen);
1274
1275 return keepGoing;
1276}
1277
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001278bool
1279CheckFormatHandler::CheckNumArgs(
1280 const analyze_format_string::FormatSpecifier &FS,
1281 const analyze_format_string::ConversionSpecifier &CS,
1282 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
1283
1284 if (argIndex >= NumDataArgs) {
1285 if (FS.usesPositionalArg()) {
1286 S.Diag(getLocationOfByte(CS.getStart()),
1287 diag::warn_printf_positional_arg_exceeds_data_args)
1288 << (argIndex+1) << NumDataArgs
1289 << getSpecifierRange(startSpecifier, specifierLen);
1290 }
1291 else {
1292 S.Diag(getLocationOfByte(CS.getStart()),
1293 diag::warn_printf_insufficient_data_args)
1294 << getSpecifierRange(startSpecifier, specifierLen);
1295 }
1296
1297 return false;
1298 }
1299 return true;
1300}
1301
Ted Kremenek02087932010-07-16 02:11:22 +00001302//===--- CHECK: Printf format string checking ------------------------------===//
1303
1304namespace {
1305class CheckPrintfHandler : public CheckFormatHandler {
1306public:
1307 CheckPrintfHandler(Sema &s, const StringLiteral *fexpr,
1308 const Expr *origFormatExpr, unsigned firstDataArg,
1309 unsigned numDataArgs, bool isObjCLiteral,
1310 const char *beg, bool hasVAListArg,
1311 const CallExpr *theCall, unsigned formatIdx)
1312 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1313 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1314 theCall, formatIdx) {}
1315
1316
1317 bool HandleInvalidPrintfConversionSpecifier(
1318 const analyze_printf::PrintfSpecifier &FS,
1319 const char *startSpecifier,
1320 unsigned specifierLen);
1321
1322 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
1323 const char *startSpecifier,
1324 unsigned specifierLen);
1325
1326 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
1327 const char *startSpecifier, unsigned specifierLen);
1328 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
1329 const analyze_printf::OptionalAmount &Amt,
1330 unsigned type,
1331 const char *startSpecifier, unsigned specifierLen);
1332 void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
1333 const analyze_printf::OptionalFlag &flag,
1334 const char *startSpecifier, unsigned specifierLen);
1335 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
1336 const analyze_printf::OptionalFlag &ignoredFlag,
1337 const analyze_printf::OptionalFlag &flag,
1338 const char *startSpecifier, unsigned specifierLen);
1339};
1340}
1341
1342bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
1343 const analyze_printf::PrintfSpecifier &FS,
1344 const char *startSpecifier,
1345 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001346 const analyze_printf::PrintfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001347 FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001348
Ted Kremenekce815422010-07-19 21:25:57 +00001349 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1350 getLocationOfByte(CS.getStart()),
1351 startSpecifier, specifierLen,
1352 CS.getStart(), CS.getLength());
Ted Kremenek94af5752010-01-29 02:40:24 +00001353}
1354
Ted Kremenek02087932010-07-16 02:11:22 +00001355bool CheckPrintfHandler::HandleAmount(
1356 const analyze_format_string::OptionalAmount &Amt,
1357 unsigned k, const char *startSpecifier,
1358 unsigned specifierLen) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001359
1360 if (Amt.hasDataArgument()) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001361 if (!HasVAListArg) {
Ted Kremenek4a49d982010-02-26 19:18:41 +00001362 unsigned argIndex = Amt.getArgIndex();
1363 if (argIndex >= NumDataArgs) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001364 S.Diag(getLocationOfByte(Amt.getStart()),
1365 diag::warn_printf_asterisk_missing_arg)
Ted Kremenek02087932010-07-16 02:11:22 +00001366 << k << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenek5739de72010-01-29 01:06:55 +00001367 // Don't do any more checking. We will just emit
1368 // spurious errors.
1369 return false;
1370 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001371
Ted Kremenek5739de72010-01-29 01:06:55 +00001372 // Type check the data argument. It should be an 'int'.
Ted Kremenek605b0112010-01-29 23:32:22 +00001373 // Although not in conformance with C99, we also allow the argument to be
1374 // an 'unsigned int' as that is a reasonably safe case. GCC also
1375 // doesn't emit a warning for that case.
Ted Kremenek4a49d982010-02-26 19:18:41 +00001376 CoveredArgs.set(argIndex);
1377 const Expr *Arg = getDataArg(argIndex);
Ted Kremenek5739de72010-01-29 01:06:55 +00001378 QualType T = Arg->getType();
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001379
1380 const analyze_printf::ArgTypeResult &ATR = Amt.getArgType(S.Context);
1381 assert(ATR.isValid());
1382
1383 if (!ATR.matchesType(S.Context, T)) {
Ted Kremenekd1668192010-02-27 01:41:03 +00001384 S.Diag(getLocationOfByte(Amt.getStart()),
1385 diag::warn_printf_asterisk_wrong_type)
1386 << k
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001387 << ATR.getRepresentativeType(S.Context) << T
Ted Kremenek02087932010-07-16 02:11:22 +00001388 << getSpecifierRange(startSpecifier, specifierLen)
Ted Kremenekc3bdff72010-01-30 00:49:51 +00001389 << Arg->getSourceRange();
Ted Kremenek5739de72010-01-29 01:06:55 +00001390 // Don't do any more checking. We will just emit
1391 // spurious errors.
1392 return false;
1393 }
1394 }
1395 }
1396 return true;
1397}
Ted Kremenek5739de72010-01-29 01:06:55 +00001398
Tom Careb49ec692010-06-17 19:00:27 +00001399void CheckPrintfHandler::HandleInvalidAmount(
Ted Kremenek02087932010-07-16 02:11:22 +00001400 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001401 const analyze_printf::OptionalAmount &Amt,
1402 unsigned type,
1403 const char *startSpecifier,
1404 unsigned specifierLen) {
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001405 const analyze_printf::PrintfConversionSpecifier &CS =
1406 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001407 switch (Amt.getHowSpecified()) {
1408 case analyze_printf::OptionalAmount::Constant:
1409 S.Diag(getLocationOfByte(Amt.getStart()),
1410 diag::warn_printf_nonsensical_optional_amount)
1411 << type
1412 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001413 << getSpecifierRange(startSpecifier, specifierLen)
1414 << FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001415 Amt.getConstantLength()));
1416 break;
1417
1418 default:
1419 S.Diag(getLocationOfByte(Amt.getStart()),
1420 diag::warn_printf_nonsensical_optional_amount)
1421 << type
1422 << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001423 << getSpecifierRange(startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001424 break;
1425 }
1426}
1427
Ted Kremenek02087932010-07-16 02:11:22 +00001428void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001429 const analyze_printf::OptionalFlag &flag,
1430 const char *startSpecifier,
1431 unsigned specifierLen) {
1432 // Warn about pointless flag with a fixit removal.
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001433 const analyze_printf::PrintfConversionSpecifier &CS =
1434 FS.getConversionSpecifier();
Tom Careb49ec692010-06-17 19:00:27 +00001435 S.Diag(getLocationOfByte(flag.getPosition()),
1436 diag::warn_printf_nonsensical_flag)
1437 << flag.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001438 << getSpecifierRange(startSpecifier, specifierLen)
1439 << FixItHint::CreateRemoval(getSpecifierRange(flag.getPosition(), 1));
Tom Careb49ec692010-06-17 19:00:27 +00001440}
1441
1442void CheckPrintfHandler::HandleIgnoredFlag(
Ted Kremenek02087932010-07-16 02:11:22 +00001443 const analyze_printf::PrintfSpecifier &FS,
Tom Careb49ec692010-06-17 19:00:27 +00001444 const analyze_printf::OptionalFlag &ignoredFlag,
1445 const analyze_printf::OptionalFlag &flag,
1446 const char *startSpecifier,
1447 unsigned specifierLen) {
1448 // Warn about ignored flag with a fixit removal.
1449 S.Diag(getLocationOfByte(ignoredFlag.getPosition()),
1450 diag::warn_printf_ignored_flag)
1451 << ignoredFlag.toString() << flag.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001452 << getSpecifierRange(startSpecifier, specifierLen)
1453 << FixItHint::CreateRemoval(getSpecifierRange(
Tom Careb49ec692010-06-17 19:00:27 +00001454 ignoredFlag.getPosition(), 1));
1455}
1456
Ted Kremenekab278de2010-01-28 23:39:18 +00001457bool
Ted Kremenek02087932010-07-16 02:11:22 +00001458CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
Ted Kremenekd31b2632010-02-11 09:27:41 +00001459 &FS,
Ted Kremenekab278de2010-01-28 23:39:18 +00001460 const char *startSpecifier,
1461 unsigned specifierLen) {
1462
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001463 using namespace analyze_format_string;
Ted Kremenekd1668192010-02-27 01:41:03 +00001464 using namespace analyze_printf;
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001465 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenekab278de2010-01-28 23:39:18 +00001466
Ted Kremenek6cd69422010-07-19 22:01:06 +00001467 if (FS.consumesDataArgument()) {
1468 if (atFirstArg) {
1469 atFirstArg = false;
1470 usesPositionalArgs = FS.usesPositionalArg();
1471 }
1472 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1473 // Cannot mix-and-match positional and non-positional arguments.
1474 S.Diag(getLocationOfByte(CS.getStart()),
1475 diag::warn_format_mix_positional_nonpositional_args)
1476 << getSpecifierRange(startSpecifier, specifierLen);
1477 return false;
1478 }
Ted Kremenek5739de72010-01-29 01:06:55 +00001479 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001480
Ted Kremenekd1668192010-02-27 01:41:03 +00001481 // First check if the field width, precision, and conversion specifier
1482 // have matching data arguments.
1483 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
1484 startSpecifier, specifierLen)) {
1485 return false;
1486 }
1487
1488 if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
1489 startSpecifier, specifierLen)) {
Ted Kremenek5739de72010-01-29 01:06:55 +00001490 return false;
1491 }
1492
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001493 if (!CS.consumesDataArgument()) {
1494 // FIXME: Technically specifying a precision or field width here
1495 // makes no sense. Worth issuing a warning at some point.
Ted Kremenekfb45d352010-02-10 02:16:30 +00001496 return true;
Ted Kremenek8d9842d2010-01-29 20:55:36 +00001497 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001498
Ted Kremenek4a49d982010-02-26 19:18:41 +00001499 // Consume the argument.
1500 unsigned argIndex = FS.getArgIndex();
Ted Kremenek09597b42010-02-27 08:34:51 +00001501 if (argIndex < NumDataArgs) {
1502 // The check to see if the argIndex is valid will come later.
1503 // We set the bit here because we may exit early from this
1504 // function if we encounter some other error.
1505 CoveredArgs.set(argIndex);
1506 }
Ted Kremenek4a49d982010-02-26 19:18:41 +00001507
1508 // Check for using an Objective-C specific conversion specifier
1509 // in a non-ObjC literal.
1510 if (!IsObjCLiteral && CS.isObjCArg()) {
Ted Kremenek02087932010-07-16 02:11:22 +00001511 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
1512 specifierLen);
Ted Kremenek4a49d982010-02-26 19:18:41 +00001513 }
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001514
Tom Careb49ec692010-06-17 19:00:27 +00001515 // Check for invalid use of field width
1516 if (!FS.hasValidFieldWidth()) {
Tom Care3f272b82010-06-21 21:21:01 +00001517 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
Tom Careb49ec692010-06-17 19:00:27 +00001518 startSpecifier, specifierLen);
1519 }
1520
1521 // Check for invalid use of precision
1522 if (!FS.hasValidPrecision()) {
1523 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
1524 startSpecifier, specifierLen);
1525 }
1526
1527 // Check each flag does not conflict with any other component.
Ted Kremenekbf4832c2011-01-08 05:28:46 +00001528 if (!FS.hasValidThousandsGroupingPrefix())
1529 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001530 if (!FS.hasValidLeadingZeros())
1531 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
1532 if (!FS.hasValidPlusPrefix())
1533 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
Tom Care3f272b82010-06-21 21:21:01 +00001534 if (!FS.hasValidSpacePrefix())
1535 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001536 if (!FS.hasValidAlternativeForm())
1537 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
1538 if (!FS.hasValidLeftJustified())
1539 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
1540
1541 // Check that flags are not ignored by another flag
Tom Care3f272b82010-06-21 21:21:01 +00001542 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
1543 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
1544 startSpecifier, specifierLen);
Tom Careb49ec692010-06-17 19:00:27 +00001545 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
1546 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
1547 startSpecifier, specifierLen);
1548
1549 // Check the length modifier is valid with the given conversion specifier.
1550 const LengthModifier &LM = FS.getLengthModifier();
1551 if (!FS.hasValidLengthModifier())
1552 S.Diag(getLocationOfByte(LM.getStart()),
Ted Kremenekb65a9d52010-07-20 20:03:43 +00001553 diag::warn_format_nonsensical_length)
Tom Careb49ec692010-06-17 19:00:27 +00001554 << LM.toString() << CS.toString()
Ted Kremenek02087932010-07-16 02:11:22 +00001555 << getSpecifierRange(startSpecifier, specifierLen)
1556 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
Tom Careb49ec692010-06-17 19:00:27 +00001557 LM.getLength()));
1558
1559 // Are we using '%n'?
Ted Kremenek516ef222010-07-20 20:04:10 +00001560 if (CS.getKind() == ConversionSpecifier::nArg) {
Tom Careb49ec692010-06-17 19:00:27 +00001561 // Issue a warning about this being a possible security issue.
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001562 S.Diag(getLocationOfByte(CS.getStart()), diag::warn_printf_write_back)
Ted Kremenek02087932010-07-16 02:11:22 +00001563 << getSpecifierRange(startSpecifier, specifierLen);
Ted Kremenekd5fd0fa2010-01-29 01:35:25 +00001564 // Continue checking the other format specifiers.
1565 return true;
1566 }
Ted Kremenekd31b2632010-02-11 09:27:41 +00001567
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001568 // The remaining checks depend on the data arguments.
1569 if (HasVAListArg)
1570 return true;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001571
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001572 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek9fcd8302010-01-29 01:43:31 +00001573 return false;
Ted Kremenekc8b188d2010-02-16 01:46:59 +00001574
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001575 // Now type check the data expression that matches the
1576 // format specifier.
1577 const Expr *Ex = getDataArg(argIndex);
1578 const analyze_printf::ArgTypeResult &ATR = FS.getArgType(S.Context);
1579 if (ATR.isValid() && !ATR.matchesType(S.Context, Ex->getType())) {
1580 // Check if we didn't match because of an implicit cast from a 'char'
1581 // or 'short' to an 'int'. This is done because printf is a varargs
1582 // function.
1583 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Ex))
Ted Kremenek12a37de2010-10-21 04:00:58 +00001584 if (ICE->getType() == S.Context.IntTy) {
1585 // All further checking is done on the subexpression.
1586 Ex = ICE->getSubExpr();
1587 if (ATR.matchesType(S.Context, Ex->getType()))
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001588 return true;
Ted Kremenek12a37de2010-10-21 04:00:58 +00001589 }
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001590
1591 // We may be able to offer a FixItHint if it is a supported type.
1592 PrintfSpecifier fixedFS = FS;
1593 bool success = fixedFS.fixType(Ex->getType());
1594
1595 if (success) {
1596 // Get the fix string from the fixed format specifier
1597 llvm::SmallString<128> buf;
1598 llvm::raw_svector_ostream os(buf);
1599 fixedFS.toString(os);
1600
Ted Kremenek5f0c0662010-08-24 22:24:51 +00001601 // FIXME: getRepresentativeType() perhaps should return a string
1602 // instead of a QualType to better handle when the representative
1603 // type is 'wint_t' (which is defined in the system headers).
Michael J. Spencer2c35bc12010-07-27 04:46:02 +00001604 S.Diag(getLocationOfByte(CS.getStart()),
1605 diag::warn_printf_conversion_argument_type_mismatch)
1606 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1607 << getSpecifierRange(startSpecifier, specifierLen)
1608 << Ex->getSourceRange()
1609 << FixItHint::CreateReplacement(
1610 getSpecifierRange(startSpecifier, specifierLen),
1611 os.str());
1612 }
1613 else {
1614 S.Diag(getLocationOfByte(CS.getStart()),
1615 diag::warn_printf_conversion_argument_type_mismatch)
1616 << ATR.getRepresentativeType(S.Context) << Ex->getType()
1617 << getSpecifierRange(startSpecifier, specifierLen)
1618 << Ex->getSourceRange();
1619 }
1620 }
1621
Ted Kremenekab278de2010-01-28 23:39:18 +00001622 return true;
1623}
1624
Ted Kremenek02087932010-07-16 02:11:22 +00001625//===--- CHECK: Scanf format string checking ------------------------------===//
1626
1627namespace {
1628class CheckScanfHandler : public CheckFormatHandler {
1629public:
1630 CheckScanfHandler(Sema &s, const StringLiteral *fexpr,
1631 const Expr *origFormatExpr, unsigned firstDataArg,
1632 unsigned numDataArgs, bool isObjCLiteral,
1633 const char *beg, bool hasVAListArg,
1634 const CallExpr *theCall, unsigned formatIdx)
1635 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
1636 numDataArgs, isObjCLiteral, beg, hasVAListArg,
1637 theCall, formatIdx) {}
1638
1639 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
1640 const char *startSpecifier,
1641 unsigned specifierLen);
Ted Kremenekce815422010-07-19 21:25:57 +00001642
1643 bool HandleInvalidScanfConversionSpecifier(
1644 const analyze_scanf::ScanfSpecifier &FS,
1645 const char *startSpecifier,
1646 unsigned specifierLen);
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001647
1648 void HandleIncompleteScanList(const char *start, const char *end);
Ted Kremenek02087932010-07-16 02:11:22 +00001649};
Ted Kremenek019d2242010-01-29 01:50:07 +00001650}
Ted Kremenekab278de2010-01-28 23:39:18 +00001651
Ted Kremenekd7b31cc2010-07-16 18:28:03 +00001652void CheckScanfHandler::HandleIncompleteScanList(const char *start,
1653 const char *end) {
1654 S.Diag(getLocationOfByte(end), diag::warn_scanf_scanlist_incomplete)
1655 << getSpecifierRange(start, end - start);
1656}
1657
Ted Kremenekce815422010-07-19 21:25:57 +00001658bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
1659 const analyze_scanf::ScanfSpecifier &FS,
1660 const char *startSpecifier,
1661 unsigned specifierLen) {
1662
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001663 const analyze_scanf::ScanfConversionSpecifier &CS =
Ted Kremenekce815422010-07-19 21:25:57 +00001664 FS.getConversionSpecifier();
1665
1666 return HandleInvalidConversionSpecifier(FS.getArgIndex(),
1667 getLocationOfByte(CS.getStart()),
1668 startSpecifier, specifierLen,
1669 CS.getStart(), CS.getLength());
1670}
1671
Ted Kremenek02087932010-07-16 02:11:22 +00001672bool CheckScanfHandler::HandleScanfSpecifier(
1673 const analyze_scanf::ScanfSpecifier &FS,
1674 const char *startSpecifier,
1675 unsigned specifierLen) {
1676
1677 using namespace analyze_scanf;
1678 using namespace analyze_format_string;
1679
Ted Kremenekf03e6d852010-07-20 20:04:27 +00001680 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
Ted Kremenek02087932010-07-16 02:11:22 +00001681
Ted Kremenek6cd69422010-07-19 22:01:06 +00001682 // Handle case where '%' and '*' don't consume an argument. These shouldn't
1683 // be used to decide if we are using positional arguments consistently.
1684 if (FS.consumesDataArgument()) {
1685 if (atFirstArg) {
1686 atFirstArg = false;
1687 usesPositionalArgs = FS.usesPositionalArg();
1688 }
1689 else if (usesPositionalArgs != FS.usesPositionalArg()) {
1690 // Cannot mix-and-match positional and non-positional arguments.
1691 S.Diag(getLocationOfByte(CS.getStart()),
1692 diag::warn_format_mix_positional_nonpositional_args)
1693 << getSpecifierRange(startSpecifier, specifierLen);
1694 return false;
1695 }
Ted Kremenek02087932010-07-16 02:11:22 +00001696 }
1697
1698 // Check if the field with is non-zero.
1699 const OptionalAmount &Amt = FS.getFieldWidth();
1700 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
1701 if (Amt.getConstantAmount() == 0) {
1702 const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
1703 Amt.getConstantLength());
1704 S.Diag(getLocationOfByte(Amt.getStart()),
1705 diag::warn_scanf_nonzero_width)
1706 << R << FixItHint::CreateRemoval(R);
1707 }
1708 }
1709
1710 if (!FS.consumesDataArgument()) {
1711 // FIXME: Technically specifying a precision or field width here
1712 // makes no sense. Worth issuing a warning at some point.
1713 return true;
1714 }
1715
1716 // Consume the argument.
1717 unsigned argIndex = FS.getArgIndex();
1718 if (argIndex < NumDataArgs) {
1719 // The check to see if the argIndex is valid will come later.
1720 // We set the bit here because we may exit early from this
1721 // function if we encounter some other error.
1722 CoveredArgs.set(argIndex);
1723 }
1724
Ted Kremenek4407ea42010-07-20 20:04:47 +00001725 // Check the length modifier is valid with the given conversion specifier.
1726 const LengthModifier &LM = FS.getLengthModifier();
1727 if (!FS.hasValidLengthModifier()) {
1728 S.Diag(getLocationOfByte(LM.getStart()),
1729 diag::warn_format_nonsensical_length)
1730 << LM.toString() << CS.toString()
1731 << getSpecifierRange(startSpecifier, specifierLen)
1732 << FixItHint::CreateRemoval(getSpecifierRange(LM.getStart(),
1733 LM.getLength()));
1734 }
1735
Ted Kremenek02087932010-07-16 02:11:22 +00001736 // The remaining checks depend on the data arguments.
1737 if (HasVAListArg)
1738 return true;
1739
Ted Kremenek6adb7e32010-07-26 19:45:42 +00001740 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
Ted Kremenek02087932010-07-16 02:11:22 +00001741 return false;
Ted Kremenek02087932010-07-16 02:11:22 +00001742
1743 // FIXME: Check that the argument type matches the format specifier.
1744
1745 return true;
1746}
1747
1748void Sema::CheckFormatString(const StringLiteral *FExpr,
Ted Kremenekfb45d352010-02-10 02:16:30 +00001749 const Expr *OrigFormatExpr,
1750 const CallExpr *TheCall, bool HasVAListArg,
Ted Kremenek02087932010-07-16 02:11:22 +00001751 unsigned format_idx, unsigned firstDataArg,
1752 bool isPrintf) {
1753
Ted Kremenekab278de2010-01-28 23:39:18 +00001754 // CHECK: is the format string a wide literal?
1755 if (FExpr->isWide()) {
1756 Diag(FExpr->getLocStart(),
Ted Kremenek02087932010-07-16 02:11:22 +00001757 diag::warn_format_string_is_wide_literal)
Ted Kremenekab278de2010-01-28 23:39:18 +00001758 << OrigFormatExpr->getSourceRange();
1759 return;
1760 }
Ted Kremenek02087932010-07-16 02:11:22 +00001761
Ted Kremenekab278de2010-01-28 23:39:18 +00001762 // Str - The format string. NOTE: this is NOT null-terminated!
Benjamin Kramer35b077e2010-08-17 12:54:38 +00001763 llvm::StringRef StrRef = FExpr->getString();
1764 const char *Str = StrRef.data();
1765 unsigned StrLen = StrRef.size();
Ted Kremenek02087932010-07-16 02:11:22 +00001766
Ted Kremenekab278de2010-01-28 23:39:18 +00001767 // CHECK: empty format string?
Ted Kremenekab278de2010-01-28 23:39:18 +00001768 if (StrLen == 0) {
Ted Kremenek02087932010-07-16 02:11:22 +00001769 Diag(FExpr->getLocStart(), diag::warn_empty_format_string)
Ted Kremenekab278de2010-01-28 23:39:18 +00001770 << OrigFormatExpr->getSourceRange();
1771 return;
1772 }
Ted Kremenek02087932010-07-16 02:11:22 +00001773
1774 if (isPrintf) {
1775 CheckPrintfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1776 TheCall->getNumArgs() - firstDataArg,
1777 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1778 HasVAListArg, TheCall, format_idx);
1779
1780 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen))
1781 H.DoneProcessing();
1782 }
1783 else {
1784 CheckScanfHandler H(*this, FExpr, OrigFormatExpr, firstDataArg,
1785 TheCall->getNumArgs() - firstDataArg,
1786 isa<ObjCStringLiteral>(OrigFormatExpr), Str,
1787 HasVAListArg, TheCall, format_idx);
1788
1789 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen))
1790 H.DoneProcessing();
1791 }
Ted Kremenekc70ee862010-01-28 01:18:22 +00001792}
1793
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001794//===--- CHECK: Return Address of Stack Variable --------------------------===//
1795
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001796static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
1797static Expr *EvalAddr(Expr* E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001798
1799/// CheckReturnStackAddr - Check if a return statement returns the address
1800/// of a stack variable.
1801void
1802Sema::CheckReturnStackAddr(Expr *RetValExp, QualType lhsType,
1803 SourceLocation ReturnLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001804
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001805 Expr *stackE = 0;
1806 llvm::SmallVector<DeclRefExpr *, 8> refVars;
1807
1808 // Perform checking for returned stack addresses, local blocks,
1809 // label addresses or references to temporaries.
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001810 if (lhsType->isPointerType() || lhsType->isBlockPointerType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001811 stackE = EvalAddr(RetValExp, refVars);
Mike Stump12b8ce12009-08-04 21:02:39 +00001812 } else if (lhsType->isReferenceType()) {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001813 stackE = EvalVal(RetValExp, refVars);
1814 }
1815
1816 if (stackE == 0)
1817 return; // Nothing suspicious was found.
1818
1819 SourceLocation diagLoc;
1820 SourceRange diagRange;
1821 if (refVars.empty()) {
1822 diagLoc = stackE->getLocStart();
1823 diagRange = stackE->getSourceRange();
1824 } else {
1825 // We followed through a reference variable. 'stackE' contains the
1826 // problematic expression but we will warn at the return statement pointing
1827 // at the reference variable. We will later display the "trail" of
1828 // reference variables using notes.
1829 diagLoc = refVars[0]->getLocStart();
1830 diagRange = refVars[0]->getSourceRange();
1831 }
1832
1833 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) { //address of local var.
1834 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_stack_ref
1835 : diag::warn_ret_stack_addr)
1836 << DR->getDecl()->getDeclName() << diagRange;
1837 } else if (isa<BlockExpr>(stackE)) { // local block.
1838 Diag(diagLoc, diag::err_ret_local_block) << diagRange;
1839 } else if (isa<AddrLabelExpr>(stackE)) { // address of label.
1840 Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
1841 } else { // local temporary.
1842 Diag(diagLoc, lhsType->isReferenceType() ? diag::warn_ret_local_temp_ref
1843 : diag::warn_ret_local_temp_addr)
1844 << diagRange;
1845 }
1846
1847 // Display the "trail" of reference variables that we followed until we
1848 // found the problematic expression using notes.
1849 for (unsigned i = 0, e = refVars.size(); i != e; ++i) {
1850 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
1851 // If this var binds to another reference var, show the range of the next
1852 // var, otherwise the var binds to the problematic expression, in which case
1853 // show the range of the expression.
1854 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
1855 : stackE->getSourceRange();
1856 Diag(VD->getLocation(), diag::note_ref_var_local_bind)
1857 << VD->getDeclName() << range;
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001858 }
1859}
1860
1861/// EvalAddr - EvalAddr and EvalVal are mutually recursive functions that
1862/// check if the expression in a return statement evaluates to an address
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001863/// to a location on the stack, a local block, an address of a label, or a
1864/// reference to local temporary. The recursion is used to traverse the
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001865/// AST of the return expression, with recursion backtracking when we
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001866/// encounter a subexpression that (1) clearly does not lead to one of the
1867/// above problematic expressions (2) is something we cannot determine leads to
1868/// a problematic expression based on such local checking.
1869///
1870/// Both EvalAddr and EvalVal follow through reference variables to evaluate
1871/// the expression that they point to. Such variables are added to the
1872/// 'refVars' vector so that we know what the reference variable "trail" was.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001873///
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00001874/// EvalAddr processes expressions that are pointers that are used as
1875/// references (and not L-values). EvalVal handles all other values.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001876/// At the base case of the recursion is a check for the above problematic
1877/// expressions.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001878///
1879/// This implementation handles:
1880///
1881/// * pointer-to-pointer casts
1882/// * implicit conversions from array references to pointers
1883/// * taking the address of fields
1884/// * arbitrary interplay between "&" and "*" operators
1885/// * pointer arithmetic from an address of a stack variable
1886/// * taking the address of an array element where the array is on the stack
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001887static Expr *EvalAddr(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
1888 if (E->isTypeDependent())
1889 return NULL;
1890
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001891 // We should only be called for evaluating pointer expressions.
David Chisnall9f57c292009-08-17 16:35:33 +00001892 assert((E->getType()->isAnyPointerType() ||
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001893 E->getType()->isBlockPointerType() ||
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001894 E->getType()->isObjCQualifiedIdType()) &&
Chris Lattner934edb22007-12-28 05:31:15 +00001895 "EvalAddr only works on pointers");
Mike Stump11289f42009-09-09 15:08:12 +00001896
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001897 // Our "symbolic interpreter" is just a dispatch off the currently
1898 // viewed AST node. We then recursively traverse the AST by calling
1899 // EvalAddr and EvalVal appropriately.
1900 switch (E->getStmtClass()) {
Chris Lattner934edb22007-12-28 05:31:15 +00001901 case Stmt::ParenExprClass:
1902 // Ignore parentheses.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001903 return EvalAddr(cast<ParenExpr>(E)->getSubExpr(), refVars);
1904
1905 case Stmt::DeclRefExprClass: {
1906 DeclRefExpr *DR = cast<DeclRefExpr>(E);
1907
1908 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
1909 // If this is a reference variable, follow through to the expression that
1910 // it points to.
1911 if (V->hasLocalStorage() &&
1912 V->getType()->isReferenceType() && V->hasInit()) {
1913 // Add the reference variable to the "trail".
1914 refVars.push_back(DR);
1915 return EvalAddr(V->getInit(), refVars);
1916 }
1917
1918 return NULL;
1919 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001920
Chris Lattner934edb22007-12-28 05:31:15 +00001921 case Stmt::UnaryOperatorClass: {
1922 // The only unary operator that make sense to handle here
1923 // is AddrOf. All others don't make sense as pointers.
1924 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001925
John McCalle3027922010-08-25 11:45:40 +00001926 if (U->getOpcode() == UO_AddrOf)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001927 return EvalVal(U->getSubExpr(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001928 else
Ted Kremenekcff94fa2007-08-17 16:46:58 +00001929 return NULL;
1930 }
Mike Stump11289f42009-09-09 15:08:12 +00001931
Chris Lattner934edb22007-12-28 05:31:15 +00001932 case Stmt::BinaryOperatorClass: {
1933 // Handle pointer arithmetic. All other binary operators are not valid
1934 // in this context.
1935 BinaryOperator *B = cast<BinaryOperator>(E);
John McCalle3027922010-08-25 11:45:40 +00001936 BinaryOperatorKind op = B->getOpcode();
Mike Stump11289f42009-09-09 15:08:12 +00001937
John McCalle3027922010-08-25 11:45:40 +00001938 if (op != BO_Add && op != BO_Sub)
Chris Lattner934edb22007-12-28 05:31:15 +00001939 return NULL;
Mike Stump11289f42009-09-09 15:08:12 +00001940
Chris Lattner934edb22007-12-28 05:31:15 +00001941 Expr *Base = B->getLHS();
1942
1943 // Determine which argument is the real pointer base. It could be
1944 // the RHS argument instead of the LHS.
1945 if (!Base->getType()->isPointerType()) Base = B->getRHS();
Mike Stump11289f42009-09-09 15:08:12 +00001946
Chris Lattner934edb22007-12-28 05:31:15 +00001947 assert (Base->getType()->isPointerType());
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001948 return EvalAddr(Base, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001949 }
Steve Naroff2752a172008-09-10 19:17:48 +00001950
Chris Lattner934edb22007-12-28 05:31:15 +00001951 // For conditional operators we need to see if either the LHS or RHS are
1952 // valid DeclRefExpr*s. If one of them is valid, we return it.
1953 case Stmt::ConditionalOperatorClass: {
1954 ConditionalOperator *C = cast<ConditionalOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00001955
Chris Lattner934edb22007-12-28 05:31:15 +00001956 // Handle the GNU extension for missing LHS.
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001957 if (Expr *lhsExpr = C->getLHS()) {
1958 // In C++, we can have a throw-expression, which has 'void' type.
1959 if (!lhsExpr->getType()->isVoidType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001960 if (Expr* LHS = EvalAddr(lhsExpr, refVars))
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001961 return LHS;
1962 }
Chris Lattner934edb22007-12-28 05:31:15 +00001963
Douglas Gregor270b2ef2010-10-21 16:21:08 +00001964 // In C++, we can have a throw-expression, which has 'void' type.
1965 if (C->getRHS()->getType()->isVoidType())
1966 return NULL;
1967
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001968 return EvalAddr(C->getRHS(), refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001969 }
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001970
1971 case Stmt::BlockExprClass:
John McCallc63de662011-02-02 13:00:07 +00001972 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001973 return E; // local block.
1974 return NULL;
1975
1976 case Stmt::AddrLabelExprClass:
1977 return E; // address of label.
Mike Stump11289f42009-09-09 15:08:12 +00001978
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001979 // For casts, we need to handle conversions from arrays to
1980 // pointer values, and pointer-to-pointer conversions.
Douglas Gregore200adc2008-10-27 19:41:14 +00001981 case Stmt::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00001982 case Stmt::CStyleCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00001983 case Stmt::CXXFunctionalCastExprClass: {
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00001984 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001985 QualType T = SubExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001986
Steve Naroff8de9c3a2008-09-05 22:11:13 +00001987 if (SubExpr->getType()->isPointerType() ||
1988 SubExpr->getType()->isBlockPointerType() ||
1989 SubExpr->getType()->isObjCQualifiedIdType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001990 return EvalAddr(SubExpr, refVars);
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001991 else if (T->isArrayType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00001992 return EvalVal(SubExpr, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00001993 else
Ted Kremenekc3b4c522008-08-07 00:49:01 +00001994 return 0;
Chris Lattner934edb22007-12-28 05:31:15 +00001995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattner934edb22007-12-28 05:31:15 +00001997 // C++ casts. For dynamic casts, static casts, and const casts, we
1998 // are always converting from a pointer-to-pointer, so we just blow
Douglas Gregore200adc2008-10-27 19:41:14 +00001999 // through the cast. In the case the dynamic cast doesn't fail (and
2000 // return NULL), we take the conservative route and report cases
Chris Lattner934edb22007-12-28 05:31:15 +00002001 // where we return the address of a stack variable. For Reinterpre
Douglas Gregore200adc2008-10-27 19:41:14 +00002002 // FIXME: The comment about is wrong; we're not always converting
2003 // from pointer to pointer. I'm guessing that this code should also
Mike Stump11289f42009-09-09 15:08:12 +00002004 // handle references to objects.
2005 case Stmt::CXXStaticCastExprClass:
2006 case Stmt::CXXDynamicCastExprClass:
Douglas Gregore200adc2008-10-27 19:41:14 +00002007 case Stmt::CXXConstCastExprClass:
2008 case Stmt::CXXReinterpretCastExprClass: {
2009 Expr *S = cast<CXXNamedCastExpr>(E)->getSubExpr();
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002010 if (S->getType()->isPointerType() || S->getType()->isBlockPointerType())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002011 return EvalAddr(S, refVars);
Chris Lattner934edb22007-12-28 05:31:15 +00002012 else
2013 return NULL;
Chris Lattner934edb22007-12-28 05:31:15 +00002014 }
Mike Stump11289f42009-09-09 15:08:12 +00002015
Chris Lattner934edb22007-12-28 05:31:15 +00002016 // Everything else: we simply don't reason about them.
2017 default:
2018 return NULL;
2019 }
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002020}
Mike Stump11289f42009-09-09 15:08:12 +00002021
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002022
2023/// EvalVal - This function is complements EvalAddr in the mutual recursion.
2024/// See the comments for EvalAddr for more details.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002025static Expr *EvalVal(Expr *E, llvm::SmallVectorImpl<DeclRefExpr *> &refVars) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002026do {
Ted Kremeneke07a8cd2007-08-28 17:02:55 +00002027 // We should only be called for evaluating non-pointer expressions, or
2028 // expressions with a pointer type that are not used as references but instead
2029 // are l-values (e.g., DeclRefExpr with a pointer type).
Mike Stump11289f42009-09-09 15:08:12 +00002030
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002031 // Our "symbolic interpreter" is just a dispatch off the currently
2032 // viewed AST node. We then recursively traverse the AST by calling
2033 // EvalAddr and EvalVal appropriately.
2034 switch (E->getStmtClass()) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002035 case Stmt::ImplicitCastExprClass: {
2036 ImplicitCastExpr *IE = cast<ImplicitCastExpr>(E);
John McCall2536c6d2010-08-25 10:28:54 +00002037 if (IE->getValueKind() == VK_LValue) {
Ted Kremenekb7861562010-08-04 20:01:07 +00002038 E = IE->getSubExpr();
2039 continue;
2040 }
2041 return NULL;
2042 }
2043
Douglas Gregor4bd90e52009-10-23 18:54:35 +00002044 case Stmt::DeclRefExprClass: {
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002045 // When we hit a DeclRefExpr we are looking at code that refers to a
2046 // variable's name. If it's not a reference variable we check if it has
2047 // local storage within the function, and if so, return the expression.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002048 DeclRefExpr *DR = cast<DeclRefExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002049
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002050 if (VarDecl *V = dyn_cast<VarDecl>(DR->getDecl()))
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002051 if (V->hasLocalStorage()) {
2052 if (!V->getType()->isReferenceType())
2053 return DR;
2054
2055 // Reference variable, follow through to the expression that
2056 // it points to.
2057 if (V->hasInit()) {
2058 // Add the reference variable to the "trail".
2059 refVars.push_back(DR);
2060 return EvalVal(V->getInit(), refVars);
2061 }
2062 }
Mike Stump11289f42009-09-09 15:08:12 +00002063
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002064 return NULL;
2065 }
Mike Stump11289f42009-09-09 15:08:12 +00002066
Ted Kremenekb7861562010-08-04 20:01:07 +00002067 case Stmt::ParenExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002068 // Ignore parentheses.
Ted Kremenekb7861562010-08-04 20:01:07 +00002069 E = cast<ParenExpr>(E)->getSubExpr();
2070 continue;
2071 }
Mike Stump11289f42009-09-09 15:08:12 +00002072
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002073 case Stmt::UnaryOperatorClass: {
2074 // The only unary operator that make sense to handle here
2075 // is Deref. All others don't resolve to a "name." This includes
2076 // handling all sorts of rvalues passed to a unary operator.
2077 UnaryOperator *U = cast<UnaryOperator>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002078
John McCalle3027922010-08-25 11:45:40 +00002079 if (U->getOpcode() == UO_Deref)
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002080 return EvalAddr(U->getSubExpr(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002081
2082 return NULL;
2083 }
Mike Stump11289f42009-09-09 15:08:12 +00002084
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002085 case Stmt::ArraySubscriptExprClass: {
2086 // Array subscripts are potential references to data on the stack. We
2087 // retrieve the DeclRefExpr* for the array variable if it indeed
2088 // has local storage.
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002089 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002092 case Stmt::ConditionalOperatorClass: {
2093 // For conditional operators we need to see if either the LHS or RHS are
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002094 // non-NULL Expr's. If one is non-NULL, we return it.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002095 ConditionalOperator *C = cast<ConditionalOperator>(E);
2096
Anders Carlsson801c5c72007-11-30 19:04:31 +00002097 // Handle the GNU extension for missing LHS.
2098 if (Expr *lhsExpr = C->getLHS())
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002099 if (Expr *LHS = EvalVal(lhsExpr, refVars))
Anders Carlsson801c5c72007-11-30 19:04:31 +00002100 return LHS;
2101
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002102 return EvalVal(C->getRHS(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002103 }
Mike Stump11289f42009-09-09 15:08:12 +00002104
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002105 // Accesses to members are potential references to data on the stack.
Douglas Gregorf405d7e2009-08-31 23:41:50 +00002106 case Stmt::MemberExprClass: {
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002107 MemberExpr *M = cast<MemberExpr>(E);
Mike Stump11289f42009-09-09 15:08:12 +00002108
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002109 // Check for indirect access. We only want direct field accesses.
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002110 if (M->isArrow())
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002111 return NULL;
Ted Kremenekcbe6b0b2010-09-02 01:12:13 +00002112
2113 // Check whether the member type is itself a reference, in which case
2114 // we're not going to refer to the member, but to what the member refers to.
2115 if (M->getMemberDecl()->getType()->isReferenceType())
2116 return NULL;
2117
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002118 return EvalVal(M->getBase(), refVars);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002119 }
Mike Stump11289f42009-09-09 15:08:12 +00002120
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002121 default:
Argyrios Kyrtzidise72f7152010-11-30 22:57:32 +00002122 // Check that we don't return or take the address of a reference to a
2123 // temporary. This is only useful in C++.
2124 if (!E->isTypeDependent() && E->isRValue())
2125 return E;
2126
2127 // Everything else: we simply don't reason about them.
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002128 return NULL;
2129 }
Ted Kremenekb7861562010-08-04 20:01:07 +00002130} while (true);
Ted Kremenekcff94fa2007-08-17 16:46:58 +00002131}
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002132
2133//===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
2134
2135/// Check for comparisons of floating point operands using != and ==.
2136/// Issue a warning if these are no self-comparisons, as they are not likely
2137/// to do what the programmer intended.
2138void Sema::CheckFloatComparison(SourceLocation loc, Expr* lex, Expr *rex) {
2139 bool EmitWarning = true;
Mike Stump11289f42009-09-09 15:08:12 +00002140
John McCall34376a62010-12-04 03:47:34 +00002141 Expr* LeftExprSansParen = lex->IgnoreParenImpCasts();
2142 Expr* RightExprSansParen = rex->IgnoreParenImpCasts();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002143
2144 // Special case: check for x == x (which is OK).
2145 // Do not emit warnings for such cases.
2146 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
2147 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
2148 if (DRL->getDecl() == DRR->getDecl())
2149 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002150
2151
Ted Kremenekeda40e22007-11-29 00:59:04 +00002152 // Special case: check for comparisons against literals that can be exactly
2153 // represented by APFloat. In such cases, do not emit a warning. This
2154 // is a heuristic: often comparison against such literals are used to
2155 // detect if a value in a variable has not changed. This clearly can
2156 // lead to false negatives.
2157 if (EmitWarning) {
2158 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
2159 if (FLL->isExact())
2160 EmitWarning = false;
Mike Stump12b8ce12009-08-04 21:02:39 +00002161 } else
Ted Kremenekeda40e22007-11-29 00:59:04 +00002162 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)){
2163 if (FLR->isExact())
2164 EmitWarning = false;
2165 }
2166 }
Mike Stump11289f42009-09-09 15:08:12 +00002167
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002168 // Check for comparisons with builtin types.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002169 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002170 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002171 if (CL->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002172 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002173
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002174 if (EmitWarning)
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002175 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
Douglas Gregore711f702009-02-14 18:57:46 +00002176 if (CR->isBuiltinCall(Context))
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002177 EmitWarning = false;
Mike Stump11289f42009-09-09 15:08:12 +00002178
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002179 // Emit the diagnostic.
2180 if (EmitWarning)
Chris Lattner3b054132008-11-19 05:08:23 +00002181 Diag(loc, diag::warn_floatingpoint_eq)
2182 << lex->getSourceRange() << rex->getSourceRange();
Ted Kremenek43fb8b02007-11-25 00:58:00 +00002183}
John McCallca01b222010-01-04 23:21:16 +00002184
John McCall70aa5392010-01-06 05:24:50 +00002185//===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
2186//===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
John McCallca01b222010-01-04 23:21:16 +00002187
John McCall70aa5392010-01-06 05:24:50 +00002188namespace {
John McCallca01b222010-01-04 23:21:16 +00002189
John McCall70aa5392010-01-06 05:24:50 +00002190/// Structure recording the 'active' range of an integer-valued
2191/// expression.
2192struct IntRange {
2193 /// The number of bits active in the int.
2194 unsigned Width;
John McCallca01b222010-01-04 23:21:16 +00002195
John McCall70aa5392010-01-06 05:24:50 +00002196 /// True if the int is known not to have negative values.
2197 bool NonNegative;
John McCallca01b222010-01-04 23:21:16 +00002198
John McCall70aa5392010-01-06 05:24:50 +00002199 IntRange(unsigned Width, bool NonNegative)
2200 : Width(Width), NonNegative(NonNegative)
2201 {}
John McCallca01b222010-01-04 23:21:16 +00002202
John McCall817d4af2010-11-10 23:38:19 +00002203 /// Returns the range of the bool type.
John McCall70aa5392010-01-06 05:24:50 +00002204 static IntRange forBoolType() {
2205 return IntRange(1, true);
John McCall263a48b2010-01-04 23:31:57 +00002206 }
2207
John McCall817d4af2010-11-10 23:38:19 +00002208 /// Returns the range of an opaque value of the given integral type.
2209 static IntRange forValueOfType(ASTContext &C, QualType T) {
2210 return forValueOfCanonicalType(C,
2211 T->getCanonicalTypeInternal().getTypePtr());
John McCall263a48b2010-01-04 23:31:57 +00002212 }
2213
John McCall817d4af2010-11-10 23:38:19 +00002214 /// Returns the range of an opaque value of a canonical integral type.
2215 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
John McCall70aa5392010-01-06 05:24:50 +00002216 assert(T->isCanonicalUnqualified());
2217
2218 if (const VectorType *VT = dyn_cast<VectorType>(T))
2219 T = VT->getElementType().getTypePtr();
2220 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2221 T = CT->getElementType().getTypePtr();
John McCallcc7e5bf2010-05-06 08:58:33 +00002222
John McCall18a2c2c2010-11-09 22:22:12 +00002223 // For enum types, use the known bit width of the enumerators.
John McCallcc7e5bf2010-05-06 08:58:33 +00002224 if (const EnumType *ET = dyn_cast<EnumType>(T)) {
2225 EnumDecl *Enum = ET->getDecl();
John McCall18a2c2c2010-11-09 22:22:12 +00002226 if (!Enum->isDefinition())
2227 return IntRange(C.getIntWidth(QualType(T, 0)), false);
2228
John McCallcc7e5bf2010-05-06 08:58:33 +00002229 unsigned NumPositive = Enum->getNumPositiveBits();
2230 unsigned NumNegative = Enum->getNumNegativeBits();
2231
2232 return IntRange(std::max(NumPositive, NumNegative), NumNegative == 0);
2233 }
John McCall70aa5392010-01-06 05:24:50 +00002234
2235 const BuiltinType *BT = cast<BuiltinType>(T);
2236 assert(BT->isInteger());
2237
2238 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2239 }
2240
John McCall817d4af2010-11-10 23:38:19 +00002241 /// Returns the "target" range of a canonical integral type, i.e.
2242 /// the range of values expressible in the type.
2243 ///
2244 /// This matches forValueOfCanonicalType except that enums have the
2245 /// full range of their type, not the range of their enumerators.
2246 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
2247 assert(T->isCanonicalUnqualified());
2248
2249 if (const VectorType *VT = dyn_cast<VectorType>(T))
2250 T = VT->getElementType().getTypePtr();
2251 if (const ComplexType *CT = dyn_cast<ComplexType>(T))
2252 T = CT->getElementType().getTypePtr();
2253 if (const EnumType *ET = dyn_cast<EnumType>(T))
2254 T = ET->getDecl()->getIntegerType().getTypePtr();
2255
2256 const BuiltinType *BT = cast<BuiltinType>(T);
2257 assert(BT->isInteger());
2258
2259 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
2260 }
2261
2262 /// Returns the supremum of two ranges: i.e. their conservative merge.
John McCallff96ccd2010-02-23 19:22:29 +00002263 static IntRange join(IntRange L, IntRange R) {
John McCall70aa5392010-01-06 05:24:50 +00002264 return IntRange(std::max(L.Width, R.Width),
John McCall2ce81ad2010-01-06 22:07:33 +00002265 L.NonNegative && R.NonNegative);
2266 }
2267
John McCall817d4af2010-11-10 23:38:19 +00002268 /// Returns the infinum of two ranges: i.e. their aggressive merge.
John McCallff96ccd2010-02-23 19:22:29 +00002269 static IntRange meet(IntRange L, IntRange R) {
John McCall2ce81ad2010-01-06 22:07:33 +00002270 return IntRange(std::min(L.Width, R.Width),
2271 L.NonNegative || R.NonNegative);
John McCall70aa5392010-01-06 05:24:50 +00002272 }
2273};
2274
2275IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, unsigned MaxWidth) {
2276 if (value.isSigned() && value.isNegative())
2277 return IntRange(value.getMinSignedBits(), false);
2278
2279 if (value.getBitWidth() > MaxWidth)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002280 value = value.trunc(MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002281
2282 // isNonNegative() just checks the sign bit without considering
2283 // signedness.
2284 return IntRange(value.getActiveBits(), true);
2285}
2286
John McCall74430522010-01-06 22:57:21 +00002287IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
John McCall70aa5392010-01-06 05:24:50 +00002288 unsigned MaxWidth) {
2289 if (result.isInt())
2290 return GetValueRange(C, result.getInt(), MaxWidth);
2291
2292 if (result.isVector()) {
John McCall74430522010-01-06 22:57:21 +00002293 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
2294 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
2295 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
2296 R = IntRange::join(R, El);
2297 }
John McCall70aa5392010-01-06 05:24:50 +00002298 return R;
2299 }
2300
2301 if (result.isComplexInt()) {
2302 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
2303 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
2304 return IntRange::join(R, I);
John McCall263a48b2010-01-04 23:31:57 +00002305 }
2306
2307 // This can happen with lossless casts to intptr_t of "based" lvalues.
2308 // Assume it might use arbitrary bits.
John McCall74430522010-01-06 22:57:21 +00002309 // FIXME: The only reason we need to pass the type in here is to get
2310 // the sign right on this one case. It would be nice if APValue
2311 // preserved this.
John McCall70aa5392010-01-06 05:24:50 +00002312 assert(result.isLValue());
John McCall74430522010-01-06 22:57:21 +00002313 return IntRange(MaxWidth, Ty->isUnsignedIntegerType());
John McCall263a48b2010-01-04 23:31:57 +00002314}
John McCall70aa5392010-01-06 05:24:50 +00002315
2316/// Pseudo-evaluate the given integer expression, estimating the
2317/// range of values it might take.
2318///
2319/// \param MaxWidth - the width to which the value will be truncated
2320IntRange GetExprRange(ASTContext &C, Expr *E, unsigned MaxWidth) {
2321 E = E->IgnoreParens();
2322
2323 // Try a full evaluation first.
2324 Expr::EvalResult result;
2325 if (E->Evaluate(result, C))
John McCall74430522010-01-06 22:57:21 +00002326 return GetValueRange(C, result.Val, E->getType(), MaxWidth);
John McCall70aa5392010-01-06 05:24:50 +00002327
2328 // I think we only want to look through implicit casts here; if the
2329 // user has an explicit widening cast, we should treat the value as
2330 // being of the new, wider type.
2331 if (ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E)) {
John McCalle3027922010-08-25 11:45:40 +00002332 if (CE->getCastKind() == CK_NoOp)
John McCall70aa5392010-01-06 05:24:50 +00002333 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
2334
John McCall817d4af2010-11-10 23:38:19 +00002335 IntRange OutputTypeRange = IntRange::forValueOfType(C, CE->getType());
John McCall70aa5392010-01-06 05:24:50 +00002336
John McCalle3027922010-08-25 11:45:40 +00002337 bool isIntegerCast = (CE->getCastKind() == CK_IntegralCast);
John McCall2ce81ad2010-01-06 22:07:33 +00002338
John McCall70aa5392010-01-06 05:24:50 +00002339 // Assume that non-integer casts can span the full range of the type.
John McCall2ce81ad2010-01-06 22:07:33 +00002340 if (!isIntegerCast)
John McCall70aa5392010-01-06 05:24:50 +00002341 return OutputTypeRange;
2342
2343 IntRange SubRange
2344 = GetExprRange(C, CE->getSubExpr(),
2345 std::min(MaxWidth, OutputTypeRange.Width));
2346
2347 // Bail out if the subexpr's range is as wide as the cast type.
2348 if (SubRange.Width >= OutputTypeRange.Width)
2349 return OutputTypeRange;
2350
2351 // Otherwise, we take the smaller width, and we're non-negative if
2352 // either the output type or the subexpr is.
2353 return IntRange(SubRange.Width,
2354 SubRange.NonNegative || OutputTypeRange.NonNegative);
2355 }
2356
2357 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
2358 // If we can fold the condition, just take that operand.
2359 bool CondResult;
2360 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
2361 return GetExprRange(C, CondResult ? CO->getTrueExpr()
2362 : CO->getFalseExpr(),
2363 MaxWidth);
2364
2365 // Otherwise, conservatively merge.
2366 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
2367 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
2368 return IntRange::join(L, R);
2369 }
2370
2371 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
2372 switch (BO->getOpcode()) {
2373
2374 // Boolean-valued operations are single-bit and positive.
John McCalle3027922010-08-25 11:45:40 +00002375 case BO_LAnd:
2376 case BO_LOr:
2377 case BO_LT:
2378 case BO_GT:
2379 case BO_LE:
2380 case BO_GE:
2381 case BO_EQ:
2382 case BO_NE:
John McCall70aa5392010-01-06 05:24:50 +00002383 return IntRange::forBoolType();
2384
John McCallff96ccd2010-02-23 19:22:29 +00002385 // The type of these compound assignments is the type of the LHS,
2386 // so the RHS is not necessarily an integer.
John McCalle3027922010-08-25 11:45:40 +00002387 case BO_MulAssign:
2388 case BO_DivAssign:
2389 case BO_RemAssign:
2390 case BO_AddAssign:
2391 case BO_SubAssign:
John McCall817d4af2010-11-10 23:38:19 +00002392 return IntRange::forValueOfType(C, E->getType());
John McCallff96ccd2010-02-23 19:22:29 +00002393
John McCall70aa5392010-01-06 05:24:50 +00002394 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002395 case BO_PtrMemD:
2396 case BO_PtrMemI:
John McCall817d4af2010-11-10 23:38:19 +00002397 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002398
John McCall2ce81ad2010-01-06 22:07:33 +00002399 // Bitwise-and uses the *infinum* of the two source ranges.
John McCalle3027922010-08-25 11:45:40 +00002400 case BO_And:
2401 case BO_AndAssign:
John McCall2ce81ad2010-01-06 22:07:33 +00002402 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
2403 GetExprRange(C, BO->getRHS(), MaxWidth));
2404
John McCall70aa5392010-01-06 05:24:50 +00002405 // Left shift gets black-listed based on a judgement call.
John McCalle3027922010-08-25 11:45:40 +00002406 case BO_Shl:
John McCall1bff9932010-04-07 01:14:35 +00002407 // ...except that we want to treat '1 << (blah)' as logically
2408 // positive. It's an important idiom.
2409 if (IntegerLiteral *I
2410 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
2411 if (I->getValue() == 1) {
John McCall817d4af2010-11-10 23:38:19 +00002412 IntRange R = IntRange::forValueOfType(C, E->getType());
John McCall1bff9932010-04-07 01:14:35 +00002413 return IntRange(R.Width, /*NonNegative*/ true);
2414 }
2415 }
2416 // fallthrough
2417
John McCalle3027922010-08-25 11:45:40 +00002418 case BO_ShlAssign:
John McCall817d4af2010-11-10 23:38:19 +00002419 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002420
John McCall2ce81ad2010-01-06 22:07:33 +00002421 // Right shift by a constant can narrow its left argument.
John McCalle3027922010-08-25 11:45:40 +00002422 case BO_Shr:
2423 case BO_ShrAssign: {
John McCall2ce81ad2010-01-06 22:07:33 +00002424 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2425
2426 // If the shift amount is a positive constant, drop the width by
2427 // that much.
2428 llvm::APSInt shift;
2429 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
2430 shift.isNonNegative()) {
2431 unsigned zext = shift.getZExtValue();
2432 if (zext >= L.Width)
2433 L.Width = (L.NonNegative ? 0 : 1);
2434 else
2435 L.Width -= zext;
2436 }
2437
2438 return L;
2439 }
2440
2441 // Comma acts as its right operand.
John McCalle3027922010-08-25 11:45:40 +00002442 case BO_Comma:
John McCall70aa5392010-01-06 05:24:50 +00002443 return GetExprRange(C, BO->getRHS(), MaxWidth);
2444
John McCall2ce81ad2010-01-06 22:07:33 +00002445 // Black-list pointer subtractions.
John McCalle3027922010-08-25 11:45:40 +00002446 case BO_Sub:
John McCall70aa5392010-01-06 05:24:50 +00002447 if (BO->getLHS()->getType()->isPointerType())
John McCall817d4af2010-11-10 23:38:19 +00002448 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002449 // fallthrough
Ted Kremenekc8b188d2010-02-16 01:46:59 +00002450
John McCall70aa5392010-01-06 05:24:50 +00002451 default:
2452 break;
2453 }
2454
2455 // Treat every other operator as if it were closed on the
2456 // narrowest type that encompasses both operands.
2457 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
2458 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
2459 return IntRange::join(L, R);
2460 }
2461
2462 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2463 switch (UO->getOpcode()) {
2464 // Boolean-valued operations are white-listed.
John McCalle3027922010-08-25 11:45:40 +00002465 case UO_LNot:
John McCall70aa5392010-01-06 05:24:50 +00002466 return IntRange::forBoolType();
2467
2468 // Operations with opaque sources are black-listed.
John McCalle3027922010-08-25 11:45:40 +00002469 case UO_Deref:
2470 case UO_AddrOf: // should be impossible
John McCall817d4af2010-11-10 23:38:19 +00002471 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002472
2473 default:
2474 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
2475 }
2476 }
Douglas Gregor882211c2010-04-28 22:16:22 +00002477
2478 if (dyn_cast<OffsetOfExpr>(E)) {
John McCall817d4af2010-11-10 23:38:19 +00002479 IntRange::forValueOfType(C, E->getType());
Douglas Gregor882211c2010-04-28 22:16:22 +00002480 }
John McCall70aa5392010-01-06 05:24:50 +00002481
2482 FieldDecl *BitField = E->getBitField();
2483 if (BitField) {
2484 llvm::APSInt BitWidthAP = BitField->getBitWidth()->EvaluateAsInt(C);
2485 unsigned BitWidth = BitWidthAP.getZExtValue();
2486
2487 return IntRange(BitWidth, BitField->getType()->isUnsignedIntegerType());
2488 }
2489
John McCall817d4af2010-11-10 23:38:19 +00002490 return IntRange::forValueOfType(C, E->getType());
John McCall70aa5392010-01-06 05:24:50 +00002491}
John McCall263a48b2010-01-04 23:31:57 +00002492
John McCallcc7e5bf2010-05-06 08:58:33 +00002493IntRange GetExprRange(ASTContext &C, Expr *E) {
2494 return GetExprRange(C, E, C.getIntWidth(E->getType()));
2495}
2496
John McCall263a48b2010-01-04 23:31:57 +00002497/// Checks whether the given value, which currently has the given
2498/// source semantics, has the same value when coerced through the
2499/// target semantics.
John McCall70aa5392010-01-06 05:24:50 +00002500bool IsSameFloatAfterCast(const llvm::APFloat &value,
2501 const llvm::fltSemantics &Src,
2502 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002503 llvm::APFloat truncated = value;
2504
2505 bool ignored;
2506 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
2507 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
2508
2509 return truncated.bitwiseIsEqual(value);
2510}
2511
2512/// Checks whether the given value, which currently has the given
2513/// source semantics, has the same value when coerced through the
2514/// target semantics.
2515///
2516/// The value might be a vector of floats (or a complex number).
John McCall70aa5392010-01-06 05:24:50 +00002517bool IsSameFloatAfterCast(const APValue &value,
2518 const llvm::fltSemantics &Src,
2519 const llvm::fltSemantics &Tgt) {
John McCall263a48b2010-01-04 23:31:57 +00002520 if (value.isFloat())
2521 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
2522
2523 if (value.isVector()) {
2524 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
2525 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
2526 return false;
2527 return true;
2528 }
2529
2530 assert(value.isComplexFloat());
2531 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
2532 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
2533}
2534
John McCallacf0ee52010-10-08 02:01:28 +00002535void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002536
Ted Kremenek6274be42010-09-23 21:43:44 +00002537static bool IsZero(Sema &S, Expr *E) {
2538 // Suppress cases where we are comparing against an enum constant.
2539 if (const DeclRefExpr *DR =
2540 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
2541 if (isa<EnumConstantDecl>(DR->getDecl()))
2542 return false;
2543
2544 // Suppress cases where the '0' value is expanded from a macro.
2545 if (E->getLocStart().isMacroID())
2546 return false;
2547
John McCallcc7e5bf2010-05-06 08:58:33 +00002548 llvm::APSInt Value;
2549 return E->isIntegerConstantExpr(Value, S.Context) && Value == 0;
2550}
2551
John McCall2551c1b2010-10-06 00:25:24 +00002552static bool HasEnumType(Expr *E) {
2553 // Strip off implicit integral promotions.
2554 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002555 if (ICE->getCastKind() != CK_IntegralCast &&
2556 ICE->getCastKind() != CK_NoOp)
John McCall2551c1b2010-10-06 00:25:24 +00002557 break;
Argyrios Kyrtzidis15a9edc2010-10-07 21:52:18 +00002558 E = ICE->getSubExpr();
John McCall2551c1b2010-10-06 00:25:24 +00002559 }
2560
2561 return E->getType()->isEnumeralType();
2562}
2563
John McCallcc7e5bf2010-05-06 08:58:33 +00002564void CheckTrivialUnsignedComparison(Sema &S, BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002565 BinaryOperatorKind op = E->getOpcode();
Douglas Gregorb14dbd72010-12-21 07:22:56 +00002566 if (E->isValueDependent())
2567 return;
2568
John McCalle3027922010-08-25 11:45:40 +00002569 if (op == BO_LT && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002570 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002571 << "< 0" << "false" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002572 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002573 } else if (op == BO_GE && IsZero(S, E->getRHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002574 S.Diag(E->getOperatorLoc(), diag::warn_lunsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002575 << ">= 0" << "true" << HasEnumType(E->getLHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002576 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002577 } else if (op == BO_GT && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002578 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002579 << "0 >" << "false" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002580 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
John McCalle3027922010-08-25 11:45:40 +00002581 } else if (op == BO_LE && IsZero(S, E->getLHS())) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002582 S.Diag(E->getOperatorLoc(), diag::warn_runsigned_always_true_comparison)
John McCall2551c1b2010-10-06 00:25:24 +00002583 << "0 <=" << "true" << HasEnumType(E->getRHS())
John McCallcc7e5bf2010-05-06 08:58:33 +00002584 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
2585 }
2586}
2587
2588/// Analyze the operands of the given comparison. Implements the
2589/// fallback case from AnalyzeComparison.
2590void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
John McCallacf0ee52010-10-08 02:01:28 +00002591 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2592 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
John McCallcc7e5bf2010-05-06 08:58:33 +00002593}
John McCall263a48b2010-01-04 23:31:57 +00002594
John McCallca01b222010-01-04 23:21:16 +00002595/// \brief Implements -Wsign-compare.
2596///
2597/// \param lex the left-hand expression
2598/// \param rex the right-hand expression
2599/// \param OpLoc the location of the joining operator
John McCall71d8d9b2010-03-11 19:43:18 +00002600/// \param BinOpc binary opcode or 0
John McCallcc7e5bf2010-05-06 08:58:33 +00002601void AnalyzeComparison(Sema &S, BinaryOperator *E) {
2602 // The type the comparison is being performed in.
2603 QualType T = E->getLHS()->getType();
2604 assert(S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())
2605 && "comparison with mismatched types");
John McCallca01b222010-01-04 23:21:16 +00002606
John McCallcc7e5bf2010-05-06 08:58:33 +00002607 // We don't do anything special if this isn't an unsigned integral
2608 // comparison: we're only interested in integral comparisons, and
2609 // signed comparisons only happen in cases we don't care to warn about.
Douglas Gregor5b054542011-02-19 22:34:59 +00002610 //
2611 // We also don't care about value-dependent expressions or expressions
2612 // whose result is a constant.
2613 if (!T->hasUnsignedIntegerRepresentation()
2614 || E->isValueDependent() || E->isIntegerConstantExpr(S.Context))
John McCallcc7e5bf2010-05-06 08:58:33 +00002615 return AnalyzeImpConvsInComparison(S, E);
John McCall70aa5392010-01-06 05:24:50 +00002616
John McCallcc7e5bf2010-05-06 08:58:33 +00002617 Expr *lex = E->getLHS()->IgnoreParenImpCasts();
2618 Expr *rex = E->getRHS()->IgnoreParenImpCasts();
John McCallca01b222010-01-04 23:21:16 +00002619
John McCallcc7e5bf2010-05-06 08:58:33 +00002620 // Check to see if one of the (unmodified) operands is of different
2621 // signedness.
2622 Expr *signedOperand, *unsignedOperand;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002623 if (lex->getType()->hasSignedIntegerRepresentation()) {
2624 assert(!rex->getType()->hasSignedIntegerRepresentation() &&
John McCallcc7e5bf2010-05-06 08:58:33 +00002625 "unsigned comparison between two signed integer expressions?");
2626 signedOperand = lex;
2627 unsignedOperand = rex;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002628 } else if (rex->getType()->hasSignedIntegerRepresentation()) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002629 signedOperand = rex;
2630 unsignedOperand = lex;
John McCallca01b222010-01-04 23:21:16 +00002631 } else {
John McCallcc7e5bf2010-05-06 08:58:33 +00002632 CheckTrivialUnsignedComparison(S, E);
2633 return AnalyzeImpConvsInComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002634 }
2635
John McCallcc7e5bf2010-05-06 08:58:33 +00002636 // Otherwise, calculate the effective range of the signed operand.
2637 IntRange signedRange = GetExprRange(S.Context, signedOperand);
John McCall70aa5392010-01-06 05:24:50 +00002638
John McCallcc7e5bf2010-05-06 08:58:33 +00002639 // Go ahead and analyze implicit conversions in the operands. Note
2640 // that we skip the implicit conversions on both sides.
John McCallacf0ee52010-10-08 02:01:28 +00002641 AnalyzeImplicitConversions(S, lex, E->getOperatorLoc());
2642 AnalyzeImplicitConversions(S, rex, E->getOperatorLoc());
John McCallca01b222010-01-04 23:21:16 +00002643
John McCallcc7e5bf2010-05-06 08:58:33 +00002644 // If the signed range is non-negative, -Wsign-compare won't fire,
2645 // but we should still check for comparisons which are always true
2646 // or false.
2647 if (signedRange.NonNegative)
2648 return CheckTrivialUnsignedComparison(S, E);
John McCallca01b222010-01-04 23:21:16 +00002649
2650 // For (in)equality comparisons, if the unsigned operand is a
2651 // constant which cannot collide with a overflowed signed operand,
2652 // then reinterpreting the signed operand as unsigned will not
2653 // change the result of the comparison.
John McCallcc7e5bf2010-05-06 08:58:33 +00002654 if (E->isEqualityOp()) {
2655 unsigned comparisonWidth = S.Context.getIntWidth(T);
2656 IntRange unsignedRange = GetExprRange(S.Context, unsignedOperand);
John McCallca01b222010-01-04 23:21:16 +00002657
John McCallcc7e5bf2010-05-06 08:58:33 +00002658 // We should never be unable to prove that the unsigned operand is
2659 // non-negative.
2660 assert(unsignedRange.NonNegative && "unsigned range includes negative?");
2661
2662 if (unsignedRange.Width < comparisonWidth)
2663 return;
2664 }
2665
2666 S.Diag(E->getOperatorLoc(), diag::warn_mixed_sign_comparison)
2667 << lex->getType() << rex->getType()
2668 << lex->getSourceRange() << rex->getSourceRange();
John McCallca01b222010-01-04 23:21:16 +00002669}
2670
John McCall1f425642010-11-11 03:21:53 +00002671/// Analyzes an attempt to assign the given value to a bitfield.
2672///
2673/// Returns true if there was something fishy about the attempt.
2674bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
2675 SourceLocation InitLoc) {
2676 assert(Bitfield->isBitField());
2677 if (Bitfield->isInvalidDecl())
2678 return false;
2679
John McCalldeebbcf2010-11-11 05:33:51 +00002680 // White-list bool bitfields.
2681 if (Bitfield->getType()->isBooleanType())
2682 return false;
2683
Douglas Gregor789adec2011-02-04 13:09:01 +00002684 // Ignore value- or type-dependent expressions.
2685 if (Bitfield->getBitWidth()->isValueDependent() ||
2686 Bitfield->getBitWidth()->isTypeDependent() ||
2687 Init->isValueDependent() ||
2688 Init->isTypeDependent())
2689 return false;
2690
John McCall1f425642010-11-11 03:21:53 +00002691 Expr *OriginalInit = Init->IgnoreParenImpCasts();
2692
2693 llvm::APSInt Width(32);
2694 Expr::EvalResult InitValue;
2695 if (!Bitfield->getBitWidth()->isIntegerConstantExpr(Width, S.Context) ||
John McCalldeebbcf2010-11-11 05:33:51 +00002696 !OriginalInit->Evaluate(InitValue, S.Context) ||
John McCall1f425642010-11-11 03:21:53 +00002697 !InitValue.Val.isInt())
2698 return false;
2699
2700 const llvm::APSInt &Value = InitValue.Val.getInt();
2701 unsigned OriginalWidth = Value.getBitWidth();
2702 unsigned FieldWidth = Width.getZExtValue();
2703
2704 if (OriginalWidth <= FieldWidth)
2705 return false;
2706
Jay Foad6d4db0c2010-12-07 08:25:34 +00002707 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
John McCall1f425642010-11-11 03:21:53 +00002708
2709 // It's fairly common to write values into signed bitfields
2710 // that, if sign-extended, would end up becoming a different
2711 // value. We don't want to warn about that.
2712 if (Value.isSigned() && Value.isNegative())
Jay Foad6d4db0c2010-12-07 08:25:34 +00002713 TruncatedValue = TruncatedValue.sext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00002714 else
Jay Foad6d4db0c2010-12-07 08:25:34 +00002715 TruncatedValue = TruncatedValue.zext(OriginalWidth);
John McCall1f425642010-11-11 03:21:53 +00002716
2717 if (Value == TruncatedValue)
2718 return false;
2719
2720 std::string PrettyValue = Value.toString(10);
2721 std::string PrettyTrunc = TruncatedValue.toString(10);
2722
2723 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
2724 << PrettyValue << PrettyTrunc << OriginalInit->getType()
2725 << Init->getSourceRange();
2726
2727 return true;
2728}
2729
John McCalld2a53122010-11-09 23:24:47 +00002730/// Analyze the given simple or compound assignment for warning-worthy
2731/// operations.
2732void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
2733 // Just recurse on the LHS.
2734 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
2735
2736 // We want to recurse on the RHS as normal unless we're assigning to
2737 // a bitfield.
2738 if (FieldDecl *Bitfield = E->getLHS()->getBitField()) {
John McCall1f425642010-11-11 03:21:53 +00002739 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
2740 E->getOperatorLoc())) {
2741 // Recurse, ignoring any implicit conversions on the RHS.
2742 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
2743 E->getOperatorLoc());
John McCalld2a53122010-11-09 23:24:47 +00002744 }
2745 }
2746
2747 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
2748}
2749
John McCall263a48b2010-01-04 23:31:57 +00002750/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
Douglas Gregor364f7db2011-03-12 00:14:31 +00002751void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
2752 SourceLocation CContext, unsigned diag) {
2753 S.Diag(E->getExprLoc(), diag)
2754 << SourceType << T << E->getSourceRange() << SourceRange(CContext);
2755}
2756
Chandler Carruth7f3654f2011-04-05 06:47:57 +00002757/// Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
2758void DiagnoseImpCast(Sema &S, Expr *E, QualType T, SourceLocation CContext,
2759 unsigned diag) {
2760 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag);
2761}
2762
John McCall18a2c2c2010-11-09 22:22:12 +00002763std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range) {
2764 if (!Range.Width) return "0";
2765
2766 llvm::APSInt ValueInRange = Value;
2767 ValueInRange.setIsSigned(!Range.NonNegative);
Jay Foad6d4db0c2010-12-07 08:25:34 +00002768 ValueInRange = ValueInRange.trunc(Range.Width);
John McCall18a2c2c2010-11-09 22:22:12 +00002769 return ValueInRange.toString(10);
2770}
2771
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002772static bool isFromSystemMacro(Sema &S, SourceLocation loc) {
2773 SourceManager &smgr = S.Context.getSourceManager();
2774 return loc.isMacroID() && smgr.isInSystemHeader(smgr.getSpellingLoc(loc));
2775}
2776
John McCallcc7e5bf2010-05-06 08:58:33 +00002777void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002778 SourceLocation CC, bool *ICContext = 0) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002779 if (E->isTypeDependent() || E->isValueDependent()) return;
John McCall263a48b2010-01-04 23:31:57 +00002780
John McCallcc7e5bf2010-05-06 08:58:33 +00002781 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
2782 const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
2783 if (Source == Target) return;
2784 if (Target->isDependentType()) return;
John McCall263a48b2010-01-04 23:31:57 +00002785
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002786 // If the conversion context location is invalid don't complain.
2787 // We also don't want to emit a warning if the issue occurs from the
2788 // instantiation of a system macro. The problem is that 'getSpellingLoc()'
2789 // is slow, so we delay this check as long as possible. Once we detect
2790 // we are in that scenario, we just return.
2791 if (CC.isInvalid())
John McCallacf0ee52010-10-08 02:01:28 +00002792 return;
2793
John McCall263a48b2010-01-04 23:31:57 +00002794 // Never diagnose implicit casts to bool.
2795 if (Target->isSpecificBuiltinType(BuiltinType::Bool))
2796 return;
2797
2798 // Strip vector types.
2799 if (isa<VectorType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002800 if (!isa<VectorType>(Target)) {
2801 if (isFromSystemMacro(S, CC))
2802 return;
John McCallacf0ee52010-10-08 02:01:28 +00002803 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002804 }
John McCall263a48b2010-01-04 23:31:57 +00002805
2806 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
2807 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
2808 }
2809
2810 // Strip complex types.
2811 if (isa<ComplexType>(Source)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002812 if (!isa<ComplexType>(Target)) {
2813 if (isFromSystemMacro(S, CC))
2814 return;
2815
John McCallacf0ee52010-10-08 02:01:28 +00002816 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002817 }
John McCall263a48b2010-01-04 23:31:57 +00002818
2819 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
2820 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
2821 }
2822
2823 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
2824 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
2825
2826 // If the source is floating point...
2827 if (SourceBT && SourceBT->isFloatingPoint()) {
2828 // ...and the target is floating point...
2829 if (TargetBT && TargetBT->isFloatingPoint()) {
2830 // ...then warn if we're dropping FP rank.
2831
2832 // Builtin FP kinds are ordered by increasing FP rank.
2833 if (SourceBT->getKind() > TargetBT->getKind()) {
2834 // Don't warn about float constants that are precisely
2835 // representable in the target type.
2836 Expr::EvalResult result;
John McCallcc7e5bf2010-05-06 08:58:33 +00002837 if (E->Evaluate(result, S.Context)) {
John McCall263a48b2010-01-04 23:31:57 +00002838 // Value might be a float, a float vector, or a float complex.
2839 if (IsSameFloatAfterCast(result.Val,
John McCallcc7e5bf2010-05-06 08:58:33 +00002840 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
2841 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
John McCall263a48b2010-01-04 23:31:57 +00002842 return;
2843 }
2844
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002845 if (isFromSystemMacro(S, CC))
2846 return;
2847
John McCallacf0ee52010-10-08 02:01:28 +00002848 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
John McCall263a48b2010-01-04 23:31:57 +00002849 }
2850 return;
2851 }
2852
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002853 // If the target is integral, always warn.
Chandler Carruth22c7a792011-02-17 11:05:49 +00002854 if ((TargetBT && TargetBT->isInteger())) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002855 if (isFromSystemMacro(S, CC))
2856 return;
2857
Chandler Carruth22c7a792011-02-17 11:05:49 +00002858 Expr *InnerE = E->IgnoreParenImpCasts();
2859 if (FloatingLiteral *LiteralExpr = dyn_cast<FloatingLiteral>(InnerE)) {
2860 DiagnoseImpCast(S, LiteralExpr, T, CC,
2861 diag::warn_impcast_literal_float_to_integer);
2862 } else {
2863 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
2864 }
2865 }
John McCall263a48b2010-01-04 23:31:57 +00002866
2867 return;
2868 }
2869
John McCall70aa5392010-01-06 05:24:50 +00002870 if (!Source->isIntegerType() || !Target->isIntegerType())
John McCall263a48b2010-01-04 23:31:57 +00002871 return;
2872
John McCallcc7e5bf2010-05-06 08:58:33 +00002873 IntRange SourceRange = GetExprRange(S.Context, E);
John McCall817d4af2010-11-10 23:38:19 +00002874 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
John McCall70aa5392010-01-06 05:24:50 +00002875
2876 if (SourceRange.Width > TargetRange.Width) {
John McCall18a2c2c2010-11-09 22:22:12 +00002877 // If the source is a constant, use a default-on diagnostic.
2878 // TODO: this should happen for bitfield stores, too.
2879 llvm::APSInt Value(32);
2880 if (E->isIntegerConstantExpr(Value, S.Context)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002881 if (isFromSystemMacro(S, CC))
2882 return;
2883
John McCall18a2c2c2010-11-09 22:22:12 +00002884 std::string PrettySourceValue = Value.toString(10);
2885 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
2886
2887 S.Diag(E->getExprLoc(), diag::warn_impcast_integer_precision_constant)
2888 << PrettySourceValue << PrettyTargetValue
2889 << E->getType() << T << E->getSourceRange() << clang::SourceRange(CC);
2890 return;
2891 }
2892
John McCall263a48b2010-01-04 23:31:57 +00002893 // People want to build with -Wshorten-64-to-32 and not -Wconversion
2894 // and by god we'll let them.
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002895
2896 if (isFromSystemMacro(S, CC))
2897 return;
2898
John McCall70aa5392010-01-06 05:24:50 +00002899 if (SourceRange.Width == 64 && TargetRange.Width == 32)
John McCallacf0ee52010-10-08 02:01:28 +00002900 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32);
2901 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
John McCallcc7e5bf2010-05-06 08:58:33 +00002902 }
2903
2904 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
2905 (!TargetRange.NonNegative && SourceRange.NonNegative &&
2906 SourceRange.Width == TargetRange.Width)) {
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002907
2908 if (isFromSystemMacro(S, CC))
2909 return;
2910
John McCallcc7e5bf2010-05-06 08:58:33 +00002911 unsigned DiagID = diag::warn_impcast_integer_sign;
2912
2913 // Traditionally, gcc has warned about this under -Wsign-compare.
2914 // We also want to warn about it in -Wconversion.
2915 // So if -Wconversion is off, use a completely identical diagnostic
2916 // in the sign-compare group.
2917 // The conditional-checking code will
2918 if (ICContext) {
2919 DiagID = diag::warn_impcast_integer_sign_conditional;
2920 *ICContext = true;
2921 }
2922
John McCallacf0ee52010-10-08 02:01:28 +00002923 return DiagnoseImpCast(S, E, T, CC, DiagID);
John McCall263a48b2010-01-04 23:31:57 +00002924 }
2925
Douglas Gregora78f1932011-02-22 02:45:07 +00002926 // Diagnose conversions between different enumeration types.
Douglas Gregor364f7db2011-03-12 00:14:31 +00002927 // In C, we pretend that the type of an EnumConstantDecl is its enumeration
2928 // type, to give us better diagnostics.
2929 QualType SourceType = E->getType();
2930 if (!S.getLangOptions().CPlusPlus) {
2931 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2932 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
2933 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
2934 SourceType = S.Context.getTypeDeclType(Enum);
2935 Source = S.Context.getCanonicalType(SourceType).getTypePtr();
2936 }
2937 }
2938
Douglas Gregora78f1932011-02-22 02:45:07 +00002939 if (const EnumType *SourceEnum = Source->getAs<EnumType>())
2940 if (const EnumType *TargetEnum = Target->getAs<EnumType>())
2941 if ((SourceEnum->getDecl()->getIdentifier() ||
2942 SourceEnum->getDecl()->getTypedefForAnonDecl()) &&
2943 (TargetEnum->getDecl()->getIdentifier() ||
2944 TargetEnum->getDecl()->getTypedefForAnonDecl()) &&
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002945 SourceEnum != TargetEnum) {
2946 if (isFromSystemMacro(S, CC))
2947 return;
2948
Douglas Gregor364f7db2011-03-12 00:14:31 +00002949 return DiagnoseImpCast(S, E, SourceType, T, CC,
Douglas Gregora78f1932011-02-22 02:45:07 +00002950 diag::warn_impcast_different_enum_types);
Ted Kremenek4c0826c2011-03-10 20:03:42 +00002951 }
Douglas Gregora78f1932011-02-22 02:45:07 +00002952
John McCall263a48b2010-01-04 23:31:57 +00002953 return;
2954}
2955
John McCallcc7e5bf2010-05-06 08:58:33 +00002956void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T);
2957
2958void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
John McCallacf0ee52010-10-08 02:01:28 +00002959 SourceLocation CC, bool &ICContext) {
John McCallcc7e5bf2010-05-06 08:58:33 +00002960 E = E->IgnoreParenImpCasts();
2961
2962 if (isa<ConditionalOperator>(E))
2963 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), T);
2964
John McCallacf0ee52010-10-08 02:01:28 +00002965 AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002966 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00002967 return CheckImplicitConversion(S, E, T, CC, &ICContext);
John McCallcc7e5bf2010-05-06 08:58:33 +00002968 return;
2969}
2970
2971void CheckConditionalOperator(Sema &S, ConditionalOperator *E, QualType T) {
John McCallacf0ee52010-10-08 02:01:28 +00002972 SourceLocation CC = E->getQuestionLoc();
2973
2974 AnalyzeImplicitConversions(S, E->getCond(), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00002975
2976 bool Suspicious = false;
John McCallacf0ee52010-10-08 02:01:28 +00002977 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious);
2978 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002979
2980 // If -Wconversion would have warned about either of the candidates
2981 // for a signedness conversion to the context type...
2982 if (!Suspicious) return;
2983
2984 // ...but it's currently ignored...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002985 if (S.Diags.getDiagnosticLevel(diag::warn_impcast_integer_sign_conditional,
2986 CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00002987 return;
2988
2989 // ...and -Wsign-compare isn't...
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00002990 if (!S.Diags.getDiagnosticLevel(diag::warn_mixed_sign_conditional, CC))
John McCallcc7e5bf2010-05-06 08:58:33 +00002991 return;
2992
2993 // ...then check whether it would have warned about either of the
2994 // candidates for a signedness conversion to the condition type.
2995 if (E->getType() != T) {
2996 Suspicious = false;
2997 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00002998 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00002999 if (!Suspicious)
3000 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
John McCallacf0ee52010-10-08 02:01:28 +00003001 E->getType(), CC, &Suspicious);
John McCallcc7e5bf2010-05-06 08:58:33 +00003002 if (!Suspicious)
3003 return;
3004 }
3005
3006 // If so, emit a diagnostic under -Wsign-compare.
3007 Expr *lex = E->getTrueExpr()->IgnoreParenImpCasts();
3008 Expr *rex = E->getFalseExpr()->IgnoreParenImpCasts();
3009 S.Diag(E->getQuestionLoc(), diag::warn_mixed_sign_conditional)
3010 << lex->getType() << rex->getType()
3011 << lex->getSourceRange() << rex->getSourceRange();
3012}
3013
3014/// AnalyzeImplicitConversions - Find and report any interesting
3015/// implicit conversions in the given expression. There are a couple
3016/// of competing diagnostics here, -Wconversion and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003017void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003018 QualType T = OrigE->getType();
3019 Expr *E = OrigE->IgnoreParenImpCasts();
3020
3021 // For conditional operators, we analyze the arguments as if they
3022 // were being fed directly into the output.
3023 if (isa<ConditionalOperator>(E)) {
3024 ConditionalOperator *CO = cast<ConditionalOperator>(E);
3025 CheckConditionalOperator(S, CO, T);
3026 return;
3027 }
3028
3029 // Go ahead and check any implicit conversions we might have skipped.
3030 // The non-canonical typecheck is just an optimization;
3031 // CheckImplicitConversion will filter out dead implicit conversions.
3032 if (E->getType() != T)
John McCallacf0ee52010-10-08 02:01:28 +00003033 CheckImplicitConversion(S, E, T, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003034
3035 // Now continue drilling into this expression.
3036
3037 // Skip past explicit casts.
3038 if (isa<ExplicitCastExpr>(E)) {
3039 E = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreParenImpCasts();
John McCallacf0ee52010-10-08 02:01:28 +00003040 return AnalyzeImplicitConversions(S, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003041 }
3042
John McCalld2a53122010-11-09 23:24:47 +00003043 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3044 // Do a somewhat different check with comparison operators.
3045 if (BO->isComparisonOp())
3046 return AnalyzeComparison(S, BO);
3047
3048 // And with assignments and compound assignments.
3049 if (BO->isAssignmentOp())
3050 return AnalyzeAssignment(S, BO);
3051 }
John McCallcc7e5bf2010-05-06 08:58:33 +00003052
3053 // These break the otherwise-useful invariant below. Fortunately,
3054 // we don't really need to recurse into them, because any internal
3055 // expressions should have been analyzed already when they were
3056 // built into statements.
3057 if (isa<StmtExpr>(E)) return;
3058
3059 // Don't descend into unevaluated contexts.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003060 if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
John McCallcc7e5bf2010-05-06 08:58:33 +00003061
3062 // Now just recurse over the expression's children.
John McCallacf0ee52010-10-08 02:01:28 +00003063 CC = E->getExprLoc();
John McCall8322c3a2011-02-13 04:07:26 +00003064 for (Stmt::child_range I = E->children(); I; ++I)
John McCallacf0ee52010-10-08 02:01:28 +00003065 AnalyzeImplicitConversions(S, cast<Expr>(*I), CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003066}
3067
3068} // end anonymous namespace
3069
3070/// Diagnoses "dangerous" implicit conversions within the given
3071/// expression (which is a full expression). Implements -Wconversion
3072/// and -Wsign-compare.
John McCallacf0ee52010-10-08 02:01:28 +00003073///
3074/// \param CC the "context" location of the implicit conversion, i.e.
3075/// the most location of the syntactic entity requiring the implicit
3076/// conversion
3077void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
John McCallcc7e5bf2010-05-06 08:58:33 +00003078 // Don't diagnose in unevaluated contexts.
3079 if (ExprEvalContexts.back().Context == Sema::Unevaluated)
3080 return;
3081
3082 // Don't diagnose for value- or type-dependent expressions.
3083 if (E->isTypeDependent() || E->isValueDependent())
3084 return;
3085
John McCallacf0ee52010-10-08 02:01:28 +00003086 // This is not the right CC for (e.g.) a variable initialization.
3087 AnalyzeImplicitConversions(*this, E, CC);
John McCallcc7e5bf2010-05-06 08:58:33 +00003088}
3089
John McCall1f425642010-11-11 03:21:53 +00003090void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
3091 FieldDecl *BitField,
3092 Expr *Init) {
3093 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
3094}
3095
Mike Stump0c2ec772010-01-21 03:59:47 +00003096/// CheckParmsForFunctionDef - Check that the parameters of the given
3097/// function are appropriate for the definition of a function. This
3098/// takes care of any checks that cannot be performed on the
3099/// declaration itself, e.g., that the types of each of the function
3100/// parameters are complete.
Douglas Gregorb524d902010-11-01 18:37:59 +00003101bool Sema::CheckParmsForFunctionDef(ParmVarDecl **P, ParmVarDecl **PEnd,
3102 bool CheckParameterNames) {
Mike Stump0c2ec772010-01-21 03:59:47 +00003103 bool HasInvalidParm = false;
Douglas Gregorb524d902010-11-01 18:37:59 +00003104 for (; P != PEnd; ++P) {
3105 ParmVarDecl *Param = *P;
3106
Mike Stump0c2ec772010-01-21 03:59:47 +00003107 // C99 6.7.5.3p4: the parameters in a parameter type list in a
3108 // function declarator that is part of a function definition of
3109 // that function shall not have incomplete type.
3110 //
3111 // This is also C++ [dcl.fct]p6.
3112 if (!Param->isInvalidDecl() &&
3113 RequireCompleteType(Param->getLocation(), Param->getType(),
3114 diag::err_typecheck_decl_incomplete_type)) {
3115 Param->setInvalidDecl();
3116 HasInvalidParm = true;
3117 }
3118
3119 // C99 6.9.1p5: If the declarator includes a parameter type list, the
3120 // declaration of each parameter shall include an identifier.
Douglas Gregorb524d902010-11-01 18:37:59 +00003121 if (CheckParameterNames &&
3122 Param->getIdentifier() == 0 &&
Mike Stump0c2ec772010-01-21 03:59:47 +00003123 !Param->isImplicit() &&
3124 !getLangOptions().CPlusPlus)
3125 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Sam Weinigdeb55d52010-02-01 05:02:49 +00003126
3127 // C99 6.7.5.3p12:
3128 // If the function declarator is not part of a definition of that
3129 // function, parameters may have incomplete type and may use the [*]
3130 // notation in their sequences of declarator specifiers to specify
3131 // variable length array types.
3132 QualType PType = Param->getOriginalType();
3133 if (const ArrayType *AT = Context.getAsArrayType(PType)) {
3134 if (AT->getSizeModifier() == ArrayType::Star) {
3135 // FIXME: This diagnosic should point the the '[*]' if source-location
3136 // information is added for it.
3137 Diag(Param->getLocation(), diag::err_array_star_in_function_definition);
3138 }
3139 }
Mike Stump0c2ec772010-01-21 03:59:47 +00003140 }
3141
3142 return HasInvalidParm;
3143}
John McCall2b5c1b22010-08-12 21:44:57 +00003144
3145/// CheckCastAlign - Implements -Wcast-align, which warns when a
3146/// pointer cast increases the alignment requirements.
3147void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
3148 // This is actually a lot of work to potentially be doing on every
3149 // cast; don't do it if we're ignoring -Wcast_align (as is the default).
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00003150 if (getDiagnostics().getDiagnosticLevel(diag::warn_cast_align,
3151 TRange.getBegin())
John McCall2b5c1b22010-08-12 21:44:57 +00003152 == Diagnostic::Ignored)
3153 return;
3154
3155 // Ignore dependent types.
3156 if (T->isDependentType() || Op->getType()->isDependentType())
3157 return;
3158
3159 // Require that the destination be a pointer type.
3160 const PointerType *DestPtr = T->getAs<PointerType>();
3161 if (!DestPtr) return;
3162
3163 // If the destination has alignment 1, we're done.
3164 QualType DestPointee = DestPtr->getPointeeType();
3165 if (DestPointee->isIncompleteType()) return;
3166 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
3167 if (DestAlign.isOne()) return;
3168
3169 // Require that the source be a pointer type.
3170 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
3171 if (!SrcPtr) return;
3172 QualType SrcPointee = SrcPtr->getPointeeType();
3173
3174 // Whitelist casts from cv void*. We already implicitly
3175 // whitelisted casts to cv void*, since they have alignment 1.
3176 // Also whitelist casts involving incomplete types, which implicitly
3177 // includes 'void'.
3178 if (SrcPointee->isIncompleteType()) return;
3179
3180 CharUnits SrcAlign = Context.getTypeAlignInChars(SrcPointee);
3181 if (SrcAlign >= DestAlign) return;
3182
3183 Diag(TRange.getBegin(), diag::warn_cast_align)
3184 << Op->getType() << T
3185 << static_cast<unsigned>(SrcAlign.getQuantity())
3186 << static_cast<unsigned>(DestAlign.getQuantity())
3187 << TRange << Op->getSourceRange();
3188}
3189
Ted Kremenekdf26df72011-03-01 18:41:00 +00003190static void CheckArrayAccess_Check(Sema &S,
3191 const clang::ArraySubscriptExpr *E) {
Chandler Carruth1af88f12011-02-17 21:10:52 +00003192 const Expr *BaseExpr = E->getBase()->IgnoreParenImpCasts();
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003193 const ConstantArrayType *ArrayTy =
Ted Kremenekdf26df72011-03-01 18:41:00 +00003194 S.Context.getAsConstantArrayType(BaseExpr->getType());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003195 if (!ArrayTy)
Ted Kremenek64699be2011-02-16 01:57:07 +00003196 return;
Chandler Carruth1af88f12011-02-17 21:10:52 +00003197
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003198 const Expr *IndexExpr = E->getIdx();
3199 if (IndexExpr->isValueDependent())
Ted Kremenek64699be2011-02-16 01:57:07 +00003200 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003201 llvm::APSInt index;
Ted Kremenekdf26df72011-03-01 18:41:00 +00003202 if (!IndexExpr->isIntegerConstantExpr(index, S.Context))
Ted Kremenek64699be2011-02-16 01:57:07 +00003203 return;
Ted Kremenek108b2d52011-02-16 04:01:44 +00003204
Ted Kremeneke4b316c2011-02-23 23:06:04 +00003205 if (index.isUnsigned() || !index.isNegative()) {
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003206 llvm::APInt size = ArrayTy->getSize();
Chandler Carruth1af88f12011-02-17 21:10:52 +00003207 if (!size.isStrictlyPositive())
3208 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003209 if (size.getBitWidth() > index.getBitWidth())
3210 index = index.sext(size.getBitWidth());
Ted Kremeneka7ced2c2011-02-18 02:27:00 +00003211 else if (size.getBitWidth() < index.getBitWidth())
3212 size = size.sext(index.getBitWidth());
3213
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003214 if (index.slt(size))
Ted Kremenek108b2d52011-02-16 04:01:44 +00003215 return;
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003216
Ted Kremenekdf26df72011-03-01 18:41:00 +00003217 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3218 S.PDiag(diag::warn_array_index_exceeds_bounds)
3219 << index.toString(10, true)
3220 << size.toString(10, true)
3221 << IndexExpr->getSourceRange());
Chandler Carruth2a666fc2011-02-17 20:55:08 +00003222 } else {
Ted Kremenekdf26df72011-03-01 18:41:00 +00003223 S.DiagRuntimeBehavior(E->getBase()->getLocStart(), BaseExpr,
3224 S.PDiag(diag::warn_array_index_precedes_bounds)
3225 << index.toString(10, true)
3226 << IndexExpr->getSourceRange());
Ted Kremenek64699be2011-02-16 01:57:07 +00003227 }
Chandler Carruth1af88f12011-02-17 21:10:52 +00003228
3229 const NamedDecl *ND = NULL;
3230 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
3231 ND = dyn_cast<NamedDecl>(DRE->getDecl());
3232 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
3233 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
3234 if (ND)
Ted Kremenekdf26df72011-03-01 18:41:00 +00003235 S.DiagRuntimeBehavior(ND->getLocStart(), BaseExpr,
3236 S.PDiag(diag::note_array_index_out_of_bounds)
3237 << ND->getDeclName());
Ted Kremenek64699be2011-02-16 01:57:07 +00003238}
3239
Ted Kremenekdf26df72011-03-01 18:41:00 +00003240void Sema::CheckArrayAccess(const Expr *expr) {
3241 while (true)
3242 switch (expr->getStmtClass()) {
3243 case Stmt::ParenExprClass:
3244 expr = cast<ParenExpr>(expr)->getSubExpr();
3245 continue;
3246 case Stmt::ArraySubscriptExprClass:
3247 CheckArrayAccess_Check(*this, cast<ArraySubscriptExpr>(expr));
3248 return;
3249 case Stmt::ConditionalOperatorClass: {
3250 const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
3251 if (const Expr *lhs = cond->getLHS())
3252 CheckArrayAccess(lhs);
3253 if (const Expr *rhs = cond->getRHS())
3254 CheckArrayAccess(rhs);
3255 return;
3256 }
3257 default:
3258 return;
3259 }
3260}