blob: 9fda8b086241434cedfe1e3614c421452e58afb0 [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"
23#include "clang/Basic/TokenKinds.h"
24#include "clang/Basic/Diagnostic.h"
25#include "llvm/ADT/APSInt.h"
26#include "llvm/ADT/SmallString.h"
27using namespace clang;
28
29static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +000030 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +000031 Preprocessor &PP);
32
33/// DefinedTracker - This struct is used while parsing expressions to keep track
34/// of whether !defined(X) has been seen.
35///
36/// With this simple scheme, we handle the basic forms:
37/// !defined(X) and !defined X
38/// but we also trivially handle (silly) stuff like:
39/// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
40struct DefinedTracker {
41 /// Each time a Value is evaluated, it returns information about whether the
42 /// parsed value is of the form defined(X), !defined(X) or is something else.
43 enum TrackerState {
44 DefinedMacro, // defined(X)
45 NotDefinedMacro, // !defined(X)
46 Unknown // Something else.
47 } State;
48 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
49 /// indicates the macro that was checked.
50 IdentifierInfo *TheMacro;
51};
52
53
54
55/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
56/// return the computed value in Result. Return true if there was an error
57/// parsing. This function also returns information about the form of the
58/// expression in DT. See above for information on what DT means.
59///
60/// If ValueLive is false, then this value is being evaluated in a context where
61/// the result is not used. As such, avoid diagnostics that relate to
62/// evaluation.
Chris Lattnerd2177732007-07-20 16:59:19 +000063static bool EvaluateValue(llvm::APSInt &Result, Token &PeekTok,
Reid Spencer5f016e22007-07-11 17:01:13 +000064 DefinedTracker &DT, bool ValueLive,
65 Preprocessor &PP) {
66 Result = 0;
67 DT.State = DefinedTracker::Unknown;
68
69 // If this token's spelling is a pp-identifier, check to see if it is
70 // 'defined' or if it is a macro. Note that we check here because many
71 // keywords are pp-identifiers, so we can't check the kind.
72 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
73 // If this identifier isn't 'defined' and it wasn't macro expanded, it turns
74 // into a simple 0, unless it is the C++ keyword "true", in which case it
75 // turns into "1".
76 if (II->getPPKeywordID() != tok::pp_defined) {
Chris Lattner116a4b12008-01-23 17:19:46 +000077 PP.Diag(PeekTok, diag::warn_pp_undef_identifier, II->getName());
Reid Spencer5f016e22007-07-11 17:01:13 +000078 Result = II->getTokenID() == tok::kw_true;
79 Result.setIsUnsigned(false); // "0" is signed intmax_t 0.
80 PP.LexNonComment(PeekTok);
81 return false;
82 }
83
84 // Handle "defined X" and "defined(X)".
85
86 // Get the next token, don't expand it.
87 PP.LexUnexpandedToken(PeekTok);
88
89 // Two options, it can either be a pp-identifier or a (.
90 bool InParens = false;
Chris Lattner22f6bbc2007-10-09 18:02:16 +000091 if (PeekTok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +000092 // Found a paren, remember we saw it and skip it.
93 InParens = true;
94 PP.LexUnexpandedToken(PeekTok);
95 }
96
97 // If we don't have a pp-identifier now, this is an error.
98 if ((II = PeekTok.getIdentifierInfo()) == 0) {
99 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
100 return true;
101 }
102
103 // Otherwise, we got an identifier, is it defined to something?
Chris Lattner0edde552007-10-07 08:04:56 +0000104 Result = II->hasMacroDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 Result.setIsUnsigned(false); // Result is signed intmax_t.
106
107 // If there is a macro, mark it used.
108 if (Result != 0 && ValueLive) {
Chris Lattnercc1a8752007-10-07 08:44:20 +0000109 MacroInfo *Macro = PP.getMacroInfo(II);
Chris Lattner0edde552007-10-07 08:04:56 +0000110 Macro->setIsUsed(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000111 }
112
113 // Consume identifier.
114 PP.LexNonComment(PeekTok);
115
116 // If we are in parens, ensure we have a trailing ).
117 if (InParens) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000118 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000119 PP.Diag(PeekTok, diag::err_pp_missing_rparen);
120 return true;
121 }
122 // Consume the ).
123 PP.LexNonComment(PeekTok);
124 }
125
126 // Success, remember that we saw defined(X).
127 DT.State = DefinedTracker::DefinedMacro;
128 DT.TheMacro = II;
129 return false;
130 }
131
132 switch (PeekTok.getKind()) {
133 default: // Non-value token.
Chris Lattnerd98d9752008-04-13 20:38:43 +0000134 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000135 return true;
136 case tok::eom:
137 case tok::r_paren:
138 // If there is no expression, report and exit.
139 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
140 return true;
141 case tok::numeric_constant: {
142 llvm::SmallString<64> IntegerBuffer;
143 IntegerBuffer.resize(PeekTok.getLength());
144 const char *ThisTokBegin = &IntegerBuffer[0];
145 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
146 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
147 PeekTok.getLocation(), PP);
148 if (Literal.hadError)
149 return true; // a diagnostic was already reported.
150
Chris Lattner6e400c22007-08-26 03:29:23 +0000151 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
153 return true;
154 }
155 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
156
Neil Boothb9449512007-08-29 22:00:19 +0000157 // long long is a C99 feature.
158 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000159 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000160 PP.Diag(PeekTok, diag::ext_longlong);
161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 // Parse the integer literal into Result.
163 if (Literal.GetIntegerValue(Result)) {
164 // Overflow parsing integer literal.
165 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
166 Result.setIsUnsigned(true);
167 } else {
168 // Set the signedness of the result to match whether there was a U suffix
169 // or not.
170 Result.setIsUnsigned(Literal.isUnsigned);
171
172 // Detect overflow based on whether the value is signed. If signed
173 // and if the value is too large, emit a warning "integer constant is so
174 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
175 // is 64-bits.
176 if (!Literal.isUnsigned && Result.isNegative()) {
177 if (ValueLive)PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
178 Result.setIsUnsigned(true);
179 }
180 }
181
182 // Consume the token.
183 PP.LexNonComment(PeekTok);
184 return false;
185 }
186 case tok::char_constant: { // 'x'
187 llvm::SmallString<32> CharBuffer;
188 CharBuffer.resize(PeekTok.getLength());
189 const char *ThisTokBegin = &CharBuffer[0];
190 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
191 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
192 PeekTok.getLocation(), PP);
193 if (Literal.hadError())
194 return true; // A diagnostic was already emitted.
195
196 // Character literals are always int or wchar_t, expand to intmax_t.
197 TargetInfo &TI = PP.getTargetInfo();
Chris Lattner98be4942008-03-05 18:54:05 +0000198 unsigned NumBits = TI.getCharWidth(Literal.isWide());
Reid Spencer5f016e22007-07-11 17:01:13 +0000199
200 // Set the width.
201 llvm::APSInt Val(NumBits);
202 // Set the value.
203 Val = Literal.getValue();
204 // Set the signedness.
Chris Lattner98be4942008-03-05 18:54:05 +0000205 Val.setIsUnsigned(!TI.isCharSigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000206
207 if (Result.getBitWidth() > Val.getBitWidth()) {
Chris Lattner98be4942008-03-05 18:54:05 +0000208 Result = Val.extend(Result.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 } else {
210 assert(Result.getBitWidth() == Val.getBitWidth() &&
211 "intmax_t smaller than char/wchar_t?");
212 Result = Val;
213 }
214
215 // Consume the token.
216 PP.LexNonComment(PeekTok);
217 return false;
218 }
219 case tok::l_paren:
220 PP.LexNonComment(PeekTok); // Eat the (.
221 // Parse the value and if there are any binary operators involved, parse
222 // them.
223 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
224
225 // If this is a silly value like (X), which doesn't need parens, check for
226 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000227 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000228 // Just use DT unmodified as our result.
229 } else {
230 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
231 return true;
232
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000233 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000234 PP.Diag(PeekTok, diag::err_pp_expected_rparen);
235 return true;
236 }
237 DT.State = DefinedTracker::Unknown;
238 }
239 PP.LexNonComment(PeekTok); // Eat the ).
240 return false;
241
242 case tok::plus:
243 // Unary plus doesn't modify the value.
244 PP.LexNonComment(PeekTok);
245 return EvaluateValue(Result, PeekTok, DT, ValueLive, PP);
246 case tok::minus: {
247 SourceLocation Loc = PeekTok.getLocation();
248 PP.LexNonComment(PeekTok);
249 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
250 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
251 Result = -Result;
252
253 bool Overflow = false;
254 if (Result.isUnsigned())
Dan Gohman376605b2008-02-13 22:09:49 +0000255 Overflow = Result.isNegative();
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 else if (Result.isMinSignedValue())
257 Overflow = true; // -MININT is the only thing that overflows.
258
259 // If this operator is live and overflowed, report the issue.
260 if (Overflow && ValueLive)
261 PP.Diag(Loc, diag::warn_pp_expr_overflow);
262
263 DT.State = DefinedTracker::Unknown;
264 return false;
265 }
266
267 case tok::tilde:
268 PP.LexNonComment(PeekTok);
269 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
270 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
271 Result = ~Result;
272 DT.State = DefinedTracker::Unknown;
273 return false;
274
275 case tok::exclaim:
276 PP.LexNonComment(PeekTok);
277 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
278 Result = !Result;
279 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
280 Result.setIsUnsigned(false);
281
282 if (DT.State == DefinedTracker::DefinedMacro)
283 DT.State = DefinedTracker::NotDefinedMacro;
284 else if (DT.State == DefinedTracker::NotDefinedMacro)
285 DT.State = DefinedTracker::DefinedMacro;
286 return false;
287
288 // FIXME: Handle #assert
289 }
290}
291
292
293
294/// getPrecedence - Return the precedence of the specified binary operator
295/// token. This returns:
296/// ~0 - Invalid token.
297/// 14 - *,/,%
298/// 13 - -,+
299/// 12 - <<,>>
300/// 11 - >=, <=, >, <
301/// 10 - ==, !=
302/// 9 - &
303/// 8 - ^
304/// 7 - |
305/// 6 - &&
306/// 5 - ||
307/// 4 - ?
308/// 3 - :
309/// 0 - eom, )
310static unsigned getPrecedence(tok::TokenKind Kind) {
311 switch (Kind) {
312 default: return ~0U;
313 case tok::percent:
314 case tok::slash:
315 case tok::star: return 14;
316 case tok::plus:
317 case tok::minus: return 13;
318 case tok::lessless:
319 case tok::greatergreater: return 12;
320 case tok::lessequal:
321 case tok::less:
322 case tok::greaterequal:
323 case tok::greater: return 11;
324 case tok::exclaimequal:
325 case tok::equalequal: return 10;
326 case tok::amp: return 9;
327 case tok::caret: return 8;
328 case tok::pipe: return 7;
329 case tok::ampamp: return 6;
330 case tok::pipepipe: return 5;
Chris Lattner91891562008-05-04 18:36:18 +0000331 case tok::comma: return 4;
332 case tok::question: return 3;
333 case tok::colon: return 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 case tok::r_paren: return 0; // Lowest priority, end of expr.
335 case tok::eom: return 0; // Lowest priority, end of macro.
336 }
337}
338
339
340/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
341/// PeekTok, and whose precedence is PeekPrec.
342///
343/// If ValueLive is false, then this value is being evaluated in a context where
344/// the result is not used. As such, avoid diagnostics that relate to
345/// evaluation.
346static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000347 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 Preprocessor &PP) {
349 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
350 // If this token isn't valid, report the error.
351 if (PeekPrec == ~0U) {
Chris Lattnerd98d9752008-04-13 20:38:43 +0000352 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_binop);
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 return true;
354 }
355
356 while (1) {
357 // If this token has a lower precedence than we are allowed to parse, return
358 // it so that higher levels of the recursion can parse it.
359 if (PeekPrec < MinPrec)
360 return false;
361
362 tok::TokenKind Operator = PeekTok.getKind();
363
364 // If this is a short-circuiting operator, see if the RHS of the operator is
365 // dead. Note that this cannot just clobber ValueLive. Consider
366 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
367 // this example, the RHS of the && being dead does not make the rest of the
368 // expr dead.
369 bool RHSIsLive;
370 if (Operator == tok::ampamp && LHS == 0)
371 RHSIsLive = false; // RHS of "0 && x" is dead.
372 else if (Operator == tok::pipepipe && LHS != 0)
373 RHSIsLive = false; // RHS of "1 || x" is dead.
374 else if (Operator == tok::question && LHS == 0)
375 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
376 else
377 RHSIsLive = ValueLive;
378
379 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000380 Token OpToken = PeekTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000381 PP.LexNonComment(PeekTok);
382
383 llvm::APSInt RHS(LHS.getBitWidth());
384 // Parse the RHS of the operator.
385 DefinedTracker DT;
386 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
387
388 // Remember the precedence of this operator and get the precedence of the
389 // operator immediately to the right of the RHS.
390 unsigned ThisPrec = PeekPrec;
391 PeekPrec = getPrecedence(PeekTok.getKind());
392
393 // If this token isn't valid, report the error.
394 if (PeekPrec == ~0U) {
Chris Lattnerd98d9752008-04-13 20:38:43 +0000395 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_binop);
Reid Spencer5f016e22007-07-11 17:01:13 +0000396 return true;
397 }
398
399 bool isRightAssoc = Operator == tok::question;
400
401 // Get the precedence of the operator to the right of the RHS. If it binds
402 // more tightly with RHS than we do, evaluate it completely first.
403 if (ThisPrec < PeekPrec ||
404 (ThisPrec == PeekPrec && isRightAssoc)) {
405 if (EvaluateDirectiveSubExpr(RHS, ThisPrec+1, PeekTok, RHSIsLive, PP))
406 return true;
407 PeekPrec = getPrecedence(PeekTok.getKind());
408 }
409 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
410
411 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
Chris Lattner019ef7e2008-05-04 23:46:17 +0000412 // either operand is unsigned.
Reid Spencer5f016e22007-07-11 17:01:13 +0000413 llvm::APSInt Res(LHS.getBitWidth());
Chris Lattner019ef7e2008-05-04 23:46:17 +0000414 switch (Operator) {
415 case tok::question: // No UAC for x and y in "x ? y : z".
416 case tok::lessless: // Shift amount doesn't UAC with shift value.
417 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
418 case tok::comma: // Comma operands are not subject to UACs.
419 case tok::pipepipe: // Logical || does not do UACs.
420 case tok::ampamp: // Logical && does not do UACs.
421 break; // No UAC
422 default:
Reid Spencer5f016e22007-07-11 17:01:13 +0000423 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
424 // If this just promoted something from signed to unsigned, and if the
425 // value was negative, warn about it.
426 if (ValueLive && Res.isUnsigned()) {
427 if (!LHS.isUnsigned() && LHS.isNegative())
428 PP.Diag(OpToken, diag::warn_pp_convert_lhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000429 LHS.toStringSigned() + " to " + LHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000430 if (!RHS.isUnsigned() && RHS.isNegative())
431 PP.Diag(OpToken, diag::warn_pp_convert_rhs_to_positive,
Chris Lattnerb2024b22007-08-23 05:22:10 +0000432 RHS.toStringSigned() + " to " + RHS.toStringUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 }
434 LHS.setIsUnsigned(Res.isUnsigned());
435 RHS.setIsUnsigned(Res.isUnsigned());
436 }
437
438 // FIXME: All of these should detect and report overflow??
439 bool Overflow = false;
440 switch (Operator) {
441 default: assert(0 && "Unknown operator token!");
442 case tok::percent:
443 if (RHS == 0) {
Chris Lattner3b691152008-05-04 07:15:21 +0000444 if (ValueLive) {
445 PP.Diag(OpToken, diag::err_pp_remainder_by_zero);
446 return true;
447 }
448 } else {
449 Res = LHS % RHS;
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 break;
452 case tok::slash:
453 if (RHS == 0) {
Chris Lattner3b691152008-05-04 07:15:21 +0000454 if (ValueLive) {
455 PP.Diag(OpToken, diag::err_pp_division_by_zero);
456 return true;
457 }
458 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 }
Chris Lattner3b691152008-05-04 07:15:21 +0000460
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 Res = LHS / RHS;
462 if (LHS.isSigned())
463 Overflow = LHS.isMinSignedValue() && RHS.isAllOnesValue(); // MININT/-1
464 break;
Chris Lattner3b691152008-05-04 07:15:21 +0000465
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 case tok::star:
467 Res = LHS * RHS;
468 if (LHS != 0 && RHS != 0)
469 Overflow = Res/RHS != LHS || Res/LHS != RHS;
470 break;
471 case tok::lessless: {
472 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000473 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 if (ShAmt >= LHS.getBitWidth())
475 Overflow = true, ShAmt = LHS.getBitWidth()-1;
476 else if (LHS.isUnsigned())
477 Overflow = ShAmt > LHS.countLeadingZeros();
Dan Gohman376605b2008-02-13 22:09:49 +0000478 else if (LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 Overflow = ShAmt >= LHS.countLeadingZeros(); // Don't allow sign change.
480 else
481 Overflow = ShAmt >= LHS.countLeadingOnes();
482
483 Res = LHS << ShAmt;
484 break;
485 }
486 case tok::greatergreater: {
487 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000488 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 if (ShAmt >= LHS.getBitWidth())
490 Overflow = true, ShAmt = LHS.getBitWidth()-1;
491 Res = LHS >> ShAmt;
492 break;
493 }
494 case tok::plus:
495 Res = LHS + RHS;
496 if (LHS.isUnsigned())
497 Overflow = Res.ult(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000498 else if (LHS.isNonNegative() == RHS.isNonNegative() &&
499 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 Overflow = true; // Overflow for signed addition.
501 break;
502 case tok::minus:
503 Res = LHS - RHS;
504 if (LHS.isUnsigned())
505 Overflow = Res.ugt(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000506 else if (LHS.isNonNegative() != RHS.isNonNegative() &&
507 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 Overflow = true; // Overflow for signed subtraction.
509 break;
510 case tok::lessequal:
511 Res = LHS <= RHS;
512 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
513 break;
514 case tok::less:
515 Res = LHS < RHS;
516 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
517 break;
518 case tok::greaterequal:
519 Res = LHS >= RHS;
520 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
521 break;
522 case tok::greater:
523 Res = LHS > RHS;
524 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
525 break;
526 case tok::exclaimequal:
527 Res = LHS != RHS;
528 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
529 break;
530 case tok::equalequal:
531 Res = LHS == RHS;
532 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
533 break;
534 case tok::amp:
535 Res = LHS & RHS;
536 break;
537 case tok::caret:
538 Res = LHS ^ RHS;
539 break;
540 case tok::pipe:
541 Res = LHS | RHS;
542 break;
543 case tok::ampamp:
544 Res = (LHS != 0 && RHS != 0);
545 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
546 break;
547 case tok::pipepipe:
548 Res = (LHS != 0 || RHS != 0);
549 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
550 break;
551 case tok::comma:
Chris Lattner91891562008-05-04 18:36:18 +0000552 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
553 // if not being evaluated.
554 if (!PP.getLangOptions().C99 || ValueLive)
555 PP.Diag(OpToken, diag::ext_pp_comma_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000556 Res = RHS; // LHS = LHS,RHS -> RHS.
557 break;
558 case tok::question: {
559 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000560 if (PeekTok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000561 PP.Diag(OpToken, diag::err_pp_question_without_colon);
562 return true;
563 }
564 // Consume the :.
565 PP.LexNonComment(PeekTok);
566
567 // Evaluate the value after the :.
568 bool AfterColonLive = ValueLive && LHS == 0;
569 llvm::APSInt AfterColonVal(LHS.getBitWidth());
570 DefinedTracker DT;
571 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
572 return true;
573
574 // Parse anything after the : RHS that has a higher precedence than ?.
575 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec+1,
576 PeekTok, AfterColonLive, PP))
577 return true;
578
579 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
580 Res = LHS != 0 ? RHS : AfterColonVal;
581
582 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
583 // either operand is unsigned.
584 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
585
586 // Figure out the precedence of the token after the : part.
587 PeekPrec = getPrecedence(PeekTok.getKind());
588 break;
589 }
590 case tok::colon:
591 // Don't allow :'s to float around without being part of ?: exprs.
592 PP.Diag(OpToken, diag::err_pp_colon_without_question);
593 return true;
594 }
595
596 // If this operator is live and overflowed, report the issue.
597 if (Overflow && ValueLive)
598 PP.Diag(OpToken, diag::warn_pp_expr_overflow);
599
600 // Put the result back into 'LHS' for our next iteration.
601 LHS = Res;
602 }
603
604 return false;
605}
606
607/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
608/// may occur after a #if or #elif directive. If the expression is equivalent
609/// to "!defined(X)" return X in IfNDefMacro.
610bool Preprocessor::
611EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
612 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000613 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 Lex(Tok);
615
616 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000617 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000618
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 llvm::APSInt ResVal(BitWidth);
620 DefinedTracker DT;
621 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
622 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000623 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000624 DiscardUntilEndOfDirective();
625 return false;
626 }
627
628 // If we are at the end of the expression after just parsing a value, there
629 // must be no (unparenthesized) binary operators involved, so we can exit
630 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000631 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 // If the expression we parsed was of the form !defined(macro), return the
633 // macro in IfNDefMacro.
634 if (DT.State == DefinedTracker::NotDefinedMacro)
635 IfNDefMacro = DT.TheMacro;
636
637 return ResVal != 0;
638 }
639
640 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
641 // operator and the stuff after it.
642 if (EvaluateDirectiveSubExpr(ResVal, 1, Tok, true, *this)) {
643 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000644 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 DiscardUntilEndOfDirective();
646 return false;
647 }
648
649 // If we aren't at the tok::eom token, something bad happened, like an extra
650 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000651 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 Diag(Tok, diag::err_pp_expected_eol);
653 DiscardUntilEndOfDirective();
654 }
655
656 return ResVal != 0;
657}
658