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 SourceLocation beginLoc(PeekTok.getLocation());
86 Result.setBegin(beginLoc);
88 // Get the next token, don't expand it.
89 PP.LexUnexpandedNonComment(PeekTok);
91 // Two options, it can either be a pp-identifier or a (.
92 SourceLocation LParenLoc;
93 if (PeekTok.is(tok::l_paren)) {
94 // Found a paren, remember we saw it and skip it.
95 LParenLoc = PeekTok.getLocation();
96 PP.LexUnexpandedNonComment(PeekTok);
99 if (PeekTok.is(tok::code_completion)) {
100 if (PP.getCodeCompletionHandler())
101 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
102 PP.setCodeCompletionReached();
103 PP.LexUnexpandedNonComment(PeekTok);
106 // If we don't have a pp-identifier now, this is an error.
107 if ((II = PeekTok.getIdentifierInfo()) == 0) {
108 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
112 // Otherwise, we got an identifier, is it defined to something?
113 Result.Val = II->hasMacroDefinition();
114 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
116 MacroDirective *Macro = 0;
117 // If there is a macro, mark it used.
118 if (Result.Val != 0 && ValueLive) {
119 Macro = PP.getMacroDirective(II);
120 PP.markMacroAsUsed(Macro->getMacroInfo());
123 // Save macro token for callback.
124 Token macroToken(PeekTok);
126 // If we are in parens, ensure we have a trailing ).
127 if (LParenLoc.isValid()) {
128 // Consume identifier.
129 Result.setEnd(PeekTok.getLocation());
130 PP.LexUnexpandedNonComment(PeekTok);
132 if (PeekTok.isNot(tok::r_paren)) {
133 PP.Diag(PeekTok.getLocation(), diag::err_pp_missing_rparen) << "defined";
134 PP.Diag(LParenLoc, diag::note_matching) << "(";
138 Result.setEnd(PeekTok.getLocation());
139 PP.LexNonComment(PeekTok);
141 // Consume identifier.
142 Result.setEnd(PeekTok.getLocation());
143 PP.LexNonComment(PeekTok);
146 // Invoke the 'defined' callback.
147 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
148 MacroDirective *MD = Macro;
149 // Pass the MacroInfo for the macro name even if the value is dead.
150 if (!MD && Result.Val != 0)
151 MD = PP.getMacroDirective(II);
152 Callbacks->Defined(macroToken, MD,
153 SourceRange(beginLoc, PeekTok.getLocation()));
156 // Success, remember that we saw defined(X).
157 DT.State = DefinedTracker::DefinedMacro;
162 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
163 /// return the computed value in Result. Return true if there was an error
164 /// parsing. This function also returns information about the form of the
165 /// expression in DT. See above for information on what DT means.
167 /// If ValueLive is false, then this value is being evaluated in a context where
168 /// the result is not used. As such, avoid diagnostics that relate to
170 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
171 bool ValueLive, Preprocessor &PP) {
172 DT.State = DefinedTracker::Unknown;
174 if (PeekTok.is(tok::code_completion)) {
175 if (PP.getCodeCompletionHandler())
176 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
177 PP.setCodeCompletionReached();
178 PP.LexNonComment(PeekTok);
181 // If this token's spelling is a pp-identifier, check to see if it is
182 // 'defined' or if it is a macro. Note that we check here because many
183 // keywords are pp-identifiers, so we can't check the kind.
184 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
185 // Handle "defined X" and "defined(X)".
186 if (II->isStr("defined"))
187 return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
189 // If this identifier isn't 'defined' or one of the special
190 // preprocessor keywords and it wasn't macro expanded, it turns
191 // into a simple 0, unless it is the C++ keyword "true", in which case it
194 II->getTokenID() != tok::kw_true &&
195 II->getTokenID() != tok::kw_false)
196 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
197 Result.Val = II->getTokenID() == tok::kw_true;
198 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
199 Result.setRange(PeekTok.getLocation());
200 PP.LexNonComment(PeekTok);
204 switch (PeekTok.getKind()) {
205 default: // Non-value token.
206 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
210 // If there is no expression, report and exit.
211 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
213 case tok::numeric_constant: {
214 SmallString<64> IntegerBuffer;
215 bool NumberInvalid = false;
216 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
219 return true; // a diagnostic was already reported
221 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(), PP);
222 if (Literal.hadError)
223 return true; // a diagnostic was already reported.
225 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
226 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
229 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
231 // Complain about, and drop, any ud-suffix.
232 if (Literal.hasUDSuffix())
233 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
235 // 'long long' is a C99 or C++11 feature.
236 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
237 if (PP.getLangOpts().CPlusPlus)
239 PP.getLangOpts().CPlusPlus11 ?
240 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
242 PP.Diag(PeekTok, diag::ext_c99_longlong);
245 // Parse the integer literal into Result.
246 if (Literal.GetIntegerValue(Result.Val)) {
247 // Overflow parsing integer literal.
248 if (ValueLive) PP.Diag(PeekTok, diag::err_integer_too_large);
249 Result.Val.setIsUnsigned(true);
251 // Set the signedness of the result to match whether there was a U suffix
253 Result.Val.setIsUnsigned(Literal.isUnsigned);
255 // Detect overflow based on whether the value is signed. If signed
256 // and if the value is too large, emit a warning "integer constant is so
257 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
259 if (!Literal.isUnsigned && Result.Val.isNegative()) {
260 // Don't warn for a hex or octal literal: 0x8000..0 shouldn't warn.
261 if (ValueLive && Literal.getRadix() == 10)
262 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
263 Result.Val.setIsUnsigned(true);
267 // Consume the token.
268 Result.setRange(PeekTok.getLocation());
269 PP.LexNonComment(PeekTok);
272 case tok::char_constant: // 'x'
273 case tok::wide_char_constant: // L'x'
274 case tok::utf16_char_constant: // u'x'
275 case tok::utf32_char_constant: { // U'x'
276 // Complain about, and drop, any ud-suffix.
277 if (PeekTok.hasUDSuffix())
278 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
280 SmallString<32> CharBuffer;
281 bool CharInvalid = false;
282 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
286 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
287 PeekTok.getLocation(), PP, PeekTok.getKind());
288 if (Literal.hadError())
289 return true; // A diagnostic was already emitted.
291 // Character literals are always int or wchar_t, expand to intmax_t.
292 const TargetInfo &TI = PP.getTargetInfo();
294 if (Literal.isMultiChar())
295 NumBits = TI.getIntWidth();
296 else if (Literal.isWide())
297 NumBits = TI.getWCharWidth();
298 else if (Literal.isUTF16())
299 NumBits = TI.getChar16Width();
300 else if (Literal.isUTF32())
301 NumBits = TI.getChar32Width();
303 NumBits = TI.getCharWidth();
306 llvm::APSInt Val(NumBits);
308 Val = Literal.getValue();
309 // Set the signedness. UTF-16 and UTF-32 are always unsigned
310 if (!Literal.isUTF16() && !Literal.isUTF32())
311 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
313 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
314 Result.Val = Val.extend(Result.Val.getBitWidth());
316 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
317 "intmax_t smaller than char/wchar_t?");
321 // Consume the token.
322 Result.setRange(PeekTok.getLocation());
323 PP.LexNonComment(PeekTok);
327 SourceLocation Start = PeekTok.getLocation();
328 PP.LexNonComment(PeekTok); // Eat the (.
329 // Parse the value and if there are any binary operators involved, parse
331 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
333 // If this is a silly value like (X), which doesn't need parens, check for
335 if (PeekTok.is(tok::r_paren)) {
336 // Just use DT unmodified as our result.
338 // Otherwise, we have something like (x+y), and we consumed '(x'.
339 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
342 if (PeekTok.isNot(tok::r_paren)) {
343 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
344 << Result.getRange();
345 PP.Diag(Start, diag::note_matching) << "(";
348 DT.State = DefinedTracker::Unknown;
350 Result.setRange(Start, PeekTok.getLocation());
351 PP.LexNonComment(PeekTok); // Eat the ).
355 SourceLocation Start = PeekTok.getLocation();
356 // Unary plus doesn't modify the value.
357 PP.LexNonComment(PeekTok);
358 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
359 Result.setBegin(Start);
363 SourceLocation Loc = PeekTok.getLocation();
364 PP.LexNonComment(PeekTok);
365 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
366 Result.setBegin(Loc);
368 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
369 Result.Val = -Result.Val;
371 // -MININT is the only thing that overflows. Unsigned never overflows.
372 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
374 // If this operator is live and overflowed, report the issue.
375 if (Overflow && ValueLive)
376 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
378 DT.State = DefinedTracker::Unknown;
383 SourceLocation Start = PeekTok.getLocation();
384 PP.LexNonComment(PeekTok);
385 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
386 Result.setBegin(Start);
388 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
389 Result.Val = ~Result.Val;
390 DT.State = DefinedTracker::Unknown;
395 SourceLocation Start = PeekTok.getLocation();
396 PP.LexNonComment(PeekTok);
397 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
398 Result.setBegin(Start);
399 Result.Val = !Result.Val;
400 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
401 Result.Val.setIsUnsigned(false);
403 if (DT.State == DefinedTracker::DefinedMacro)
404 DT.State = DefinedTracker::NotDefinedMacro;
405 else if (DT.State == DefinedTracker::NotDefinedMacro)
406 DT.State = DefinedTracker::DefinedMacro;
410 // FIXME: Handle #assert
416 /// getPrecedence - Return the precedence of the specified binary operator
417 /// token. This returns:
418 /// ~0 - Invalid token.
419 /// 14 -> 3 - various operators.
421 static unsigned getPrecedence(tok::TokenKind Kind) {
426 case tok::star: return 14;
428 case tok::minus: return 13;
430 case tok::greatergreater: return 12;
433 case tok::greaterequal:
434 case tok::greater: return 11;
435 case tok::exclaimequal:
436 case tok::equalequal: return 10;
437 case tok::amp: return 9;
438 case tok::caret: return 8;
439 case tok::pipe: return 7;
440 case tok::ampamp: return 6;
441 case tok::pipepipe: return 5;
442 case tok::question: return 4;
443 case tok::comma: return 3;
444 case tok::colon: return 2;
445 case tok::r_paren: return 0;// Lowest priority, end of expr.
446 case tok::eod: return 0;// Lowest priority, end of directive.
451 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
452 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
454 /// If ValueLive is false, then this value is being evaluated in a context where
455 /// the result is not used. As such, avoid diagnostics that relate to
456 /// evaluation, such as division by zero warnings.
457 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
458 Token &PeekTok, bool ValueLive,
460 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
461 // If this token isn't valid, report the error.
462 if (PeekPrec == ~0U) {
463 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
469 // If this token has a lower precedence than we are allowed to parse, return
470 // it so that higher levels of the recursion can parse it.
471 if (PeekPrec < MinPrec)
474 tok::TokenKind Operator = PeekTok.getKind();
476 // If this is a short-circuiting operator, see if the RHS of the operator is
477 // dead. Note that this cannot just clobber ValueLive. Consider
478 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
479 // this example, the RHS of the && being dead does not make the rest of the
482 if (Operator == tok::ampamp && LHS.Val == 0)
483 RHSIsLive = false; // RHS of "0 && x" is dead.
484 else if (Operator == tok::pipepipe && LHS.Val != 0)
485 RHSIsLive = false; // RHS of "1 || x" is dead.
486 else if (Operator == tok::question && LHS.Val == 0)
487 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
489 RHSIsLive = ValueLive;
491 // Consume the operator, remembering the operator's location for reporting.
492 SourceLocation OpLoc = PeekTok.getLocation();
493 PP.LexNonComment(PeekTok);
495 PPValue RHS(LHS.getBitWidth());
496 // Parse the RHS of the operator.
498 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
500 // Remember the precedence of this operator and get the precedence of the
501 // operator immediately to the right of the RHS.
502 unsigned ThisPrec = PeekPrec;
503 PeekPrec = getPrecedence(PeekTok.getKind());
505 // If this token isn't valid, report the error.
506 if (PeekPrec == ~0U) {
507 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
512 // Decide whether to include the next binop in this subexpression. For
513 // example, when parsing x+y*z and looking at '*', we want to recursively
514 // handle y*z as a single subexpression. We do this because the precedence
515 // of * is higher than that of +. The only strange case we have to handle
516 // here is for the ?: operator, where the precedence is actually lower than
517 // the LHS of the '?'. The grammar rule is:
519 // conditional-expression ::=
520 // logical-OR-expression ? expression : conditional-expression
521 // where 'expression' is actually comma-expression.
523 if (Operator == tok::question)
524 // The RHS of "?" should be maximally consumed as an expression.
525 RHSPrec = getPrecedence(tok::comma);
526 else // All others should munch while higher precedence.
527 RHSPrec = ThisPrec+1;
529 if (PeekPrec >= RHSPrec) {
530 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
532 PeekPrec = getPrecedence(PeekTok.getKind());
534 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
536 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
537 // either operand is unsigned.
538 llvm::APSInt Res(LHS.getBitWidth());
540 case tok::question: // No UAC for x and y in "x ? y : z".
541 case tok::lessless: // Shift amount doesn't UAC with shift value.
542 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
543 case tok::comma: // Comma operands are not subject to UACs.
544 case tok::pipepipe: // Logical || does not do UACs.
545 case tok::ampamp: // Logical && does not do UACs.
548 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
549 // If this just promoted something from signed to unsigned, and if the
550 // value was negative, warn about it.
551 if (ValueLive && Res.isUnsigned()) {
552 if (!LHS.isUnsigned() && LHS.Val.isNegative())
553 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
554 << LHS.Val.toString(10, true) + " to " +
555 LHS.Val.toString(10, false)
556 << LHS.getRange() << RHS.getRange();
557 if (!RHS.isUnsigned() && RHS.Val.isNegative())
558 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
559 << RHS.Val.toString(10, true) + " to " +
560 RHS.Val.toString(10, false)
561 << LHS.getRange() << RHS.getRange();
563 LHS.Val.setIsUnsigned(Res.isUnsigned());
564 RHS.Val.setIsUnsigned(Res.isUnsigned());
567 bool Overflow = false;
569 default: llvm_unreachable("Unknown operator token!");
572 Res = LHS.Val % RHS.Val;
573 else if (ValueLive) {
574 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
575 << LHS.getRange() << RHS.getRange();
581 if (LHS.Val.isSigned())
582 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
584 Res = LHS.Val / RHS.Val;
585 } else if (ValueLive) {
586 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
587 << LHS.getRange() << RHS.getRange();
594 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
596 Res = LHS.Val * RHS.Val;
598 case tok::lessless: {
599 // Determine whether overflow is about to happen.
600 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
601 if (LHS.isUnsigned()) {
602 Overflow = ShAmt >= LHS.Val.getBitWidth();
604 ShAmt = LHS.Val.getBitWidth()-1;
605 Res = LHS.Val << ShAmt;
607 Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
611 case tok::greatergreater: {
612 // Determine whether overflow is about to happen.
613 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
614 if (ShAmt >= LHS.getBitWidth())
615 Overflow = true, ShAmt = LHS.getBitWidth()-1;
616 Res = LHS.Val >> ShAmt;
620 if (LHS.isUnsigned())
621 Res = LHS.Val + RHS.Val;
623 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
626 if (LHS.isUnsigned())
627 Res = LHS.Val - RHS.Val;
629 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
632 Res = LHS.Val <= RHS.Val;
633 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
636 Res = LHS.Val < RHS.Val;
637 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
639 case tok::greaterequal:
640 Res = LHS.Val >= RHS.Val;
641 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
644 Res = LHS.Val > RHS.Val;
645 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
647 case tok::exclaimequal:
648 Res = LHS.Val != RHS.Val;
649 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
651 case tok::equalequal:
652 Res = LHS.Val == RHS.Val;
653 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
656 Res = LHS.Val & RHS.Val;
659 Res = LHS.Val ^ RHS.Val;
662 Res = LHS.Val | RHS.Val;
665 Res = (LHS.Val != 0 && RHS.Val != 0);
666 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
669 Res = (LHS.Val != 0 || RHS.Val != 0);
670 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
673 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
674 // if not being evaluated.
675 if (!PP.getLangOpts().C99 || ValueLive)
676 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
677 << LHS.getRange() << RHS.getRange();
678 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
680 case tok::question: {
681 // Parse the : part of the expression.
682 if (PeekTok.isNot(tok::colon)) {
683 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
684 << LHS.getRange(), RHS.getRange();
685 PP.Diag(OpLoc, diag::note_matching) << "?";
689 PP.LexNonComment(PeekTok);
691 // Evaluate the value after the :.
692 bool AfterColonLive = ValueLive && LHS.Val == 0;
693 PPValue AfterColonVal(LHS.getBitWidth());
695 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
698 // Parse anything after the : with the same precedence as ?. We allow
699 // things of equal precedence because ?: is right associative.
700 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
701 PeekTok, AfterColonLive, PP))
704 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
705 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
706 RHS.setEnd(AfterColonVal.getRange().getEnd());
708 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
709 // either operand is unsigned.
710 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
712 // Figure out the precedence of the token after the : part.
713 PeekPrec = getPrecedence(PeekTok.getKind());
717 // Don't allow :'s to float around without being part of ?: exprs.
718 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
719 << LHS.getRange() << RHS.getRange();
723 // If this operator is live and overflowed, report the issue.
724 if (Overflow && ValueLive)
725 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
726 << LHS.getRange() << RHS.getRange();
728 // Put the result back into 'LHS' for our next iteration.
730 LHS.setEnd(RHS.getRange().getEnd());
734 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
735 /// may occur after a #if or #elif directive. If the expression is equivalent
736 /// to "!defined(X)" return X in IfNDefMacro.
738 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
739 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
740 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
741 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
742 // in which case a directive is undefined behavior. We want macros to be able
743 // to recursively expand in order to get more gcc-list behavior, so we force
744 // DisableMacroExpansion to false and restore it when we're done parsing the
746 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
747 DisableMacroExpansion = false;
749 // Peek ahead one token.
753 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
754 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
756 PPValue ResVal(BitWidth);
758 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
759 // Parse error, skip the rest of the macro line.
760 if (Tok.isNot(tok::eod))
761 DiscardUntilEndOfDirective();
763 // Restore 'DisableMacroExpansion'.
764 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
768 // If we are at the end of the expression after just parsing a value, there
769 // must be no (unparenthesized) binary operators involved, so we can exit
771 if (Tok.is(tok::eod)) {
772 // If the expression we parsed was of the form !defined(macro), return the
773 // macro in IfNDefMacro.
774 if (DT.State == DefinedTracker::NotDefinedMacro)
775 IfNDefMacro = DT.TheMacro;
777 // Restore 'DisableMacroExpansion'.
778 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
779 return ResVal.Val != 0;
782 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
783 // operator and the stuff after it.
784 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
786 // Parse error, skip the rest of the macro line.
787 if (Tok.isNot(tok::eod))
788 DiscardUntilEndOfDirective();
790 // Restore 'DisableMacroExpansion'.
791 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
795 // If we aren't at the tok::eod token, something bad happened, like an extra
797 if (Tok.isNot(tok::eod)) {
798 Diag(Tok, diag::err_pp_expected_eol);
799 DiscardUntilEndOfDirective();
802 // Restore 'DisableMacroExpansion'.
803 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
804 return ResVal.Val != 0;