blob: 5f11df089368f22c045bb893de71d4b63e0eb747 [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
Chris Lattner8ed30442008-05-05 06:45:50 +000029/// PPValue - Represents the value of a subexpression of a preprocessor
30/// conditional and the source range covered by it.
31class PPValue {
32 SourceRange Range;
33public:
34 llvm::APSInt Val;
35
36 // Default ctor - Construct an 'invalid' PPValue.
37 PPValue(unsigned BitWidth) : Val(BitWidth) {}
38
39 unsigned getBitWidth() const { return Val.getBitWidth(); }
40 bool isUnsigned() const { return Val.isUnsigned(); }
41
42 const SourceRange &getRange() const { return Range; }
43
44 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
45 void setRange(SourceLocation B, SourceLocation E) {
46 Range.setBegin(B); Range.setEnd(E);
47 }
48 void setBegin(SourceLocation L) { Range.setBegin(L); }
49 void setEnd(SourceLocation L) { Range.setEnd(L); }
50};
51
52static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +000053 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +000054 Preprocessor &PP);
55
56/// DefinedTracker - This struct is used while parsing expressions to keep track
57/// of whether !defined(X) has been seen.
58///
59/// With this simple scheme, we handle the basic forms:
60/// !defined(X) and !defined X
61/// but we also trivially handle (silly) stuff like:
62/// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
63struct DefinedTracker {
64 /// Each time a Value is evaluated, it returns information about whether the
65 /// parsed value is of the form defined(X), !defined(X) or is something else.
66 enum TrackerState {
67 DefinedMacro, // defined(X)
68 NotDefinedMacro, // !defined(X)
69 Unknown // Something else.
70 } State;
71 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
72 /// indicates the macro that was checked.
73 IdentifierInfo *TheMacro;
74};
75
Reid Spencer5f016e22007-07-11 17:01:13 +000076/// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
77/// return the computed value in Result. Return true if there was an error
78/// parsing. This function also returns information about the form of the
79/// expression in DT. See above for information on what DT means.
80///
81/// If ValueLive is false, then this value is being evaluated in a context where
82/// the result is not used. As such, avoid diagnostics that relate to
83/// evaluation.
Chris Lattner8ed30442008-05-05 06:45:50 +000084static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
85 bool ValueLive, Preprocessor &PP) {
Reid Spencer5f016e22007-07-11 17:01:13 +000086 DT.State = DefinedTracker::Unknown;
87
88 // If this token's spelling is a pp-identifier, check to see if it is
89 // 'defined' or if it is a macro. Note that we check here because many
90 // keywords are pp-identifiers, so we can't check the kind.
91 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
92 // If this identifier isn't 'defined' and it wasn't macro expanded, it turns
93 // into a simple 0, unless it is the C++ keyword "true", in which case it
94 // turns into "1".
95 if (II->getPPKeywordID() != tok::pp_defined) {
Chris Lattner116a4b12008-01-23 17:19:46 +000096 PP.Diag(PeekTok, diag::warn_pp_undef_identifier, II->getName());
Chris Lattner8ed30442008-05-05 06:45:50 +000097 Result.Val = II->getTokenID() == tok::kw_true;
98 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
99 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 PP.LexNonComment(PeekTok);
101 return false;
102 }
103
104 // Handle "defined X" and "defined(X)".
Chris Lattner8ed30442008-05-05 06:45:50 +0000105 Result.setBegin(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000106
107 // Get the next token, don't expand it.
108 PP.LexUnexpandedToken(PeekTok);
109
110 // Two options, it can either be a pp-identifier or a (.
Chris Lattner8ed30442008-05-05 06:45:50 +0000111 SourceLocation LParenLoc;
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000112 if (PeekTok.is(tok::l_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000113 // Found a paren, remember we saw it and skip it.
Chris Lattner8ed30442008-05-05 06:45:50 +0000114 LParenLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000115 PP.LexUnexpandedToken(PeekTok);
116 }
117
118 // If we don't have a pp-identifier now, this is an error.
119 if ((II = PeekTok.getIdentifierInfo()) == 0) {
120 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
121 return true;
122 }
123
124 // Otherwise, we got an identifier, is it defined to something?
Chris Lattner8ed30442008-05-05 06:45:50 +0000125 Result.Val = II->hasMacroDefinition();
126 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
Reid Spencer5f016e22007-07-11 17:01:13 +0000127
128 // If there is a macro, mark it used.
Chris Lattner8ed30442008-05-05 06:45:50 +0000129 if (Result.Val != 0 && ValueLive) {
Chris Lattnercc1a8752007-10-07 08:44:20 +0000130 MacroInfo *Macro = PP.getMacroInfo(II);
Chris Lattner0edde552007-10-07 08:04:56 +0000131 Macro->setIsUsed(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000132 }
133
134 // Consume identifier.
Chris Lattner8ed30442008-05-05 06:45:50 +0000135 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000136 PP.LexNonComment(PeekTok);
137
138 // If we are in parens, ensure we have a trailing ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000139 if (LParenLoc.isValid()) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000140 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000141 PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen);
142 PP.Diag(LParenLoc, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000143 return true;
144 }
145 // Consume the ).
Chris Lattner8ed30442008-05-05 06:45:50 +0000146 Result.setEnd(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000147 PP.LexNonComment(PeekTok);
148 }
149
150 // Success, remember that we saw defined(X).
151 DT.State = DefinedTracker::DefinedMacro;
152 DT.TheMacro = II;
153 return false;
154 }
155
156 switch (PeekTok.getKind()) {
157 default: // Non-value token.
Chris Lattnerd98d9752008-04-13 20:38:43 +0000158 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000159 return true;
160 case tok::eom:
161 case tok::r_paren:
162 // If there is no expression, report and exit.
163 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
164 return true;
165 case tok::numeric_constant: {
166 llvm::SmallString<64> IntegerBuffer;
167 IntegerBuffer.resize(PeekTok.getLength());
168 const char *ThisTokBegin = &IntegerBuffer[0];
169 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
170 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
171 PeekTok.getLocation(), PP);
172 if (Literal.hadError)
173 return true; // a diagnostic was already reported.
174
Chris Lattner6e400c22007-08-26 03:29:23 +0000175 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000176 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
177 return true;
178 }
179 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
180
Neil Boothb9449512007-08-29 22:00:19 +0000181 // long long is a C99 feature.
182 if (!PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus0x
Neil Booth79859c32007-08-29 22:13:52 +0000183 && Literal.isLongLong)
Neil Boothb9449512007-08-29 22:00:19 +0000184 PP.Diag(PeekTok, diag::ext_longlong);
185
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 // Parse the integer literal into Result.
Chris Lattner8ed30442008-05-05 06:45:50 +0000187 if (Literal.GetIntegerValue(Result.Val)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 // Overflow parsing integer literal.
189 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
Chris Lattner8ed30442008-05-05 06:45:50 +0000190 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 } else {
192 // Set the signedness of the result to match whether there was a U suffix
193 // or not.
Chris Lattner8ed30442008-05-05 06:45:50 +0000194 Result.Val.setIsUnsigned(Literal.isUnsigned);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195
196 // Detect overflow based on whether the value is signed. If signed
197 // and if the value is too large, emit a warning "integer constant is so
198 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
199 // is 64-bits.
Chris Lattner8ed30442008-05-05 06:45:50 +0000200 if (!Literal.isUnsigned && Result.Val.isNegative()) {
201 if (ValueLive)
202 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
203 Result.Val.setIsUnsigned(true);
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 }
205 }
206
207 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000208 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 PP.LexNonComment(PeekTok);
210 return false;
211 }
212 case tok::char_constant: { // 'x'
213 llvm::SmallString<32> CharBuffer;
214 CharBuffer.resize(PeekTok.getLength());
215 const char *ThisTokBegin = &CharBuffer[0];
216 unsigned ActualLength = PP.getSpelling(PeekTok, ThisTokBegin);
217 CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
218 PeekTok.getLocation(), PP);
219 if (Literal.hadError())
220 return true; // A diagnostic was already emitted.
221
222 // Character literals are always int or wchar_t, expand to intmax_t.
223 TargetInfo &TI = PP.getTargetInfo();
Chris Lattner98be4942008-03-05 18:54:05 +0000224 unsigned NumBits = TI.getCharWidth(Literal.isWide());
Reid Spencer5f016e22007-07-11 17:01:13 +0000225
226 // Set the width.
227 llvm::APSInt Val(NumBits);
228 // Set the value.
229 Val = Literal.getValue();
230 // Set the signedness.
Chris Lattner98be4942008-03-05 18:54:05 +0000231 Val.setIsUnsigned(!TI.isCharSigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000232
Chris Lattner8ed30442008-05-05 06:45:50 +0000233 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
234 Result.Val = Val.extend(Result.Val.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000236 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000237 "intmax_t smaller than char/wchar_t?");
Chris Lattner8ed30442008-05-05 06:45:50 +0000238 Result.Val = Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000239 }
240
241 // Consume the token.
Chris Lattner8ed30442008-05-05 06:45:50 +0000242 Result.setRange(PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 PP.LexNonComment(PeekTok);
244 return false;
245 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000246 case tok::l_paren: {
247 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 PP.LexNonComment(PeekTok); // Eat the (.
249 // Parse the value and if there are any binary operators involved, parse
250 // them.
251 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
252
253 // If this is a silly value like (X), which doesn't need parens, check for
254 // !(defined X).
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000255 if (PeekTok.is(tok::r_paren)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 // Just use DT unmodified as our result.
257 } else {
Chris Lattner8ed30442008-05-05 06:45:50 +0000258 // Otherwise, we have something like (x+y), and we consumed '(x'.
Reid Spencer5f016e22007-07-11 17:01:13 +0000259 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
260 return true;
261
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000262 if (PeekTok.isNot(tok::r_paren)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000263 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen,
264 Result.getRange());
265 PP.Diag(Start, diag::err_matching, "(");
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 return true;
267 }
268 DT.State = DefinedTracker::Unknown;
269 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000270 Result.setRange(Start, PeekTok.getLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +0000271 PP.LexNonComment(PeekTok); // Eat the ).
272 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000273 }
274 case tok::plus: {
275 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000276 // Unary plus doesn't modify the value.
277 PP.LexNonComment(PeekTok);
Chris Lattner8ed30442008-05-05 06:45:50 +0000278 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
279 Result.setBegin(Start);
280 return false;
281 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000282 case tok::minus: {
283 SourceLocation Loc = PeekTok.getLocation();
284 PP.LexNonComment(PeekTok);
285 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000286 Result.setBegin(Loc);
287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000289 Result.Val = -Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000290
291 bool Overflow = false;
292 if (Result.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000293 Overflow = Result.Val.isNegative();
294 else if (Result.Val.isMinSignedValue())
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 Overflow = true; // -MININT is the only thing that overflows.
296
297 // If this operator is live and overflowed, report the issue.
298 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000299 PP.Diag(Loc, diag::warn_pp_expr_overflow, Result.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000300
301 DT.State = DefinedTracker::Unknown;
302 return false;
303 }
304
Chris Lattner8ed30442008-05-05 06:45:50 +0000305 case tok::tilde: {
306 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000307 PP.LexNonComment(PeekTok);
308 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000309 Result.setBegin(Start);
310
Reid Spencer5f016e22007-07-11 17:01:13 +0000311 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
Chris Lattner8ed30442008-05-05 06:45:50 +0000312 Result.Val = ~Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 DT.State = DefinedTracker::Unknown;
314 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000315 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000316
Chris Lattner8ed30442008-05-05 06:45:50 +0000317 case tok::exclaim: {
318 SourceLocation Start = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000319 PP.LexNonComment(PeekTok);
320 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
Chris Lattner8ed30442008-05-05 06:45:50 +0000321 Result.setBegin(Start);
322 Result.Val = !Result.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000323 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
Chris Lattner8ed30442008-05-05 06:45:50 +0000324 Result.Val.setIsUnsigned(false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000325
326 if (DT.State == DefinedTracker::DefinedMacro)
327 DT.State = DefinedTracker::NotDefinedMacro;
328 else if (DT.State == DefinedTracker::NotDefinedMacro)
329 DT.State = DefinedTracker::DefinedMacro;
330 return false;
Chris Lattner8ed30442008-05-05 06:45:50 +0000331 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000332
333 // FIXME: Handle #assert
334 }
335}
336
337
338
339/// getPrecedence - Return the precedence of the specified binary operator
340/// token. This returns:
341/// ~0 - Invalid token.
Chris Lattner9e66ba62008-05-05 04:10:51 +0000342/// 14 -> 3 - various operators.
343/// 0 - 'eom' or ')'
Reid Spencer5f016e22007-07-11 17:01:13 +0000344static unsigned getPrecedence(tok::TokenKind Kind) {
345 switch (Kind) {
346 default: return ~0U;
347 case tok::percent:
348 case tok::slash:
349 case tok::star: return 14;
350 case tok::plus:
351 case tok::minus: return 13;
352 case tok::lessless:
353 case tok::greatergreater: return 12;
354 case tok::lessequal:
355 case tok::less:
356 case tok::greaterequal:
357 case tok::greater: return 11;
358 case tok::exclaimequal:
359 case tok::equalequal: return 10;
360 case tok::amp: return 9;
361 case tok::caret: return 8;
362 case tok::pipe: return 7;
363 case tok::ampamp: return 6;
364 case tok::pipepipe: return 5;
Chris Lattner98ed49f2008-05-05 20:07:41 +0000365 case tok::question: return 4;
366 case tok::comma: return 3;
Chris Lattner91891562008-05-04 18:36:18 +0000367 case tok::colon: return 2;
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 case tok::r_paren: return 0; // Lowest priority, end of expr.
369 case tok::eom: return 0; // Lowest priority, end of macro.
370 }
371}
372
373
374/// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
Chris Lattner8ed30442008-05-05 06:45:50 +0000375/// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000376///
377/// If ValueLive is false, then this value is being evaluated in a context where
378/// the result is not used. As such, avoid diagnostics that relate to
Chris Lattner8ed30442008-05-05 06:45:50 +0000379/// evaluation, such as division by zero warnings.
380static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
Chris Lattnerd2177732007-07-20 16:59:19 +0000381 Token &PeekTok, bool ValueLive,
Reid Spencer5f016e22007-07-11 17:01:13 +0000382 Preprocessor &PP) {
383 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
384 // If this token isn't valid, report the error.
385 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000386 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
387 LHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 return true;
389 }
390
391 while (1) {
392 // If this token has a lower precedence than we are allowed to parse, return
393 // it so that higher levels of the recursion can parse it.
394 if (PeekPrec < MinPrec)
395 return false;
396
397 tok::TokenKind Operator = PeekTok.getKind();
398
399 // If this is a short-circuiting operator, see if the RHS of the operator is
400 // dead. Note that this cannot just clobber ValueLive. Consider
401 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
402 // this example, the RHS of the && being dead does not make the rest of the
403 // expr dead.
404 bool RHSIsLive;
Chris Lattner8ed30442008-05-05 06:45:50 +0000405 if (Operator == tok::ampamp && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 RHSIsLive = false; // RHS of "0 && x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000407 else if (Operator == tok::pipepipe && LHS.Val != 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000408 RHSIsLive = false; // RHS of "1 || x" is dead.
Chris Lattner8ed30442008-05-05 06:45:50 +0000409 else if (Operator == tok::question && LHS.Val == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
411 else
412 RHSIsLive = ValueLive;
413
Chris Lattner8ed30442008-05-05 06:45:50 +0000414 // Consume the operator, remembering the operator's location for reporting.
415 SourceLocation OpLoc = PeekTok.getLocation();
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 PP.LexNonComment(PeekTok);
417
Chris Lattner8ed30442008-05-05 06:45:50 +0000418 PPValue RHS(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000419 // Parse the RHS of the operator.
420 DefinedTracker DT;
421 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
422
423 // Remember the precedence of this operator and get the precedence of the
424 // operator immediately to the right of the RHS.
425 unsigned ThisPrec = PeekPrec;
426 PeekPrec = getPrecedence(PeekTok.getKind());
427
428 // If this token isn't valid, report the error.
429 if (PeekPrec == ~0U) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000430 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop,
431 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 return true;
433 }
434
Chris Lattner98ed49f2008-05-05 20:07:41 +0000435 // Decide whether to include the next binop in this subexpression. For
436 // example, when parsing x+y*z and looking at '*', we want to recursively
Chris Lattner44cbbb02008-05-05 20:09:27 +0000437 // handle y*z as a single subexpression. We do this because the precedence
438 // of * is higher than that of +. The only strange case we have to handle
439 // here is for the ?: operator, where the precedence is actually lower than
440 // the LHS of the '?'. The grammar rule is:
Chris Lattner98ed49f2008-05-05 20:07:41 +0000441 //
442 // conditional-expression ::=
443 // logical-OR-expression ? expression : conditional-expression
444 // where 'expression' is actually comma-expression.
445 unsigned RHSPrec;
446 if (Operator == tok::question)
447 // The RHS of "?" should be maximally consumed as an expression.
448 RHSPrec = getPrecedence(tok::comma);
449 else // All others should munch while higher precedence.
450 RHSPrec = ThisPrec+1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000451
Chris Lattner98ed49f2008-05-05 20:07:41 +0000452 if (PeekPrec >= RHSPrec) {
453 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 return true;
455 PeekPrec = getPrecedence(PeekTok.getKind());
456 }
457 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
458
459 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
Chris Lattner019ef7e2008-05-04 23:46:17 +0000460 // either operand is unsigned.
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 llvm::APSInt Res(LHS.getBitWidth());
Chris Lattner019ef7e2008-05-04 23:46:17 +0000462 switch (Operator) {
463 case tok::question: // No UAC for x and y in "x ? y : z".
464 case tok::lessless: // Shift amount doesn't UAC with shift value.
465 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
466 case tok::comma: // Comma operands are not subject to UACs.
467 case tok::pipepipe: // Logical || does not do UACs.
468 case tok::ampamp: // Logical && does not do UACs.
469 break; // No UAC
470 default:
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
472 // If this just promoted something from signed to unsigned, and if the
473 // value was negative, warn about it.
474 if (ValueLive && Res.isUnsigned()) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000475 if (!LHS.isUnsigned() && LHS.Val.isNegative())
476 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive,
477 LHS.Val.toStringSigned() + " to "+LHS.Val.toStringUnsigned(),
478 LHS.getRange(), RHS.getRange());
479 if (!RHS.isUnsigned() && RHS.Val.isNegative())
480 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive,
481 RHS.Val.toStringSigned() + " to "+RHS.Val.toStringUnsigned(),
482 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 }
Chris Lattner8ed30442008-05-05 06:45:50 +0000484 LHS.Val.setIsUnsigned(Res.isUnsigned());
485 RHS.Val.setIsUnsigned(Res.isUnsigned());
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 }
487
488 // FIXME: All of these should detect and report overflow??
489 bool Overflow = false;
490 switch (Operator) {
491 default: assert(0 && "Unknown operator token!");
492 case tok::percent:
Chris Lattner8ed30442008-05-05 06:45:50 +0000493 if (RHS.Val != 0)
494 Res = LHS.Val % RHS.Val;
495 else if (ValueLive) {
496 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero, LHS.getRange(),
497 RHS.getRange());
498 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 break;
501 case tok::slash:
Chris Lattner8ed30442008-05-05 06:45:50 +0000502 if (RHS.Val != 0) {
503 Res = LHS.Val / RHS.Val;
504 if (LHS.Val.isSigned()) // MININT/-1 --> overflow.
505 Overflow = LHS.Val.isMinSignedValue() && RHS.Val.isAllOnesValue();
506 } else if (ValueLive) {
507 PP.Diag(OpLoc, diag::err_pp_division_by_zero, LHS.getRange(),
508 RHS.getRange());
509 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 break;
Chris Lattner3b691152008-05-04 07:15:21 +0000512
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 case tok::star:
Chris Lattner8ed30442008-05-05 06:45:50 +0000514 Res = LHS.Val * RHS.Val;
515 if (LHS.Val != 0 && RHS.Val != 0)
516 Overflow = Res/RHS.Val != LHS.Val || Res/LHS.Val != RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000517 break;
518 case tok::lessless: {
519 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000520 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
521 if (ShAmt >= LHS.Val.getBitWidth())
522 Overflow = true, ShAmt = LHS.Val.getBitWidth()-1;
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 else if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000524 Overflow = ShAmt > LHS.Val.countLeadingZeros();
525 else if (LHS.Val.isNonNegative()) // Don't allow sign change.
526 Overflow = ShAmt >= LHS.Val.countLeadingZeros();
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 else
Chris Lattner8ed30442008-05-05 06:45:50 +0000528 Overflow = ShAmt >= LHS.Val.countLeadingOnes();
Reid Spencer5f016e22007-07-11 17:01:13 +0000529
Chris Lattner8ed30442008-05-05 06:45:50 +0000530 Res = LHS.Val << ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 break;
532 }
533 case tok::greatergreater: {
534 // Determine whether overflow is about to happen.
Chris Lattner8ed30442008-05-05 06:45:50 +0000535 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 if (ShAmt >= LHS.getBitWidth())
537 Overflow = true, ShAmt = LHS.getBitWidth()-1;
Chris Lattner8ed30442008-05-05 06:45:50 +0000538 Res = LHS.Val >> ShAmt;
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 break;
540 }
541 case tok::plus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000542 Res = LHS.Val + RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000544 Overflow = Res.ult(LHS.Val);
545 else if (LHS.Val.isNonNegative() == RHS.Val.isNonNegative() &&
546 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 Overflow = true; // Overflow for signed addition.
548 break;
549 case tok::minus:
Chris Lattner8ed30442008-05-05 06:45:50 +0000550 Res = LHS.Val - RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000551 if (LHS.isUnsigned())
Chris Lattner8ed30442008-05-05 06:45:50 +0000552 Overflow = Res.ugt(LHS.Val);
553 else if (LHS.Val.isNonNegative() != RHS.Val.isNonNegative() &&
554 Res.isNonNegative() != LHS.Val.isNonNegative())
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 Overflow = true; // Overflow for signed subtraction.
556 break;
557 case tok::lessequal:
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::less:
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::greaterequal:
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::greater:
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.8p6, result is always int (signed)
572 break;
573 case tok::exclaimequal:
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::equalequal:
Chris Lattner8ed30442008-05-05 06:45:50 +0000578 Res = LHS.Val == RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000579 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
580 break;
581 case tok::amp:
Chris Lattner8ed30442008-05-05 06:45:50 +0000582 Res = LHS.Val & RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000583 break;
584 case tok::caret:
Chris Lattner8ed30442008-05-05 06:45:50 +0000585 Res = LHS.Val ^ RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 break;
587 case tok::pipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000588 Res = LHS.Val | RHS.Val;
Reid Spencer5f016e22007-07-11 17:01:13 +0000589 break;
590 case tok::ampamp:
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.13p3, result is always int (signed)
593 break;
594 case tok::pipepipe:
Chris Lattner8ed30442008-05-05 06:45:50 +0000595 Res = (LHS.Val != 0 || RHS.Val != 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000596 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
597 break;
598 case tok::comma:
Chris Lattner91891562008-05-04 18:36:18 +0000599 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
600 // if not being evaluated.
601 if (!PP.getLangOptions().C99 || ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000602 PP.Diag(OpLoc, diag::ext_pp_comma_expr, LHS.getRange(), RHS.getRange());
603 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
Reid Spencer5f016e22007-07-11 17:01:13 +0000604 break;
605 case tok::question: {
606 // Parse the : part of the expression.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000607 if (PeekTok.isNot(tok::colon)) {
Chris Lattner8ed30442008-05-05 06:45:50 +0000608 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon,
609 LHS.getRange(), RHS.getRange());
610 PP.Diag(OpLoc, diag::err_matching, "?");
Reid Spencer5f016e22007-07-11 17:01:13 +0000611 return true;
612 }
613 // Consume the :.
614 PP.LexNonComment(PeekTok);
615
616 // Evaluate the value after the :.
Chris Lattner8ed30442008-05-05 06:45:50 +0000617 bool AfterColonLive = ValueLive && LHS.Val == 0;
618 PPValue AfterColonVal(LHS.getBitWidth());
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 DefinedTracker DT;
620 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
621 return true;
622
Chris Lattner44cbbb02008-05-05 20:09:27 +0000623 // Parse anything after the : with the same precedence as ?. We allow
624 // things of equal precedence because ?: is right associative.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000625 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 PeekTok, AfterColonLive, PP))
627 return true;
628
629 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
Chris Lattner8ed30442008-05-05 06:45:50 +0000630 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
631 RHS.setEnd(AfterColonVal.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000632
633 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
634 // either operand is unsigned.
635 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
636
637 // Figure out the precedence of the token after the : part.
638 PeekPrec = getPrecedence(PeekTok.getKind());
639 break;
640 }
641 case tok::colon:
642 // Don't allow :'s to float around without being part of ?: exprs.
Chris Lattner8ed30442008-05-05 06:45:50 +0000643 PP.Diag(OpLoc, diag::err_pp_colon_without_question, LHS.getRange(),
644 RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 return true;
646 }
647
648 // If this operator is live and overflowed, report the issue.
649 if (Overflow && ValueLive)
Chris Lattner8ed30442008-05-05 06:45:50 +0000650 PP.Diag(OpLoc, diag::warn_pp_expr_overflow,
651 LHS.getRange(), RHS.getRange());
Reid Spencer5f016e22007-07-11 17:01:13 +0000652
653 // Put the result back into 'LHS' for our next iteration.
Chris Lattner8ed30442008-05-05 06:45:50 +0000654 LHS.Val = Res;
655 LHS.setEnd(RHS.getRange().getEnd());
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 }
657
658 return false;
659}
660
661/// EvaluateDirectiveExpression - Evaluate an integer constant expression that
662/// may occur after a #if or #elif directive. If the expression is equivalent
663/// to "!defined(X)" return X in IfNDefMacro.
664bool Preprocessor::
665EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
666 // Peek ahead one token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000667 Token Tok;
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 Lex(Tok);
669
670 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
Chris Lattner98be4942008-03-05 18:54:05 +0000671 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000672
Chris Lattner8ed30442008-05-05 06:45:50 +0000673 PPValue ResVal(BitWidth);
Reid Spencer5f016e22007-07-11 17:01:13 +0000674 DefinedTracker DT;
675 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
676 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000677 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 DiscardUntilEndOfDirective();
679 return false;
680 }
681
682 // If we are at the end of the expression after just parsing a value, there
683 // must be no (unparenthesized) binary operators involved, so we can exit
684 // directly.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000685 if (Tok.is(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000686 // If the expression we parsed was of the form !defined(macro), return the
687 // macro in IfNDefMacro.
688 if (DT.State == DefinedTracker::NotDefinedMacro)
689 IfNDefMacro = DT.TheMacro;
690
Chris Lattner8ed30442008-05-05 06:45:50 +0000691 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000692 }
693
694 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
695 // operator and the stuff after it.
Chris Lattner98ed49f2008-05-05 20:07:41 +0000696 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
697 Tok, true, *this)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000698 // Parse error, skip the rest of the macro line.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000699 if (Tok.isNot(tok::eom))
Reid Spencer5f016e22007-07-11 17:01:13 +0000700 DiscardUntilEndOfDirective();
701 return false;
702 }
703
704 // If we aren't at the tok::eom token, something bad happened, like an extra
705 // ')' token.
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000706 if (Tok.isNot(tok::eom)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 Diag(Tok, diag::err_pp_expected_eol);
708 DiscardUntilEndOfDirective();
709 }
710
Chris Lattner8ed30442008-05-05 06:45:50 +0000711 return ResVal.Val != 0;
Reid Spencer5f016e22007-07-11 17:01:13 +0000712}
713