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) {
84 SourceLocation beginLoc(PeekTok.getLocation());
85 Result.setBegin(beginLoc);
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 (PP.CheckMacroName(PeekTok, MU_Other))
109 // Otherwise, we got an identifier, is it defined to something?
110 IdentifierInfo *II = PeekTok.getIdentifierInfo();
111 Result.Val = II->hasMacroDefinition();
112 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
114 MacroDirective *Macro = nullptr;
115 // If there is a macro, mark it used.
116 if (Result.Val != 0 && ValueLive) {
117 Macro = PP.getMacroDirective(II);
118 PP.markMacroAsUsed(Macro->getMacroInfo());
121 // Save macro token for callback.
122 Token macroToken(PeekTok);
124 // If we are in parens, ensure we have a trailing ).
125 if (LParenLoc.isValid()) {
126 // Consume identifier.
127 Result.setEnd(PeekTok.getLocation());
128 PP.LexUnexpandedNonComment(PeekTok);
130 if (PeekTok.isNot(tok::r_paren)) {
131 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
132 << "'defined'" << tok::r_paren;
133 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
137 Result.setEnd(PeekTok.getLocation());
138 PP.LexNonComment(PeekTok);
140 // Consume identifier.
141 Result.setEnd(PeekTok.getLocation());
142 PP.LexNonComment(PeekTok);
145 // Invoke the 'defined' callback.
146 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
147 MacroDirective *MD = Macro;
148 // Pass the MacroInfo for the macro name even if the value is dead.
149 if (!MD && Result.Val != 0)
150 MD = PP.getMacroDirective(II);
151 Callbacks->Defined(macroToken, MD,
152 SourceRange(beginLoc, PeekTok.getLocation()));
155 // Success, remember that we saw defined(X).
156 DT.State = DefinedTracker::DefinedMacro;
161 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
162 /// return the computed value in Result. Return true if there was an error
163 /// parsing. This function also returns information about the form of the
164 /// expression in DT. See above for information on what DT means.
166 /// If ValueLive is false, then this value is being evaluated in a context where
167 /// the result is not used. As such, avoid diagnostics that relate to
169 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
170 bool ValueLive, Preprocessor &PP) {
171 DT.State = DefinedTracker::Unknown;
173 if (PeekTok.is(tok::code_completion)) {
174 if (PP.getCodeCompletionHandler())
175 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
176 PP.setCodeCompletionReached();
177 PP.LexNonComment(PeekTok);
180 // If this token's spelling is a pp-identifier, check to see if it is
181 // 'defined' or if it is a macro. Note that we check here because many
182 // keywords are pp-identifiers, so we can't check the kind.
183 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
184 // Handle "defined X" and "defined(X)".
185 if (II->isStr("defined"))
186 return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
188 // If this identifier isn't 'defined' or one of the special
189 // preprocessor keywords and it wasn't macro expanded, it turns
190 // into a simple 0, unless it is the C++ keyword "true", in which case it
193 II->getTokenID() != tok::kw_true &&
194 II->getTokenID() != tok::kw_false)
195 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
196 Result.Val = II->getTokenID() == tok::kw_true;
197 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
198 Result.setRange(PeekTok.getLocation());
199 PP.LexNonComment(PeekTok);
203 switch (PeekTok.getKind()) {
204 default: // Non-value token.
205 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
209 // If there is no expression, report and exit.
210 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
212 case tok::numeric_constant: {
213 SmallString<64> IntegerBuffer;
214 bool NumberInvalid = false;
215 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
218 return true; // a diagnostic was already reported
220 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
221 if (Literal.hadError)
222 return true; // a diagnostic was already reported.
224 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
225 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
228 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
230 // Complain about, and drop, any ud-suffix.
231 if (Literal.hasUDSuffix())
232 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
234 // 'long long' is a C99 or C++11 feature.
235 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
236 if (PP.getLangOpts().CPlusPlus)
238 PP.getLangOpts().CPlusPlus11 ?
239 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
241 PP.Diag(PeekTok, diag::ext_c99_longlong);
244 // Parse the integer literal into Result.
245 if (Literal.GetIntegerValue(Result.Val)) {
246 // Overflow parsing integer literal.
248 PP.Diag(PeekTok, diag::err_integer_literal_too_large)
250 Result.Val.setIsUnsigned(true);
252 // Set the signedness of the result to match whether there was a U suffix
254 Result.Val.setIsUnsigned(Literal.isUnsigned);
256 // Detect overflow based on whether the value is signed. If signed
257 // and if the value is too large, emit a warning "integer constant is so
258 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
260 if (!Literal.isUnsigned && Result.Val.isNegative()) {
261 // Octal, hexadecimal, and binary literals are implicitly unsigned if
262 // the value does not fit into a signed integer type.
263 if (ValueLive && Literal.getRadix() == 10)
264 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
265 Result.Val.setIsUnsigned(true);
269 // Consume the token.
270 Result.setRange(PeekTok.getLocation());
271 PP.LexNonComment(PeekTok);
274 case tok::char_constant: // 'x'
275 case tok::wide_char_constant: // L'x'
276 case tok::utf8_char_constant: // u8'x'
277 case tok::utf16_char_constant: // u'x'
278 case tok::utf32_char_constant: { // U'x'
279 // Complain about, and drop, any ud-suffix.
280 if (PeekTok.hasUDSuffix())
281 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
283 SmallString<32> CharBuffer;
284 bool CharInvalid = false;
285 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
289 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
290 PeekTok.getLocation(), PP, PeekTok.getKind());
291 if (Literal.hadError())
292 return true; // A diagnostic was already emitted.
294 // Character literals are always int or wchar_t, expand to intmax_t.
295 const TargetInfo &TI = PP.getTargetInfo();
297 if (Literal.isMultiChar())
298 NumBits = TI.getIntWidth();
299 else if (Literal.isWide())
300 NumBits = TI.getWCharWidth();
301 else if (Literal.isUTF16())
302 NumBits = TI.getChar16Width();
303 else if (Literal.isUTF32())
304 NumBits = TI.getChar32Width();
306 NumBits = TI.getCharWidth();
309 llvm::APSInt Val(NumBits);
311 Val = Literal.getValue();
312 // Set the signedness. UTF-16 and UTF-32 are always unsigned
313 if (!Literal.isUTF16() && !Literal.isUTF32())
314 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
316 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
317 Result.Val = Val.extend(Result.Val.getBitWidth());
319 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
320 "intmax_t smaller than char/wchar_t?");
324 // Consume the token.
325 Result.setRange(PeekTok.getLocation());
326 PP.LexNonComment(PeekTok);
330 SourceLocation Start = PeekTok.getLocation();
331 PP.LexNonComment(PeekTok); // Eat the (.
332 // Parse the value and if there are any binary operators involved, parse
334 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
336 // If this is a silly value like (X), which doesn't need parens, check for
338 if (PeekTok.is(tok::r_paren)) {
339 // Just use DT unmodified as our result.
341 // Otherwise, we have something like (x+y), and we consumed '(x'.
342 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
345 if (PeekTok.isNot(tok::r_paren)) {
346 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
347 << Result.getRange();
348 PP.Diag(Start, diag::note_matching) << tok::l_paren;
351 DT.State = DefinedTracker::Unknown;
353 Result.setRange(Start, PeekTok.getLocation());
354 PP.LexNonComment(PeekTok); // Eat the ).
358 SourceLocation Start = PeekTok.getLocation();
359 // Unary plus doesn't modify the value.
360 PP.LexNonComment(PeekTok);
361 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
362 Result.setBegin(Start);
366 SourceLocation Loc = PeekTok.getLocation();
367 PP.LexNonComment(PeekTok);
368 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
369 Result.setBegin(Loc);
371 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
372 Result.Val = -Result.Val;
374 // -MININT is the only thing that overflows. Unsigned never overflows.
375 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
377 // If this operator is live and overflowed, report the issue.
378 if (Overflow && ValueLive)
379 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
381 DT.State = DefinedTracker::Unknown;
386 SourceLocation Start = PeekTok.getLocation();
387 PP.LexNonComment(PeekTok);
388 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
389 Result.setBegin(Start);
391 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
392 Result.Val = ~Result.Val;
393 DT.State = DefinedTracker::Unknown;
398 SourceLocation Start = PeekTok.getLocation();
399 PP.LexNonComment(PeekTok);
400 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
401 Result.setBegin(Start);
402 Result.Val = !Result.Val;
403 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
404 Result.Val.setIsUnsigned(false);
406 if (DT.State == DefinedTracker::DefinedMacro)
407 DT.State = DefinedTracker::NotDefinedMacro;
408 else if (DT.State == DefinedTracker::NotDefinedMacro)
409 DT.State = DefinedTracker::DefinedMacro;
413 // FIXME: Handle #assert
419 /// getPrecedence - Return the precedence of the specified binary operator
420 /// token. This returns:
421 /// ~0 - Invalid token.
422 /// 14 -> 3 - various operators.
424 static unsigned getPrecedence(tok::TokenKind Kind) {
429 case tok::star: return 14;
431 case tok::minus: return 13;
433 case tok::greatergreater: return 12;
436 case tok::greaterequal:
437 case tok::greater: return 11;
438 case tok::exclaimequal:
439 case tok::equalequal: return 10;
440 case tok::amp: return 9;
441 case tok::caret: return 8;
442 case tok::pipe: return 7;
443 case tok::ampamp: return 6;
444 case tok::pipepipe: return 5;
445 case tok::question: return 4;
446 case tok::comma: return 3;
447 case tok::colon: return 2;
448 case tok::r_paren: return 0;// Lowest priority, end of expr.
449 case tok::eod: return 0;// Lowest priority, end of directive.
454 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
455 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
457 /// If ValueLive is false, then this value is being evaluated in a context where
458 /// the result is not used. As such, avoid diagnostics that relate to
459 /// evaluation, such as division by zero warnings.
460 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
461 Token &PeekTok, bool ValueLive,
463 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
464 // If this token isn't valid, report the error.
465 if (PeekPrec == ~0U) {
466 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
472 // If this token has a lower precedence than we are allowed to parse, return
473 // it so that higher levels of the recursion can parse it.
474 if (PeekPrec < MinPrec)
477 tok::TokenKind Operator = PeekTok.getKind();
479 // If this is a short-circuiting operator, see if the RHS of the operator is
480 // dead. Note that this cannot just clobber ValueLive. Consider
481 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
482 // this example, the RHS of the && being dead does not make the rest of the
485 if (Operator == tok::ampamp && LHS.Val == 0)
486 RHSIsLive = false; // RHS of "0 && x" is dead.
487 else if (Operator == tok::pipepipe && LHS.Val != 0)
488 RHSIsLive = false; // RHS of "1 || x" is dead.
489 else if (Operator == tok::question && LHS.Val == 0)
490 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
492 RHSIsLive = ValueLive;
494 // Consume the operator, remembering the operator's location for reporting.
495 SourceLocation OpLoc = PeekTok.getLocation();
496 PP.LexNonComment(PeekTok);
498 PPValue RHS(LHS.getBitWidth());
499 // Parse the RHS of the operator.
501 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
503 // Remember the precedence of this operator and get the precedence of the
504 // operator immediately to the right of the RHS.
505 unsigned ThisPrec = PeekPrec;
506 PeekPrec = getPrecedence(PeekTok.getKind());
508 // If this token isn't valid, report the error.
509 if (PeekPrec == ~0U) {
510 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
515 // Decide whether to include the next binop in this subexpression. For
516 // example, when parsing x+y*z and looking at '*', we want to recursively
517 // handle y*z as a single subexpression. We do this because the precedence
518 // of * is higher than that of +. The only strange case we have to handle
519 // here is for the ?: operator, where the precedence is actually lower than
520 // the LHS of the '?'. The grammar rule is:
522 // conditional-expression ::=
523 // logical-OR-expression ? expression : conditional-expression
524 // where 'expression' is actually comma-expression.
526 if (Operator == tok::question)
527 // The RHS of "?" should be maximally consumed as an expression.
528 RHSPrec = getPrecedence(tok::comma);
529 else // All others should munch while higher precedence.
530 RHSPrec = ThisPrec+1;
532 if (PeekPrec >= RHSPrec) {
533 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
535 PeekPrec = getPrecedence(PeekTok.getKind());
537 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
539 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
540 // either operand is unsigned.
541 llvm::APSInt Res(LHS.getBitWidth());
543 case tok::question: // No UAC for x and y in "x ? y : z".
544 case tok::lessless: // Shift amount doesn't UAC with shift value.
545 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
546 case tok::comma: // Comma operands are not subject to UACs.
547 case tok::pipepipe: // Logical || does not do UACs.
548 case tok::ampamp: // Logical && does not do UACs.
551 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
552 // If this just promoted something from signed to unsigned, and if the
553 // value was negative, warn about it.
554 if (ValueLive && Res.isUnsigned()) {
555 if (!LHS.isUnsigned() && LHS.Val.isNegative())
556 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
557 << LHS.Val.toString(10, true) + " to " +
558 LHS.Val.toString(10, false)
559 << LHS.getRange() << RHS.getRange();
560 if (!RHS.isUnsigned() && RHS.Val.isNegative())
561 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
562 << RHS.Val.toString(10, true) + " to " +
563 RHS.Val.toString(10, false)
564 << LHS.getRange() << RHS.getRange();
566 LHS.Val.setIsUnsigned(Res.isUnsigned());
567 RHS.Val.setIsUnsigned(Res.isUnsigned());
570 bool Overflow = false;
572 default: llvm_unreachable("Unknown operator token!");
575 Res = LHS.Val % RHS.Val;
576 else if (ValueLive) {
577 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
578 << LHS.getRange() << RHS.getRange();
584 if (LHS.Val.isSigned())
585 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
587 Res = LHS.Val / RHS.Val;
588 } else if (ValueLive) {
589 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
590 << LHS.getRange() << RHS.getRange();
597 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
599 Res = LHS.Val * RHS.Val;
601 case tok::lessless: {
602 // Determine whether overflow is about to happen.
603 if (LHS.isUnsigned())
604 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
606 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
609 case tok::greatergreater: {
610 // Determine whether overflow is about to happen.
611 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
612 if (ShAmt >= LHS.getBitWidth())
613 Overflow = true, ShAmt = LHS.getBitWidth()-1;
614 Res = LHS.Val >> ShAmt;
618 if (LHS.isUnsigned())
619 Res = LHS.Val + RHS.Val;
621 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
624 if (LHS.isUnsigned())
625 Res = LHS.Val - RHS.Val;
627 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
630 Res = LHS.Val <= RHS.Val;
631 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
634 Res = LHS.Val < RHS.Val;
635 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
637 case tok::greaterequal:
638 Res = LHS.Val >= RHS.Val;
639 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
642 Res = LHS.Val > RHS.Val;
643 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
645 case tok::exclaimequal:
646 Res = LHS.Val != RHS.Val;
647 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
649 case tok::equalequal:
650 Res = LHS.Val == RHS.Val;
651 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
654 Res = LHS.Val & RHS.Val;
657 Res = LHS.Val ^ RHS.Val;
660 Res = LHS.Val | RHS.Val;
663 Res = (LHS.Val != 0 && RHS.Val != 0);
664 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
667 Res = (LHS.Val != 0 || RHS.Val != 0);
668 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
671 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
672 // if not being evaluated.
673 if (!PP.getLangOpts().C99 || ValueLive)
674 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
675 << LHS.getRange() << RHS.getRange();
676 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
678 case tok::question: {
679 // Parse the : part of the expression.
680 if (PeekTok.isNot(tok::colon)) {
681 PP.Diag(PeekTok.getLocation(), diag::err_expected)
682 << tok::colon << LHS.getRange() << RHS.getRange();
683 PP.Diag(OpLoc, diag::note_matching) << tok::question;
687 PP.LexNonComment(PeekTok);
689 // Evaluate the value after the :.
690 bool AfterColonLive = ValueLive && LHS.Val == 0;
691 PPValue AfterColonVal(LHS.getBitWidth());
693 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
696 // Parse anything after the : with the same precedence as ?. We allow
697 // things of equal precedence because ?: is right associative.
698 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
699 PeekTok, AfterColonLive, PP))
702 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
703 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
704 RHS.setEnd(AfterColonVal.getRange().getEnd());
706 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
707 // either operand is unsigned.
708 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
710 // Figure out the precedence of the token after the : part.
711 PeekPrec = getPrecedence(PeekTok.getKind());
715 // Don't allow :'s to float around without being part of ?: exprs.
716 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
717 << LHS.getRange() << RHS.getRange();
721 // If this operator is live and overflowed, report the issue.
722 if (Overflow && ValueLive)
723 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
724 << LHS.getRange() << RHS.getRange();
726 // Put the result back into 'LHS' for our next iteration.
728 LHS.setEnd(RHS.getRange().getEnd());
732 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
733 /// may occur after a #if or #elif directive. If the expression is equivalent
734 /// to "!defined(X)" return X in IfNDefMacro.
736 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
737 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
738 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
739 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
740 // in which case a directive is undefined behavior. We want macros to be able
741 // to recursively expand in order to get more gcc-list behavior, so we force
742 // DisableMacroExpansion to false and restore it when we're done parsing the
744 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
745 DisableMacroExpansion = false;
747 // Peek ahead one token.
751 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
752 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
754 PPValue ResVal(BitWidth);
756 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
757 // Parse error, skip the rest of the macro line.
758 if (Tok.isNot(tok::eod))
759 DiscardUntilEndOfDirective();
761 // Restore 'DisableMacroExpansion'.
762 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
766 // If we are at the end of the expression after just parsing a value, there
767 // must be no (unparenthesized) binary operators involved, so we can exit
769 if (Tok.is(tok::eod)) {
770 // If the expression we parsed was of the form !defined(macro), return the
771 // macro in IfNDefMacro.
772 if (DT.State == DefinedTracker::NotDefinedMacro)
773 IfNDefMacro = DT.TheMacro;
775 // Restore 'DisableMacroExpansion'.
776 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
777 return ResVal.Val != 0;
780 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
781 // operator and the stuff after it.
782 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
784 // Parse error, skip the rest of the macro line.
785 if (Tok.isNot(tok::eod))
786 DiscardUntilEndOfDirective();
788 // Restore 'DisableMacroExpansion'.
789 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
793 // If we aren't at the tok::eod token, something bad happened, like an extra
795 if (Tok.isNot(tok::eod)) {
796 Diag(Tok, diag::err_pp_expected_eol);
797 DiscardUntilEndOfDirective();
800 // Restore 'DisableMacroExpansion'.
801 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
802 return ResVal.Val != 0;