blob: c0499fac141b35d839c82a320df9ffacd10b9cba [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor::EvaluateDirectiveExpression method,
11// which parses and evaluates integer constant expressions for #if directives.
12//
13//===----------------------------------------------------------------------===//
14//
15// FIXME: implement testing for #assert's.
16//
17//===----------------------------------------------------------------------===//
18
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/MacroInfo.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000023#include "clang/Basic/Diagnostic.h"
24#include "llvm/ADT/APSInt.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000025using namespace clang;
26
Chris Lattner8ed30442008-05-05 06:45:50 +000027/// PPValue - Represents the value of a subexpression of a preprocessor
28/// conditional and the source range covered by it.
29class PPValue {
30 SourceRange Range;
31public:
32 llvm::APSInt Val;
33
34 // Default ctor - Construct an 'invalid' PPValue.
35 PPValue(unsigned BitWidth) : Val(BitWidth) {}
36
37 unsigned getBitWidth() const { return Val.getBitWidth(); }
38 bool isUnsigned() const { return Val.isUnsigned(); }
39
40 const SourceRange &getRange() const { return Range; }
41
42 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
43 void setRange(SourceLocation B, SourceLocation E) {
44 Range.setBegin(B); Range.setEnd(E);
45 }
46 void setBegin(SourceLocation L) { Range.setBegin(L); }
47 void setEnd(SourceLocation L) { Range.setEnd(L); }
48};
49
50static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +000051 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +000052 Preprocessor &PP);
53
54/// DefinedTracker - This struct is used while parsing expressions to keep track
55/// of whether !defined(X) has been seen.
56///
57/// With this simple scheme, we handle the basic forms:
58/// !defined(X) and !defined X
59/// but we also trivially handle (silly) stuff like:
60/// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
61struct DefinedTracker {
62 /// Each time a Value is evaluated, it returns information about whether the
63 /// parsed value is of the form defined(X), !defined(X) or is something else.
64 enum TrackerState {
65 DefinedMacro, // defined(X)
66 NotDefinedMacro, // !defined(X)
67 Unknown // Something else.
68 } State;
69 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
70 /// indicates the macro that was checked.
71 IdentifierInfo *TheMacro;
72};
73
Reid Spencer5f016e22007-07-11 17:01:13 +000074/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
75/// return the computed value in Result. Return true if there was an error
76/// parsing. This function also returns information about the form of the
77/// expression in DT. See above for information on what DT means.
78///
79/// If ValueLive is false, then this value is being evaluated in a context where
80/// the result is not used. As such, avoid diagnostics that relate to
81/// evaluation.
Chris Lattner8ed30442008-05-05 06:45:50 +000082static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
83 bool ValueLive, Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +000084 DT.State = DefinedTracker::Unknown;
85
86 // If this token's spelling is a pp-identifier, check to see if it is
87 // 'defined' or if it is a macro. Note that we check here because many
88 // keywords are pp-identifiers, so we can't check the kind.
89 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
90 // If this identifier isn't 'defined' and it wasn't macro expanded, it turns
91 // into a simple 0, unless it is the C++ keyword "true", in which case it
92 // turns into "1".
93 if (II->getPPKeywordID() != tok::pp_defined) {
Chris Lattner116a4b12008-01-23 17:19:46 +000094 PP.Diag(PeekTok, diag::warn_pp_undef_identifier, II->getName());
Chris Lattner8ed30442008-05-05 06:45:50 +000095 Result.Val = II->getTokenID() == tok::kw_true;
96 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
97 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +000098 PP.LexNonComment(PeekTok);
99 return false;
100 }
101
102 // Handle "defined X" and "defined(X)".
Chris Lattner8ed30442008-05-05 06:45:50 +0000103 Result.setBegin(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000104
105 // Get the next token, don't expand it.
106 PP.LexUnexpandedToken(PeekTok);
107
108 // Two options, it can either be a pp-identifier or a (.
Chris Lattner8ed30442008-05-05 06:45:50 +0000109 SourceLocation LParenLoc;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000110 if (PeekTok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 // Found a paren, remember we saw it and skip it.
Chris Lattner8ed30442008-05-05 06:45:50 +0000112 LParenLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 PP.LexUnexpandedToken(PeekTok);
114 }
115
116 // If we don't have a pp-identifier now, this is an error.
117 if ((II = PeekTok.getIdentifierInfo()) == 0) {
118 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
119 return true;
120 }
121
122 // Otherwise, we got an identifier, is it defined to something?
Chris Lattner8ed30442008-05-05 06:45:50 +0000123 Result.Val = II->hasMacroDefinition();
124 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
Reid Spencer5f016e22007-07-11 17:01:13 +0000125
126 // If there is a macro, mark it used.
Chris Lattner8ed30442008-05-05 06:45:50 +0000127 if (Result.Val != 0 && ValueLive) {
Chris Lattnercc1a8752007-10-07 08:44:20 +0000128 MacroInfo *Macro = PP.getMacroInfo(II);
Chris Lattner0edde552007-10-07 08:04:56 +0000129 Macro->setIsUsed(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000130 }
131
132 // Consume identifier.
Chris Lattner8ed30442008-05-05 06:45:50 +0000133 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000134 PP.LexNonComment(PeekTok);
135
136 // If we are in parens, ensure we have a trailing ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000137 if (LParenLoc.isValid()) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000138 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000139 PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen);
140 PP.Diag(LParenLoc, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 return true;
142 }
143 // Consume the ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000144 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 PP.LexNonComment(PeekTok);
146 }
147
148 // Success, remember that we saw defined(X).
149 DT.State = DefinedTracker::DefinedMacro;
150 DT.TheMacro = II;
151 return false;
152 }
153
154 switch (PeekTok.getKind()) {
155 default: // Non-value token.
Chris Lattnerd98d9752008-04-13 20:38:43 +0000156 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 return true;
158 case tok::eom:
159 case tok::r_paren:
160 // If there is no expression, report and exit.
161 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
162 return true;
163 case tok::numeric_constant: {
164 llvm::SmallString<64> IntegerBuffer;
165 IntegerBuffer.resize(PeekTok.getLength());
166 const char *ThisTokBegin = &IntegerBuffer[0];
167 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
168 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
169 PeekTok.getLocation(), PP);
170 if (Literal.hadError)
171 return true; // a diagnostic was already reported.
172
Chris Lattner6e400c22007-08-26 03:29:23 +0000173 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
175 return true;
176 }
177 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
178
Neil Boothb9449512007-08-29 22:00:19 +0000179 // long long is a C99 feature.
180 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000181 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000182 PP.Diag(PeekTok, diag::ext_longlong);
183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 // Parse the integer literal into Result.
Chris Lattner8ed30442008-05-05 06:45:50 +0000185 if (Literal.GetIntegerValue(Result.Val)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Overflow parsing integer literal.
187 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
Chris Lattner8ed30442008-05-05 06:45:50 +0000188 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000189 } else {
190 // Set the signedness of the result to match whether there was a U suffix
191 // or not.
Chris Lattner8ed30442008-05-05 06:45:50 +0000192 Result.Val.setIsUnsigned(Literal.isUnsigned);
Reid Spencer5f016e22007-07-11 17:01:13 +0000193
194 // Detect overflow based on whether the value is signed. If signed
195 // and if the value is too large, emit a warning "integer constant is so
196 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
197 // is 64-bits.
Chris Lattner8ed30442008-05-05 06:45:50 +0000198 if (!Literal.isUnsigned && Result.Val.isNegative()) {
Chris Lattnerb081a352008-07-03 03:47:30 +0000199 // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
200 if (ValueLive && Literal.getRadix() != 16)
Chris Lattner8ed30442008-05-05 06:45:50 +0000201 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
202 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000203 }
204 }
205
206 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000207 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 PP.LexNonComment(PeekTok);
209 return false;
210 }
211 case tok::char_constant: { // 'x'
212 llvm::SmallString<32> CharBuffer;
213 CharBuffer.resize(PeekTok.getLength());
214 const char *ThisTokBegin = &CharBuffer[0];
215 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
216 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
217 PeekTok.getLocation(), PP);
218 if (Literal.hadError())
219 return true; // A diagnostic was already emitted.
220
221 // Character literals are always int or wchar_t, expand to intmax_t.
222 TargetInfo &TI = PP.getTargetInfo();
Chris Lattner98be4942008-03-05 18:54:05 +0000223 unsigned NumBits = TI.getCharWidth(Literal.isWide());
Reid Spencer5f016e22007-07-11 17:01:13 +0000224
225 // Set the width.
226 llvm::APSInt Val(NumBits);
227 // Set the value.
228 Val = Literal.getValue();
229 // Set the signedness.
Chris Lattner98be4942008-03-05 18:54:05 +0000230 Val.setIsUnsigned(!TI.isCharSigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000231
Chris Lattner8ed30442008-05-05 06:45:50 +0000232 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
233 Result.Val = Val.extend(Result.Val.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000235 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 "intmax_t smaller than char/wchar_t?");
Chris Lattner8ed30442008-05-05 06:45:50 +0000237 Result.Val = Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000238 }
239
240 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000241 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 PP.LexNonComment(PeekTok);
243 return false;
244 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000245 case tok::l_paren: {
246 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000247 PP.LexNonComment(PeekTok); // Eat the (.
248 // Parse the value and if there are any binary operators involved, parse
249 // them.
250 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
251
252 // If this is a silly value like (X), which doesn't need parens, check for
253 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000254 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 // Just use DT unmodified as our result.
256 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000257 // Otherwise, we have something like (x+y), and we consumed '(x'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000258 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
259 return true;
260
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000261 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000262 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen,
263 Result.getRange());
264 PP.Diag(Start, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000265 return true;
266 }
267 DT.State = DefinedTracker::Unknown;
268 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000269 Result.setRange(Start, PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000270 PP.LexNonComment(PeekTok); // Eat the ).
271 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000272 }
273 case tok::plus: {
274 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000275 // Unary plus doesn't modify the value.
276 PP.LexNonComment(PeekTok);
Chris Lattner8ed30442008-05-05 06:45:50 +0000277 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
278 Result.setBegin(Start);
279 return false;
280 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000281 case tok::minus: {
282 SourceLocation Loc = PeekTok.getLocation();
283 PP.LexNonComment(PeekTok);
284 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000285 Result.setBegin(Loc);
286
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000288 Result.Val = -Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000289
Chris Lattnerb081a352008-07-03 03:47:30 +0000290 // -MININT is the only thing that overflows. Unsigned never overflows.
291 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
Reid Spencer5f016e22007-07-11 17:01:13 +0000292
293 // If this operator is live and overflowed, report the issue.
294 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000295 PP.Diag(Loc, diag::warn_pp_expr_overflow, Result.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000296
297 DT.State = DefinedTracker::Unknown;
298 return false;
299 }
300
Chris Lattner8ed30442008-05-05 06:45:50 +0000301 case tok::tilde: {
302 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000303 PP.LexNonComment(PeekTok);
304 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000305 Result.setBegin(Start);
306
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000308 Result.Val = ~Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 DT.State = DefinedTracker::Unknown;
310 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000311 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000312
Chris Lattner8ed30442008-05-05 06:45:50 +0000313 case tok::exclaim: {
314 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000315 PP.LexNonComment(PeekTok);
316 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000317 Result.setBegin(Start);
318 Result.Val = !Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
Chris Lattner8ed30442008-05-05 06:45:50 +0000320 Result.Val.setIsUnsigned(false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000321
322 if (DT.State == DefinedTracker::DefinedMacro)
323 DT.State = DefinedTracker::NotDefinedMacro;
324 else if (DT.State == DefinedTracker::NotDefinedMacro)
325 DT.State = DefinedTracker::DefinedMacro;
326 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000327 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000328
329 // FIXME: Handle #assert
330 }
331}
332
333
334
335/// getPrecedence - Return the precedence of the specified binary operator
336/// token. This returns:
337/// ~0 - Invalid token.
Chris Lattner9e66ba62008-05-05 04:10:51 +0000338/// 14 -> 3 - various operators.
339/// 0 - 'eom' or ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000340static unsigned getPrecedence(tok::TokenKind Kind) {
341 switch (Kind) {
342 default: return ~0U;
343 case tok::percent:
344 case tok::slash:
345 case tok::star: return 14;
346 case tok::plus:
347 case tok::minus: return 13;
348 case tok::lessless:
349 case tok::greatergreater: return 12;
350 case tok::lessequal:
351 case tok::less:
352 case tok::greaterequal:
353 case tok::greater: return 11;
354 case tok::exclaimequal:
355 case tok::equalequal: return 10;
356 case tok::amp: return 9;
357 case tok::caret: return 8;
358 case tok::pipe: return 7;
359 case tok::ampamp: return 6;
360 case tok::pipepipe: return 5;
Chris Lattner98ed49f2008-05-05 20:07:41 +0000361 case tok::question: return 4;
362 case tok::comma: return 3;
Chris Lattner91891562008-05-04 18:36:18 +0000363 case tok::colon: return 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000364 case tok::r_paren: return 0; // Lowest priority, end of expr.
365 case tok::eom: return 0; // Lowest priority, end of macro.
366 }
367}
368
369
370/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
Chris Lattner8ed30442008-05-05 06:45:50 +0000371/// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000372///
373/// If ValueLive is false, then this value is being evaluated in a context where
374/// the result is not used. As such, avoid diagnostics that relate to
Chris Lattner8ed30442008-05-05 06:45:50 +0000375/// evaluation, such as division by zero warnings.
376static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000377 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000378 Preprocessor &PP) {
379 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
380 // If this token isn't valid, report the error.
381 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000382 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
383 LHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000384 return true;
385 }
386
387 while (1) {
388 // If this token has a lower precedence than we are allowed to parse, return
389 // it so that higher levels of the recursion can parse it.
390 if (PeekPrec < MinPrec)
391 return false;
392
393 tok::TokenKind Operator = PeekTok.getKind();
394
395 // If this is a short-circuiting operator, see if the RHS of the operator is
396 // dead. Note that this cannot just clobber ValueLive. Consider
397 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
398 // this example, the RHS of the && being dead does not make the rest of the
399 // expr dead.
400 bool RHSIsLive;
Chris Lattner8ed30442008-05-05 06:45:50 +0000401 if (Operator == tok::ampamp && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000402 RHSIsLive = false; // RHS of "0 && x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000403 else if (Operator == tok::pipepipe && LHS.Val != 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 RHSIsLive = false; // RHS of "1 || x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000405 else if (Operator == tok::question && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
407 else
408 RHSIsLive = ValueLive;
409
Chris Lattner8ed30442008-05-05 06:45:50 +0000410 // Consume the operator, remembering the operator's location for reporting.
411 SourceLocation OpLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000412 PP.LexNonComment(PeekTok);
413
Chris Lattner8ed30442008-05-05 06:45:50 +0000414 PPValue RHS(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // Parse the RHS of the operator.
416 DefinedTracker DT;
417 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
418
419 // Remember the precedence of this operator and get the precedence of the
420 // operator immediately to the right of the RHS.
421 unsigned ThisPrec = PeekPrec;
422 PeekPrec = getPrecedence(PeekTok.getKind());
423
424 // If this token isn't valid, report the error.
425 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000426 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
427 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000428 return true;
429 }
430
Chris Lattner98ed49f2008-05-05 20:07:41 +0000431 // Decide whether to include the next binop in this subexpression. For
432 // example, when parsing x+y*z and looking at '*', we want to recursively
Chris Lattner44cbbb02008-05-05 20:09:27 +0000433 // handle y*z as a single subexpression. We do this because the precedence
434 // of * is higher than that of +. The only strange case we have to handle
435 // here is for the ?: operator, where the precedence is actually lower than
436 // the LHS of the '?'. The grammar rule is:
Chris Lattner98ed49f2008-05-05 20:07:41 +0000437 //
438 // conditional-expression ::=
439 // logical-OR-expression ? expression : conditional-expression
440 // where 'expression' is actually comma-expression.
441 unsigned RHSPrec;
442 if (Operator == tok::question)
443 // The RHS of "?" should be maximally consumed as an expression.
444 RHSPrec = getPrecedence(tok::comma);
445 else // All others should munch while higher precedence.
446 RHSPrec = ThisPrec+1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000447
Chris Lattner98ed49f2008-05-05 20:07:41 +0000448 if (PeekPrec >= RHSPrec) {
449 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 return true;
451 PeekPrec = getPrecedence(PeekTok.getKind());
452 }
453 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
454
455 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
Chris Lattner019ef7e2008-05-04 23:46:17 +0000456 // either operand is unsigned.
Reid Spencer5f016e22007-07-11 17:01:13 +0000457 llvm::APSInt Res(LHS.getBitWidth());
Chris Lattner019ef7e2008-05-04 23:46:17 +0000458 switch (Operator) {
459 case tok::question: // No UAC for x and y in "x ? y : z".
460 case tok::lessless: // Shift amount doesn't UAC with shift value.
461 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
462 case tok::comma: // Comma operands are not subject to UACs.
463 case tok::pipepipe: // Logical || does not do UACs.
464 case tok::ampamp: // Logical && does not do UACs.
465 break; // No UAC
466 default:
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
468 // If this just promoted something from signed to unsigned, and if the
469 // value was negative, warn about it.
470 if (ValueLive && Res.isUnsigned()) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000471 if (!LHS.isUnsigned() && LHS.Val.isNegative())
472 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive,
473 LHS.Val.toStringSigned() + " to "+LHS.Val.toStringUnsigned(),
474 LHS.getRange(), RHS.getRange());
475 if (!RHS.isUnsigned() && RHS.Val.isNegative())
476 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive,
477 RHS.Val.toStringSigned() + " to "+RHS.Val.toStringUnsigned(),
478 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000480 LHS.Val.setIsUnsigned(Res.isUnsigned());
481 RHS.Val.setIsUnsigned(Res.isUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 }
483
484 // FIXME: All of these should detect and report overflow??
485 bool Overflow = false;
486 switch (Operator) {
487 default: assert(0 && "Unknown operator token!");
488 case tok::percent:
Chris Lattner8ed30442008-05-05 06:45:50 +0000489 if (RHS.Val != 0)
490 Res = LHS.Val % RHS.Val;
491 else if (ValueLive) {
492 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero, LHS.getRange(),
493 RHS.getRange());
494 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000496 break;
497 case tok::slash:
Chris Lattner8ed30442008-05-05 06:45:50 +0000498 if (RHS.Val != 0) {
499 Res = LHS.Val / RHS.Val;
500 if (LHS.Val.isSigned()) // MININT/-1 --> overflow.
501 Overflow = LHS.Val.isMinSignedValue() && RHS.Val.isAllOnesValue();
502 } else if (ValueLive) {
503 PP.Diag(OpLoc, diag::err_pp_division_by_zero, LHS.getRange(),
504 RHS.getRange());
505 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 break;
Chris Lattner3b691152008-05-04 07:15:21 +0000508
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 case tok::star:
Chris Lattner8ed30442008-05-05 06:45:50 +0000510 Res = LHS.Val * RHS.Val;
511 if (LHS.Val != 0 && RHS.Val != 0)
512 Overflow = Res/RHS.Val != LHS.Val || Res/LHS.Val != RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 break;
514 case tok::lessless: {
515 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000516 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
517 if (ShAmt >= LHS.Val.getBitWidth())
518 Overflow = true, ShAmt = LHS.Val.getBitWidth()-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 else if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000520 Overflow = ShAmt > LHS.Val.countLeadingZeros();
521 else if (LHS.Val.isNonNegative()) // Don't allow sign change.
522 Overflow = ShAmt >= LHS.Val.countLeadingZeros();
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 else
Chris Lattner8ed30442008-05-05 06:45:50 +0000524 Overflow = ShAmt >= LHS.Val.countLeadingOnes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000525
Chris Lattner8ed30442008-05-05 06:45:50 +0000526 Res = LHS.Val << ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 break;
528 }
529 case tok::greatergreater: {
530 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000531 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000532 if (ShAmt >= LHS.getBitWidth())
533 Overflow = true, ShAmt = LHS.getBitWidth()-1;
Chris Lattner8ed30442008-05-05 06:45:50 +0000534 Res = LHS.Val >> ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 break;
536 }
537 case tok::plus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000538 Res = LHS.Val + RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000540 Overflow = Res.ult(LHS.Val);
541 else if (LHS.Val.isNonNegative() == RHS.Val.isNonNegative() &&
542 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 Overflow = true; // Overflow for signed addition.
544 break;
545 case tok::minus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000546 Res = LHS.Val - RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000548 Overflow = Res.ugt(LHS.Val);
549 else if (LHS.Val.isNonNegative() != RHS.Val.isNonNegative() &&
550 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 Overflow = true; // Overflow for signed subtraction.
552 break;
553 case tok::lessequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000554 Res = LHS.Val <= RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
556 break;
557 case tok::less:
Chris Lattner8ed30442008-05-05 06:45:50 +0000558 Res = LHS.Val < RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000559 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
560 break;
561 case tok::greaterequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000562 Res = LHS.Val >= RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
564 break;
565 case tok::greater:
Chris Lattner8ed30442008-05-05 06:45:50 +0000566 Res = LHS.Val > RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
568 break;
569 case tok::exclaimequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000570 Res = LHS.Val != RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000571 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
572 break;
573 case tok::equalequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000574 Res = LHS.Val == RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
576 break;
577 case tok::amp:
Chris Lattner8ed30442008-05-05 06:45:50 +0000578 Res = LHS.Val & RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 break;
580 case tok::caret:
Chris Lattner8ed30442008-05-05 06:45:50 +0000581 Res = LHS.Val ^ RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 break;
583 case tok::pipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000584 Res = LHS.Val | RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 break;
586 case tok::ampamp:
Chris Lattner8ed30442008-05-05 06:45:50 +0000587 Res = (LHS.Val != 0 && RHS.Val != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
589 break;
590 case tok::pipepipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000591 Res = (LHS.Val != 0 || RHS.Val != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000592 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
593 break;
594 case tok::comma:
Chris Lattner91891562008-05-04 18:36:18 +0000595 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
596 // if not being evaluated.
597 if (!PP.getLangOptions().C99 || ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000598 PP.Diag(OpLoc, diag::ext_pp_comma_expr, LHS.getRange(), RHS.getRange());
599 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000600 break;
601 case tok::question: {
602 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000603 if (PeekTok.isNot(tok::colon)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000604 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon,
605 LHS.getRange(), RHS.getRange());
606 PP.Diag(OpLoc, diag::err_matching, "?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 return true;
608 }
609 // Consume the :.
610 PP.LexNonComment(PeekTok);
611
612 // Evaluate the value after the :.
Chris Lattner8ed30442008-05-05 06:45:50 +0000613 bool AfterColonLive = ValueLive && LHS.Val == 0;
614 PPValue AfterColonVal(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000615 DefinedTracker DT;
616 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
617 return true;
618
Chris Lattner44cbbb02008-05-05 20:09:27 +0000619 // Parse anything after the : with the same precedence as ?. We allow
620 // things of equal precedence because ?: is right associative.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000621 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 PeekTok, AfterColonLive, PP))
623 return true;
624
625 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
Chris Lattner8ed30442008-05-05 06:45:50 +0000626 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
627 RHS.setEnd(AfterColonVal.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000628
629 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
630 // either operand is unsigned.
631 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
632
633 // Figure out the precedence of the token after the : part.
634 PeekPrec = getPrecedence(PeekTok.getKind());
635 break;
636 }
637 case tok::colon:
638 // Don't allow :'s to float around without being part of ?: exprs.
Chris Lattner8ed30442008-05-05 06:45:50 +0000639 PP.Diag(OpLoc, diag::err_pp_colon_without_question, LHS.getRange(),
640 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 return true;
642 }
643
644 // If this operator is live and overflowed, report the issue.
645 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000646 PP.Diag(OpLoc, diag::warn_pp_expr_overflow,
647 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000648
649 // Put the result back into 'LHS' for our next iteration.
Chris Lattner8ed30442008-05-05 06:45:50 +0000650 LHS.Val = Res;
651 LHS.setEnd(RHS.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 }
653
654 return false;
655}
656
657/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
658/// may occur after a #if or #elif directive. If the expression is equivalent
659/// to "!defined(X)" return X in IfNDefMacro.
660bool Preprocessor::
661EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
662 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000663 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 Lex(Tok);
665
666 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000667 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000668
Chris Lattner8ed30442008-05-05 06:45:50 +0000669 PPValue ResVal(BitWidth);
Reid Spencer5f016e22007-07-11 17:01:13 +0000670 DefinedTracker DT;
671 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
672 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000673 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 DiscardUntilEndOfDirective();
675 return false;
676 }
677
678 // If we are at the end of the expression after just parsing a value, there
679 // must be no (unparenthesized) binary operators involved, so we can exit
680 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000681 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 // If the expression we parsed was of the form !defined(macro), return the
683 // macro in IfNDefMacro.
684 if (DT.State == DefinedTracker::NotDefinedMacro)
685 IfNDefMacro = DT.TheMacro;
686
Chris Lattner8ed30442008-05-05 06:45:50 +0000687 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 }
689
690 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
691 // operator and the stuff after it.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000692 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
693 Tok, true, *this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000694 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000695 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000696 DiscardUntilEndOfDirective();
697 return false;
698 }
699
700 // If we aren't at the tok::eom token, something bad happened, like an extra
701 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000702 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 Diag(Tok, diag::err_pp_expected_eol);
704 DiscardUntilEndOfDirective();
705 }
706
Chris Lattner8ed30442008-05-05 06:45:50 +0000707 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000708}
709