1 //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Preprocessor::EvaluateDirectiveExpression method,
11 // which parses and evaluates integer constant expressions for #if directives.
13 //===----------------------------------------------------------------------===//
15 // FIXME: implement testing for #assert's.
17 //===----------------------------------------------------------------------===//
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "clang/Lex/CodeCompletionHandler.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/MacroInfo.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/SaveAndRestore.h"
28 using namespace clang;
32 /// PPValue - Represents the value of a subexpression of a preprocessor
33 /// conditional and the source range covered by it.
39 // Default ctor - Construct an 'invalid' PPValue.
40 PPValue(unsigned BitWidth) : Val(BitWidth) {}
42 unsigned getBitWidth() const { return Val.getBitWidth(); }
43 bool isUnsigned() const { return Val.isUnsigned(); }
45 const SourceRange &getRange() const { return Range; }
47 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
48 void setRange(SourceLocation B, SourceLocation E) {
49 Range.setBegin(B); Range.setEnd(E);
51 void setBegin(SourceLocation L) { Range.setBegin(L); }
52 void setEnd(SourceLocation L) { Range.setEnd(L); }
57 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
58 Token &PeekTok, bool ValueLive,
61 /// DefinedTracker - This struct is used while parsing expressions to keep track
62 /// of whether !defined(X) has been seen.
64 /// With this simple scheme, we handle the basic forms:
65 /// !defined(X) and !defined X
66 /// but we also trivially handle (silly) stuff like:
67 /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
68 struct DefinedTracker {
69 /// Each time a Value is evaluated, it returns information about whether the
70 /// parsed value is of the form defined(X), !defined(X) or is something else.
72 DefinedMacro, // defined(X)
73 NotDefinedMacro, // !defined(X)
74 Unknown // Something else.
76 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
77 /// indicates the macro that was checked.
78 IdentifierInfo *TheMacro;
81 /// EvaluateDefined - Process a 'defined(sym)' expression.
82 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
83 bool ValueLive, Preprocessor &PP) {
85 Result.setBegin(PeekTok.getLocation());
87 // Get the next token, don't expand it.
88 PP.LexUnexpandedNonComment(PeekTok);
90 // Two options, it can either be a pp-identifier or a (.
91 SourceLocation LParenLoc;
92 if (PeekTok.is(tok::l_paren)) {
93 // Found a paren, remember we saw it and skip it.
94 LParenLoc = PeekTok.getLocation();
95 PP.LexUnexpandedNonComment(PeekTok);
98 if (PeekTok.is(tok::code_completion)) {
99 if (PP.getCodeCompletionHandler())
100 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
101 PP.setCodeCompletionReached();
102 PP.LexUnexpandedNonComment(PeekTok);
105 // If we don't have a pp-identifier now, this is an error.
106 if ((II = PeekTok.getIdentifierInfo()) == 0) {
107 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
111 // Otherwise, we got an identifier, is it defined to something?
112 Result.Val = II->hasMacroDefinition();
113 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
115 MacroDirective *Macro = 0;
116 // If there is a macro, mark it used.
117 if (Result.Val != 0 && ValueLive) {
118 Macro = PP.getMacroDirective(II);
119 PP.markMacroAsUsed(Macro->getMacroInfo());
122 // Invoke the 'defined' callback.
123 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
124 MacroDirective *MD = Macro;
125 // Pass the MacroInfo for the macro name even if the value is dead.
126 if (!MD && Result.Val != 0)
127 MD = PP.getMacroDirective(II);
128 Callbacks->Defined(PeekTok, MD);
131 // If we are in parens, ensure we have a trailing ).
132 if (LParenLoc.isValid()) {
133 // Consume identifier.
134 Result.setEnd(PeekTok.getLocation());
135 PP.LexUnexpandedNonComment(PeekTok);
137 if (PeekTok.isNot(tok::r_paren)) {
138 PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
139 PP.Diag(LParenLoc, diag::note_matching) << "(";
143 Result.setEnd(PeekTok.getLocation());
144 PP.LexNonComment(PeekTok);
146 // Consume identifier.
147 Result.setEnd(PeekTok.getLocation());
148 PP.LexNonComment(PeekTok);
151 // Success, remember that we saw defined(X).
152 DT.State = DefinedTracker::DefinedMacro;
157 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
158 /// return the computed value in Result. Return true if there was an error
159 /// parsing. This function also returns information about the form of the
160 /// expression in DT. See above for information on what DT means.
162 /// If ValueLive is false, then this value is being evaluated in a context where
163 /// the result is not used. As such, avoid diagnostics that relate to
165 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
166 bool ValueLive, Preprocessor &PP) {
167 DT.State = DefinedTracker::Unknown;
169 if (PeekTok.is(tok::code_completion)) {
170 if (PP.getCodeCompletionHandler())
171 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
172 PP.setCodeCompletionReached();
173 PP.LexNonComment(PeekTok);
176 // If this token's spelling is a pp-identifier, check to see if it is
177 // 'defined' or if it is a macro. Note that we check here because many
178 // keywords are pp-identifiers, so we can't check the kind.
179 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
180 // Handle "defined X" and "defined(X)".
181 if (II->isStr("defined"))
182 return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
184 // If this identifier isn't 'defined' or one of the special
185 // preprocessor keywords and it wasn't macro expanded, it turns
186 // into a simple 0, unless it is the C++ keyword "true", in which case it
189 II->getTokenID() != tok::kw_true &&
190 II->getTokenID() != tok::kw_false)
191 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
192 Result.Val = II->getTokenID() == tok::kw_true;
193 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
194 Result.setRange(PeekTok.getLocation());
195 PP.LexNonComment(PeekTok);
199 switch (PeekTok.getKind()) {
200 default: // Non-value token.
201 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
205 // If there is no expression, report and exit.
206 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
208 case tok::numeric_constant: {
209 SmallString<64> IntegerBuffer;
210 bool NumberInvalid = false;
211 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
214 return true; // a diagnostic was already reported
216 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
217 if (Literal.hadError)
218 return true; // a diagnostic was already reported.
220 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
221 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
224 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
226 // Complain about, and drop, any ud-suffix.
227 if (Literal.hasUDSuffix())
228 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
230 // 'long long' is a C99 or C++11 feature.
231 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
232 if (PP.getLangOpts().CPlusPlus)
234 PP.getLangOpts().CPlusPlus11 ?
235 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
237 PP.Diag(PeekTok, diag::ext_c99_longlong);
240 // Parse the integer literal into Result.
241 if (Literal.GetIntegerValue(Result.Val)) {
242 // Overflow parsing integer literal.
243 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
244 Result.Val.setIsUnsigned(true);
246 // Set the signedness of the result to match whether there was a U suffix
248 Result.Val.setIsUnsigned(Literal.isUnsigned);
250 // Detect overflow based on whether the value is signed. If signed
251 // and if the value is too large, emit a warning "integer constant is so
252 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
254 if (!Literal.isUnsigned && Result.Val.isNegative()) {
255 // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
256 if (ValueLive && Literal.getRadix() != 16)
257 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
258 Result.Val.setIsUnsigned(true);
262 // Consume the token.
263 Result.setRange(PeekTok.getLocation());
264 PP.LexNonComment(PeekTok);
267 case tok::char_constant: // 'x'
268 case tok::wide_char_constant: // L'x'
269 case tok::utf16_char_constant: // u'x'
270 case tok::utf32_char_constant: { // U'x'
271 // Complain about, and drop, any ud-suffix.
272 if (PeekTok.hasUDSuffix())
273 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
275 SmallString<32> CharBuffer;
276 bool CharInvalid = false;
277 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
281 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
282 PeekTok.getLocation(), PP, PeekTok.getKind());
283 if (Literal.hadError())
284 return true; // A diagnostic was already emitted.
286 // Character literals are always int or wchar_t, expand to intmax_t.
287 const TargetInfo &TI = PP.getTargetInfo();
289 if (Literal.isMultiChar())
290 NumBits = TI.getIntWidth();
291 else if (Literal.isWide())
292 NumBits = TI.getWCharWidth();
293 else if (Literal.isUTF16())
294 NumBits = TI.getChar16Width();
295 else if (Literal.isUTF32())
296 NumBits = TI.getChar32Width();
298 NumBits = TI.getCharWidth();
301 llvm::APSInt Val(NumBits);
303 Val = Literal.getValue();
304 // Set the signedness. UTF-16 and UTF-32 are always unsigned
305 if (!Literal.isUTF16() && !Literal.isUTF32())
306 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
308 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
309 Result.Val = Val.extend(Result.Val.getBitWidth());
311 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
312 "intmax_t smaller than char/wchar_t?");
316 // Consume the token.
317 Result.setRange(PeekTok.getLocation());
318 PP.LexNonComment(PeekTok);
322 SourceLocation Start = PeekTok.getLocation();
323 PP.LexNonComment(PeekTok); // Eat the (.
324 // Parse the value and if there are any binary operators involved, parse
326 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
328 // If this is a silly value like (X), which doesn't need parens, check for
330 if (PeekTok.is(tok::r_paren)) {
331 // Just use DT unmodified as our result.
333 // Otherwise, we have something like (x+y), and we consumed '(x'.
334 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
337 if (PeekTok.isNot(tok::r_paren)) {
338 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
339 << Result.getRange();
340 PP.Diag(Start, diag::note_matching) << "(";
343 DT.State = DefinedTracker::Unknown;
345 Result.setRange(Start, PeekTok.getLocation());
346 PP.LexNonComment(PeekTok); // Eat the ).
350 SourceLocation Start = PeekTok.getLocation();
351 // Unary plus doesn't modify the value.
352 PP.LexNonComment(PeekTok);
353 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
354 Result.setBegin(Start);
358 SourceLocation Loc = PeekTok.getLocation();
359 PP.LexNonComment(PeekTok);
360 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
361 Result.setBegin(Loc);
363 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
364 Result.Val = -Result.Val;
366 // -MININT is the only thing that overflows. Unsigned never overflows.
367 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
369 // If this operator is live and overflowed, report the issue.
370 if (Overflow && ValueLive)
371 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
373 DT.State = DefinedTracker::Unknown;
378 SourceLocation Start = PeekTok.getLocation();
379 PP.LexNonComment(PeekTok);
380 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
381 Result.setBegin(Start);
383 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
384 Result.Val = ~Result.Val;
385 DT.State = DefinedTracker::Unknown;
390 SourceLocation Start = PeekTok.getLocation();
391 PP.LexNonComment(PeekTok);
392 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
393 Result.setBegin(Start);
394 Result.Val = !Result.Val;
395 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
396 Result.Val.setIsUnsigned(false);
398 if (DT.State == DefinedTracker::DefinedMacro)
399 DT.State = DefinedTracker::NotDefinedMacro;
400 else if (DT.State == DefinedTracker::NotDefinedMacro)
401 DT.State = DefinedTracker::DefinedMacro;
405 // FIXME: Handle #assert
411 /// getPrecedence - Return the precedence of the specified binary operator
412 /// token. This returns:
413 /// ~0 - Invalid token.
414 /// 14 -> 3 - various operators.
416 static unsigned getPrecedence(tok::TokenKind Kind) {
421 case tok::star: return 14;
423 case tok::minus: return 13;
425 case tok::greatergreater: return 12;
428 case tok::greaterequal:
429 case tok::greater: return 11;
430 case tok::exclaimequal:
431 case tok::equalequal: return 10;
432 case tok::amp: return 9;
433 case tok::caret: return 8;
434 case tok::pipe: return 7;
435 case tok::ampamp: return 6;
436 case tok::pipepipe: return 5;
437 case tok::question: return 4;
438 case tok::comma: return 3;
439 case tok::colon: return 2;
440 case tok::r_paren: return 0;// Lowest priority, end of expr.
441 case tok::eod: return 0;// Lowest priority, end of directive.
446 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
447 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
449 /// If ValueLive is false, then this value is being evaluated in a context where
450 /// the result is not used. As such, avoid diagnostics that relate to
451 /// evaluation, such as division by zero warnings.
452 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
453 Token &PeekTok, bool ValueLive,
455 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
456 // If this token isn't valid, report the error.
457 if (PeekPrec == ~0U) {
458 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
464 // If this token has a lower precedence than we are allowed to parse, return
465 // it so that higher levels of the recursion can parse it.
466 if (PeekPrec < MinPrec)
469 tok::TokenKind Operator = PeekTok.getKind();
471 // If this is a short-circuiting operator, see if the RHS of the operator is
472 // dead. Note that this cannot just clobber ValueLive. Consider
473 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
474 // this example, the RHS of the && being dead does not make the rest of the
477 if (Operator == tok::ampamp && LHS.Val == 0)
478 RHSIsLive = false; // RHS of "0 && x" is dead.
479 else if (Operator == tok::pipepipe && LHS.Val != 0)
480 RHSIsLive = false; // RHS of "1 || x" is dead.
481 else if (Operator == tok::question && LHS.Val == 0)
482 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
484 RHSIsLive = ValueLive;
486 // Consume the operator, remembering the operator's location for reporting.
487 SourceLocation OpLoc = PeekTok.getLocation();
488 PP.LexNonComment(PeekTok);
490 PPValue RHS(LHS.getBitWidth());
491 // Parse the RHS of the operator.
493 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
495 // Remember the precedence of this operator and get the precedence of the
496 // operator immediately to the right of the RHS.
497 unsigned ThisPrec = PeekPrec;
498 PeekPrec = getPrecedence(PeekTok.getKind());
500 // If this token isn't valid, report the error.
501 if (PeekPrec == ~0U) {
502 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
507 // Decide whether to include the next binop in this subexpression. For
508 // example, when parsing x+y*z and looking at '*', we want to recursively
509 // handle y*z as a single subexpression. We do this because the precedence
510 // of * is higher than that of +. The only strange case we have to handle
511 // here is for the ?: operator, where the precedence is actually lower than
512 // the LHS of the '?'. The grammar rule is:
514 // conditional-expression ::=
515 // logical-OR-expression ? expression : conditional-expression
516 // where 'expression' is actually comma-expression.
518 if (Operator == tok::question)
519 // The RHS of "?" should be maximally consumed as an expression.
520 RHSPrec = getPrecedence(tok::comma);
521 else // All others should munch while higher precedence.
522 RHSPrec = ThisPrec+1;
524 if (PeekPrec >= RHSPrec) {
525 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
527 PeekPrec = getPrecedence(PeekTok.getKind());
529 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
531 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
532 // either operand is unsigned.
533 llvm::APSInt Res(LHS.getBitWidth());
535 case tok::question: // No UAC for x and y in "x ? y : z".
536 case tok::lessless: // Shift amount doesn't UAC with shift value.
537 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
538 case tok::comma: // Comma operands are not subject to UACs.
539 case tok::pipepipe: // Logical || does not do UACs.
540 case tok::ampamp: // Logical && does not do UACs.
543 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
544 // If this just promoted something from signed to unsigned, and if the
545 // value was negative, warn about it.
546 if (ValueLive && Res.isUnsigned()) {
547 if (!LHS.isUnsigned() && LHS.Val.isNegative())
548 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
549 << LHS.Val.toString(10, true) + " to " +
550 LHS.Val.toString(10, false)
551 << LHS.getRange() << RHS.getRange();
552 if (!RHS.isUnsigned() && RHS.Val.isNegative())
553 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
554 << RHS.Val.toString(10, true) + " to " +
555 RHS.Val.toString(10, false)
556 << LHS.getRange() << RHS.getRange();
558 LHS.Val.setIsUnsigned(Res.isUnsigned());
559 RHS.Val.setIsUnsigned(Res.isUnsigned());
562 bool Overflow = false;
564 default: llvm_unreachable("Unknown operator token!");
567 Res = LHS.Val % RHS.Val;
568 else if (ValueLive) {
569 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
570 << LHS.getRange() << RHS.getRange();
576 if (LHS.Val.isSigned())
577 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
579 Res = LHS.Val / RHS.Val;
580 } else if (ValueLive) {
581 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
582 << LHS.getRange() << RHS.getRange();
589 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
591 Res = LHS.Val * RHS.Val;
593 case tok::lessless: {
594 // Determine whether overflow is about to happen.
595 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
596 if (LHS.isUnsigned()) {
597 Overflow = ShAmt >= LHS.Val.getBitWidth();
599 ShAmt = LHS.Val.getBitWidth()-1;
600 Res = LHS.Val << ShAmt;
602 Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
606 case tok::greatergreater: {
607 // Determine whether overflow is about to happen.
608 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
609 if (ShAmt >= LHS.getBitWidth())
610 Overflow = true, ShAmt = LHS.getBitWidth()-1;
611 Res = LHS.Val >> ShAmt;
615 if (LHS.isUnsigned())
616 Res = LHS.Val + RHS.Val;
618 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
621 if (LHS.isUnsigned())
622 Res = LHS.Val - RHS.Val;
624 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
627 Res = LHS.Val <= RHS.Val;
628 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
631 Res = LHS.Val < RHS.Val;
632 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
634 case tok::greaterequal:
635 Res = LHS.Val >= RHS.Val;
636 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
639 Res = LHS.Val > RHS.Val;
640 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
642 case tok::exclaimequal:
643 Res = LHS.Val != RHS.Val;
644 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
646 case tok::equalequal:
647 Res = LHS.Val == RHS.Val;
648 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
651 Res = LHS.Val & RHS.Val;
654 Res = LHS.Val ^ RHS.Val;
657 Res = LHS.Val | RHS.Val;
660 Res = (LHS.Val != 0 && RHS.Val != 0);
661 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
664 Res = (LHS.Val != 0 || RHS.Val != 0);
665 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
668 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
669 // if not being evaluated.
670 if (!PP.getLangOpts().C99 || ValueLive)
671 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
672 << LHS.getRange() << RHS.getRange();
673 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
675 case tok::question: {
676 // Parse the : part of the expression.
677 if (PeekTok.isNot(tok::colon)) {
678 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
679 << LHS.getRange(), RHS.getRange();
680 PP.Diag(OpLoc, diag::note_matching) << "?";
684 PP.LexNonComment(PeekTok);
686 // Evaluate the value after the :.
687 bool AfterColonLive = ValueLive && LHS.Val == 0;
688 PPValue AfterColonVal(LHS.getBitWidth());
690 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
693 // Parse anything after the : with the same precedence as ?. We allow
694 // things of equal precedence because ?: is right associative.
695 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
696 PeekTok, AfterColonLive, PP))
699 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
700 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
701 RHS.setEnd(AfterColonVal.getRange().getEnd());
703 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
704 // either operand is unsigned.
705 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
707 // Figure out the precedence of the token after the : part.
708 PeekPrec = getPrecedence(PeekTok.getKind());
712 // Don't allow :'s to float around without being part of ?: exprs.
713 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
714 << LHS.getRange() << RHS.getRange();
718 // If this operator is live and overflowed, report the issue.
719 if (Overflow && ValueLive)
720 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
721 << LHS.getRange() << RHS.getRange();
723 // Put the result back into 'LHS' for our next iteration.
725 LHS.setEnd(RHS.getRange().getEnd());
729 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
730 /// may occur after a #if or #elif directive. If the expression is equivalent
731 /// to "!defined(X)" return X in IfNDefMacro.
733 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
734 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
735 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
736 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
737 // in which case a directive is undefined behavior. We want macros to be able
738 // to recursively expand in order to get more gcc-list behavior, so we force
739 // DisableMacroExpansion to false and restore it when we're done parsing the
741 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
742 DisableMacroExpansion = false;
744 // Peek ahead one token.
748 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
749 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
751 PPValue ResVal(BitWidth);
753 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
754 // Parse error, skip the rest of the macro line.
755 if (Tok.isNot(tok::eod))
756 DiscardUntilEndOfDirective();
758 // Restore 'DisableMacroExpansion'.
759 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
763 // If we are at the end of the expression after just parsing a value, there
764 // must be no (unparenthesized) binary operators involved, so we can exit
766 if (Tok.is(tok::eod)) {
767 // If the expression we parsed was of the form !defined(macro), return the
768 // macro in IfNDefMacro.
769 if (DT.State == DefinedTracker::NotDefinedMacro)
770 IfNDefMacro = DT.TheMacro;
772 // Restore 'DisableMacroExpansion'.
773 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
774 return ResVal.Val != 0;
777 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
778 // operator and the stuff after it.
779 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
781 // Parse error, skip the rest of the macro line.
782 if (Tok.isNot(tok::eod))
783 DiscardUntilEndOfDirective();
785 // Restore 'DisableMacroExpansion'.
786 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
790 // If we aren't at the tok::eod token, something bad happened, like an extra
792 if (Tok.isNot(tok::eod)) {
793 Diag(Tok, diag::err_pp_expected_eol);
794 DiscardUntilEndOfDirective();
797 // Restore 'DisableMacroExpansion'.
798 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
799 return ResVal.Val != 0;