blob: c56692e1f47bfeecd55e7d79c8a920c47183b9c7 [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.
134 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
135 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();
198 unsigned NumBits;
199 if (Literal.isWide())
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000200 NumBits = TI.getWCharWidth(PP.getFullLoc(PeekTok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 else
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000202 NumBits = TI.getCharWidth(PP.getFullLoc(PeekTok.getLocation()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000203
204 // Set the width.
205 llvm::APSInt Val(NumBits);
206 // Set the value.
207 Val = Literal.getValue();
208 // Set the signedness.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000209 Val.setIsUnsigned(!TI.isCharSigned(PP.getFullLoc(PeekTok.getLocation())));
Reid Spencer5f016e22007-07-11 17:01:13 +0000210
211 if (Result.getBitWidth() > Val.getBitWidth()) {
212 if (Val.isSigned())
213 Result = Val.sext(Result.getBitWidth());
214 else
215 Result = Val.zext(Result.getBitWidth());
216 Result.setIsUnsigned(Val.isUnsigned());
217 } else {
218 assert(Result.getBitWidth() == Val.getBitWidth() &&
219 "intmax_t smaller than char/wchar_t?");
220 Result = Val;
221 }
222
223 // Consume the token.
224 PP.LexNonComment(PeekTok);
225 return false;
226 }
227 case tok::l_paren:
228 PP.LexNonComment(PeekTok); // Eat the (.
229 // Parse the value and if there are any binary operators involved, parse
230 // them.
231 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
232
233 // If this is a silly value like (X), which doesn't need parens, check for
234 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000235 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000236 // Just use DT unmodified as our result.
237 } else {
238 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
239 return true;
240
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000241 if (PeekTok.isNot(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000242 PP.Diag(PeekTok, diag::err_pp_expected_rparen);
243 return true;
244 }
245 DT.State = DefinedTracker::Unknown;
246 }
247 PP.LexNonComment(PeekTok); // Eat the ).
248 return false;
249
250 case tok::plus:
251 // Unary plus doesn't modify the value.
252 PP.LexNonComment(PeekTok);
253 return EvaluateValue(Result, PeekTok, DT, ValueLive, PP);
254 case tok::minus: {
255 SourceLocation Loc = PeekTok.getLocation();
256 PP.LexNonComment(PeekTok);
257 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
258 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
259 Result = -Result;
260
261 bool Overflow = false;
262 if (Result.isUnsigned())
Dan Gohman376605b2008-02-13 22:09:49 +0000263 Overflow = Result.isNegative();
Reid Spencer5f016e22007-07-11 17:01:13 +0000264 else if (Result.isMinSignedValue())
265 Overflow = true; // -MININT is the only thing that overflows.
266
267 // If this operator is live and overflowed, report the issue.
268 if (Overflow && ValueLive)
269 PP.Diag(Loc, diag::warn_pp_expr_overflow);
270
271 DT.State = DefinedTracker::Unknown;
272 return false;
273 }
274
275 case tok::tilde:
276 PP.LexNonComment(PeekTok);
277 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
278 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
279 Result = ~Result;
280 DT.State = DefinedTracker::Unknown;
281 return false;
282
283 case tok::exclaim:
284 PP.LexNonComment(PeekTok);
285 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
286 Result = !Result;
287 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
288 Result.setIsUnsigned(false);
289
290 if (DT.State == DefinedTracker::DefinedMacro)
291 DT.State = DefinedTracker::NotDefinedMacro;
292 else if (DT.State == DefinedTracker::NotDefinedMacro)
293 DT.State = DefinedTracker::DefinedMacro;
294 return false;
295
296 // FIXME: Handle #assert
297 }
298}
299
300
301
302/// getPrecedence - Return the precedence of the specified binary operator
303/// token. This returns:
304/// ~0 - Invalid token.
305/// 14 - *,/,%
306/// 13 - -,+
307/// 12 - <<,>>
308/// 11 - >=, <=, >, <
309/// 10 - ==, !=
310/// 9 - &
311/// 8 - ^
312/// 7 - |
313/// 6 - &&
314/// 5 - ||
315/// 4 - ?
316/// 3 - :
317/// 0 - eom, )
318static unsigned getPrecedence(tok::TokenKind Kind) {
319 switch (Kind) {
320 default: return ~0U;
321 case tok::percent:
322 case tok::slash:
323 case tok::star: return 14;
324 case tok::plus:
325 case tok::minus: return 13;
326 case tok::lessless:
327 case tok::greatergreater: return 12;
328 case tok::lessequal:
329 case tok::less:
330 case tok::greaterequal:
331 case tok::greater: return 11;
332 case tok::exclaimequal:
333 case tok::equalequal: return 10;
334 case tok::amp: return 9;
335 case tok::caret: return 8;
336 case tok::pipe: return 7;
337 case tok::ampamp: return 6;
338 case tok::pipepipe: return 5;
339 case tok::question: return 4;
340 case tok::colon: return 3;
341 case tok::comma: return 2;
342 case tok::r_paren: return 0; // Lowest priority, end of expr.
343 case tok::eom: return 0; // Lowest priority, end of macro.
344 }
345}
346
347
348/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
349/// PeekTok, and whose precedence is PeekPrec.
350///
351/// If ValueLive is false, then this value is being evaluated in a context where
352/// the result is not used. As such, avoid diagnostics that relate to
353/// evaluation.
354static bool EvaluateDirectiveSubExpr(llvm::APSInt &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000355 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000356 Preprocessor &PP) {
357 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
358 // If this token isn't valid, report the error.
359 if (PeekPrec == ~0U) {
360 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
361 return true;
362 }
363
364 while (1) {
365 // If this token has a lower precedence than we are allowed to parse, return
366 // it so that higher levels of the recursion can parse it.
367 if (PeekPrec < MinPrec)
368 return false;
369
370 tok::TokenKind Operator = PeekTok.getKind();
371
372 // If this is a short-circuiting operator, see if the RHS of the operator is
373 // dead. Note that this cannot just clobber ValueLive. Consider
374 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
375 // this example, the RHS of the && being dead does not make the rest of the
376 // expr dead.
377 bool RHSIsLive;
378 if (Operator == tok::ampamp && LHS == 0)
379 RHSIsLive = false; // RHS of "0 && x" is dead.
380 else if (Operator == tok::pipepipe && LHS != 0)
381 RHSIsLive = false; // RHS of "1 || x" is dead.
382 else if (Operator == tok::question && LHS == 0)
383 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
384 else
385 RHSIsLive = ValueLive;
386
387 // Consume the operator, saving the operator token for error reporting.
Chris Lattnerd2177732007-07-20 16:59:19 +0000388 Token OpToken = PeekTok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000389 PP.LexNonComment(PeekTok);
390
391 llvm::APSInt RHS(LHS.getBitWidth());
392 // Parse the RHS of the operator.
393 DefinedTracker DT;
394 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
395
396 // Remember the precedence of this operator and get the precedence of the
397 // operator immediately to the right of the RHS.
398 unsigned ThisPrec = PeekPrec;
399 PeekPrec = getPrecedence(PeekTok.getKind());
400
401 // If this token isn't valid, report the error.
402 if (PeekPrec == ~0U) {
403 PP.Diag(PeekTok, diag::err_pp_expr_bad_token);
404 return true;
405 }
406
407 bool isRightAssoc = Operator == tok::question;
408
409 // Get the precedence of the operator to the right of the RHS. If it binds
410 // more tightly with RHS than we do, evaluate it completely first.
411 if (ThisPrec < PeekPrec ||
412 (ThisPrec == PeekPrec && isRightAssoc)) {
413 if (EvaluateDirectiveSubExpr(RHS, ThisPrec+1, PeekTok, RHSIsLive, PP))
414 return true;
415 PeekPrec = getPrecedence(PeekTok.getKind());
416 }
417 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
418
419 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
420 // either operand is unsigned. Don't do this for x and y in "x ? y : z".
421 llvm::APSInt Res(LHS.getBitWidth());
422 if (Operator != tok::question) {
423 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) {
444 if (ValueLive) PP.Diag(OpToken, diag::err_pp_remainder_by_zero);
445 return true;
446 }
447 Res = LHS % RHS;
448 break;
449 case tok::slash:
450 if (RHS == 0) {
451 if (ValueLive) PP.Diag(OpToken, diag::err_pp_division_by_zero);
452 return true;
453 }
454 Res = LHS / RHS;
455 if (LHS.isSigned())
456 Overflow = LHS.isMinSignedValue() && RHS.isAllOnesValue(); // MININT/-1
457 break;
458 case tok::star:
459 Res = LHS * RHS;
460 if (LHS != 0 && RHS != 0)
461 Overflow = Res/RHS != LHS || Res/LHS != RHS;
462 break;
463 case tok::lessless: {
464 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000465 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000466 if (ShAmt >= LHS.getBitWidth())
467 Overflow = true, ShAmt = LHS.getBitWidth()-1;
468 else if (LHS.isUnsigned())
469 Overflow = ShAmt > LHS.countLeadingZeros();
Dan Gohman376605b2008-02-13 22:09:49 +0000470 else if (LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 Overflow = ShAmt >= LHS.countLeadingZeros(); // Don't allow sign change.
472 else
473 Overflow = ShAmt >= LHS.countLeadingOnes();
474
475 Res = LHS << ShAmt;
476 break;
477 }
478 case tok::greatergreater: {
479 // Determine whether overflow is about to happen.
Chris Lattner701e5eb2007-09-04 02:45:27 +0000480 unsigned ShAmt = static_cast<unsigned>(RHS.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000481 if (ShAmt >= LHS.getBitWidth())
482 Overflow = true, ShAmt = LHS.getBitWidth()-1;
483 Res = LHS >> ShAmt;
484 break;
485 }
486 case tok::plus:
487 Res = LHS + RHS;
488 if (LHS.isUnsigned())
489 Overflow = Res.ult(LHS);
Dan Gohman376605b2008-02-13 22:09:49 +0000490 else if (LHS.isNonNegative() == RHS.isNonNegative() &&
491 Res.isNonNegative() != LHS.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 Overflow = true; // Overflow for signed addition.
493 break;
494 case tok::minus:
495 Res = LHS - RHS;
496 if (LHS.isUnsigned())
497 Overflow = Res.ugt(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 subtraction.
501 break;
502 case tok::lessequal:
503 Res = LHS <= RHS;
504 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
505 break;
506 case tok::less:
507 Res = LHS < RHS;
508 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
509 break;
510 case tok::greaterequal:
511 Res = LHS >= RHS;
512 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
513 break;
514 case tok::greater:
515 Res = LHS > RHS;
516 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
517 break;
518 case tok::exclaimequal:
519 Res = LHS != RHS;
520 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
521 break;
522 case tok::equalequal:
523 Res = LHS == RHS;
524 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
525 break;
526 case tok::amp:
527 Res = LHS & RHS;
528 break;
529 case tok::caret:
530 Res = LHS ^ RHS;
531 break;
532 case tok::pipe:
533 Res = LHS | RHS;
534 break;
535 case tok::ampamp:
536 Res = (LHS != 0 && RHS != 0);
537 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
538 break;
539 case tok::pipepipe:
540 Res = (LHS != 0 || RHS != 0);
541 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
542 break;
543 case tok::comma:
544 PP.Diag(OpToken, diag::ext_pp_comma_expr);
545 Res = RHS; // LHS = LHS,RHS -> RHS.
546 break;
547 case tok::question: {
548 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000549 if (PeekTok.isNot(tok::colon)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000550 PP.Diag(OpToken, diag::err_pp_question_without_colon);
551 return true;
552 }
553 // Consume the :.
554 PP.LexNonComment(PeekTok);
555
556 // Evaluate the value after the :.
557 bool AfterColonLive = ValueLive && LHS == 0;
558 llvm::APSInt AfterColonVal(LHS.getBitWidth());
559 DefinedTracker DT;
560 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
561 return true;
562
563 // Parse anything after the : RHS that has a higher precedence than ?.
564 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec+1,
565 PeekTok, AfterColonLive, PP))
566 return true;
567
568 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
569 Res = LHS != 0 ? RHS : AfterColonVal;
570
571 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
572 // either operand is unsigned.
573 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
574
575 // Figure out the precedence of the token after the : part.
576 PeekPrec = getPrecedence(PeekTok.getKind());
577 break;
578 }
579 case tok::colon:
580 // Don't allow :'s to float around without being part of ?: exprs.
581 PP.Diag(OpToken, diag::err_pp_colon_without_question);
582 return true;
583 }
584
585 // If this operator is live and overflowed, report the issue.
586 if (Overflow && ValueLive)
587 PP.Diag(OpToken, diag::warn_pp_expr_overflow);
588
589 // Put the result back into 'LHS' for our next iteration.
590 LHS = Res;
591 }
592
593 return false;
594}
595
596/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
597/// may occur after a #if or #elif directive. If the expression is equivalent
598/// to "!defined(X)" return X in IfNDefMacro.
599bool Preprocessor::
600EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
601 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000602 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 Lex(Tok);
604
605 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000606 unsigned BitWidth =
607 getTargetInfo().getIntMaxTWidth(getFullLoc(Tok.getLocation()));
608
Reid Spencer5f016e22007-07-11 17:01:13 +0000609 llvm::APSInt ResVal(BitWidth);
610 DefinedTracker DT;
611 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
612 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000613 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 DiscardUntilEndOfDirective();
615 return false;
616 }
617
618 // If we are at the end of the expression after just parsing a value, there
619 // must be no (unparenthesized) binary operators involved, so we can exit
620 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000621 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000622 // If the expression we parsed was of the form !defined(macro), return the
623 // macro in IfNDefMacro.
624 if (DT.State == DefinedTracker::NotDefinedMacro)
625 IfNDefMacro = DT.TheMacro;
626
627 return ResVal != 0;
628 }
629
630 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
631 // operator and the stuff after it.
632 if (EvaluateDirectiveSubExpr(ResVal, 1, Tok, true, *this)) {
633 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000634 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 DiscardUntilEndOfDirective();
636 return false;
637 }
638
639 // If we aren't at the tok::eom token, something bad happened, like an extra
640 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000641 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 Diag(Tok, diag::err_pp_expected_eol);
643 DiscardUntilEndOfDirective();
644 }
645
646 return ResVal != 0;
647}
648