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/Lex/MacroInfo.h"
21 #include "clang/Lex/LiteralSupport.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "llvm/ADT/APSInt.h"
26 #include "llvm/Support/ErrorHandling.h"
27 using namespace clang;
31 /// PPValue - Represents the value of a subexpression of a preprocessor
32 /// conditional and the source range covered by it.
38 // Default ctor - Construct an 'invalid' PPValue.
39 PPValue(unsigned BitWidth) : Val(BitWidth) {}
41 unsigned getBitWidth() const { return Val.getBitWidth(); }
42 bool isUnsigned() const { return Val.isUnsigned(); }
44 const SourceRange &getRange() const { return Range; }
46 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
47 void setRange(SourceLocation B, SourceLocation E) {
48 Range.setBegin(B); Range.setEnd(E);
50 void setBegin(SourceLocation L) { Range.setBegin(L); }
51 void setEnd(SourceLocation L) { Range.setEnd(L); }
56 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
57 Token &PeekTok, bool ValueLive,
60 /// DefinedTracker - This struct is used while parsing expressions to keep track
61 /// of whether !defined(X) has been seen.
63 /// With this simple scheme, we handle the basic forms:
64 /// !defined(X) and !defined X
65 /// but we also trivially handle (silly) stuff like:
66 /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
67 struct DefinedTracker {
68 /// Each time a Value is evaluated, it returns information about whether the
69 /// parsed value is of the form defined(X), !defined(X) or is something else.
71 DefinedMacro, // defined(X)
72 NotDefinedMacro, // !defined(X)
73 Unknown // Something else.
75 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
76 /// indicates the macro that was checked.
77 IdentifierInfo *TheMacro;
80 /// EvaluateDefined - Process a 'defined(sym)' expression.
81 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
82 bool ValueLive, Preprocessor &PP) {
84 Result.setBegin(PeekTok.getLocation());
86 // Get the next token, don't expand it.
87 PP.LexUnexpandedNonComment(PeekTok);
89 // Two options, it can either be a pp-identifier or a (.
90 SourceLocation LParenLoc;
91 if (PeekTok.is(tok::l_paren)) {
92 // Found a paren, remember we saw it and skip it.
93 LParenLoc = PeekTok.getLocation();
94 PP.LexUnexpandedNonComment(PeekTok);
97 if (PeekTok.is(tok::code_completion)) {
98 if (PP.getCodeCompletionHandler())
99 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
100 PP.setCodeCompletionReached();
101 PP.LexUnexpandedNonComment(PeekTok);
104 // If we don't have a pp-identifier now, this is an error.
105 if ((II = PeekTok.getIdentifierInfo()) == 0) {
106 PP.Diag(PeekTok, diag::err_pp_defined_requires_identifier);
110 // Otherwise, we got an identifier, is it defined to something?
111 Result.Val = II->hasMacroDefinition();
112 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
114 // If there is a macro, mark it used.
115 if (Result.Val != 0 && ValueLive) {
116 MacroInfo *Macro = PP.getMacroInfo(II);
117 PP.markMacroAsUsed(Macro);
120 // Invoke the 'defined' callback.
121 if (PPCallbacks *Callbacks = PP.getPPCallbacks())
122 Callbacks->Defined(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_missing_rparen) << "defined";
132 PP.Diag(LParenLoc, diag::note_matching) << "(";
136 Result.setEnd(PeekTok.getLocation());
137 PP.LexNonComment(PeekTok);
139 // Consume identifier.
140 Result.setEnd(PeekTok.getLocation());
141 PP.LexNonComment(PeekTok);
144 // Success, remember that we saw defined(X).
145 DT.State = DefinedTracker::DefinedMacro;
150 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
151 /// return the computed value in Result. Return true if there was an error
152 /// parsing. This function also returns information about the form of the
153 /// expression in DT. See above for information on what DT means.
155 /// If ValueLive is false, then this value is being evaluated in a context where
156 /// the result is not used. As such, avoid diagnostics that relate to
158 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
159 bool ValueLive, Preprocessor &PP) {
160 DT.State = DefinedTracker::Unknown;
162 if (PeekTok.is(tok::code_completion)) {
163 if (PP.getCodeCompletionHandler())
164 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
165 PP.setCodeCompletionReached();
166 PP.LexNonComment(PeekTok);
169 // If this token's spelling is a pp-identifier, check to see if it is
170 // 'defined' or if it is a macro. Note that we check here because many
171 // keywords are pp-identifiers, so we can't check the kind.
172 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
173 // Handle "defined X" and "defined(X)".
174 if (II->isStr("defined"))
175 return(EvaluateDefined(Result, PeekTok, DT, ValueLive, PP));
177 // If this identifier isn't 'defined' or one of the special
178 // preprocessor keywords and it wasn't macro expanded, it turns
179 // into a simple 0, unless it is the C++ keyword "true", in which case it
182 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
183 Result.Val = II->getTokenID() == tok::kw_true;
184 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
185 Result.setRange(PeekTok.getLocation());
186 PP.LexNonComment(PeekTok);
190 switch (PeekTok.getKind()) {
191 default: // Non-value token.
192 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
196 // If there is no expression, report and exit.
197 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
199 case tok::numeric_constant: {
200 SmallString<64> IntegerBuffer;
201 bool NumberInvalid = false;
202 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
205 return true; // a diagnostic was already reported
207 NumericLiteralParser Literal(Spelling.begin(), Spelling.end(),
208 PeekTok.getLocation(), PP);
209 if (Literal.hadError)
210 return true; // a diagnostic was already reported.
212 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
213 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
216 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
218 // Complain about, and drop, any ud-suffix.
219 if (Literal.hasUDSuffix())
220 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
222 // long long is a C99 feature.
223 if (!PP.getLangOpts().C99 && Literal.isLongLong)
224 PP.Diag(PeekTok, PP.getLangOpts().CPlusPlus0x ?
225 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
227 // Parse the integer literal into Result.
228 if (Literal.GetIntegerValue(Result.Val)) {
229 // Overflow parsing integer literal.
230 if (ValueLive) PP.Diag(PeekTok, diag::warn_integer_too_large);
231 Result.Val.setIsUnsigned(true);
233 // Set the signedness of the result to match whether there was a U suffix
235 Result.Val.setIsUnsigned(Literal.isUnsigned);
237 // Detect overflow based on whether the value is signed. If signed
238 // and if the value is too large, emit a warning "integer constant is so
239 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
241 if (!Literal.isUnsigned && Result.Val.isNegative()) {
242 // Don't warn for a hex literal: 0x8000..0 shouldn't warn.
243 if (ValueLive && Literal.getRadix() != 16)
244 PP.Diag(PeekTok, diag::warn_integer_too_large_for_signed);
245 Result.Val.setIsUnsigned(true);
249 // Consume the token.
250 Result.setRange(PeekTok.getLocation());
251 PP.LexNonComment(PeekTok);
254 case tok::char_constant: // 'x'
255 case tok::wide_char_constant: { // L'x'
256 case tok::utf16_char_constant: // u'x'
257 case tok::utf32_char_constant: // U'x'
258 // Complain about, and drop, any ud-suffix.
259 if (PeekTok.hasUDSuffix())
260 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
262 SmallString<32> CharBuffer;
263 bool CharInvalid = false;
264 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
268 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
269 PeekTok.getLocation(), PP, PeekTok.getKind());
270 if (Literal.hadError())
271 return true; // A diagnostic was already emitted.
273 // Character literals are always int or wchar_t, expand to intmax_t.
274 const TargetInfo &TI = PP.getTargetInfo();
276 if (Literal.isMultiChar())
277 NumBits = TI.getIntWidth();
278 else if (Literal.isWide())
279 NumBits = TI.getWCharWidth();
280 else if (Literal.isUTF16())
281 NumBits = TI.getChar16Width();
282 else if (Literal.isUTF32())
283 NumBits = TI.getChar32Width();
285 NumBits = TI.getCharWidth();
288 llvm::APSInt Val(NumBits);
290 Val = Literal.getValue();
291 // Set the signedness. UTF-16 and UTF-32 are always unsigned
292 if (!Literal.isUTF16() && !Literal.isUTF32())
293 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
295 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
296 Result.Val = Val.extend(Result.Val.getBitWidth());
298 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
299 "intmax_t smaller than char/wchar_t?");
303 // Consume the token.
304 Result.setRange(PeekTok.getLocation());
305 PP.LexNonComment(PeekTok);
309 SourceLocation Start = PeekTok.getLocation();
310 PP.LexNonComment(PeekTok); // Eat the (.
311 // Parse the value and if there are any binary operators involved, parse
313 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
315 // If this is a silly value like (X), which doesn't need parens, check for
317 if (PeekTok.is(tok::r_paren)) {
318 // Just use DT unmodified as our result.
320 // Otherwise, we have something like (x+y), and we consumed '(x'.
321 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive, PP))
324 if (PeekTok.isNot(tok::r_paren)) {
325 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
326 << Result.getRange();
327 PP.Diag(Start, diag::note_matching) << "(";
330 DT.State = DefinedTracker::Unknown;
332 Result.setRange(Start, PeekTok.getLocation());
333 PP.LexNonComment(PeekTok); // Eat the ).
337 SourceLocation Start = PeekTok.getLocation();
338 // Unary plus doesn't modify the value.
339 PP.LexNonComment(PeekTok);
340 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
341 Result.setBegin(Start);
345 SourceLocation Loc = PeekTok.getLocation();
346 PP.LexNonComment(PeekTok);
347 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
348 Result.setBegin(Loc);
350 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
351 Result.Val = -Result.Val;
353 // -MININT is the only thing that overflows. Unsigned never overflows.
354 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
356 // If this operator is live and overflowed, report the issue.
357 if (Overflow && ValueLive)
358 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
360 DT.State = DefinedTracker::Unknown;
365 SourceLocation Start = PeekTok.getLocation();
366 PP.LexNonComment(PeekTok);
367 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
368 Result.setBegin(Start);
370 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
371 Result.Val = ~Result.Val;
372 DT.State = DefinedTracker::Unknown;
377 SourceLocation Start = PeekTok.getLocation();
378 PP.LexNonComment(PeekTok);
379 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
380 Result.setBegin(Start);
381 Result.Val = !Result.Val;
382 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
383 Result.Val.setIsUnsigned(false);
385 if (DT.State == DefinedTracker::DefinedMacro)
386 DT.State = DefinedTracker::NotDefinedMacro;
387 else if (DT.State == DefinedTracker::NotDefinedMacro)
388 DT.State = DefinedTracker::DefinedMacro;
392 // FIXME: Handle #assert
398 /// getPrecedence - Return the precedence of the specified binary operator
399 /// token. This returns:
400 /// ~0 - Invalid token.
401 /// 14 -> 3 - various operators.
403 static unsigned getPrecedence(tok::TokenKind Kind) {
408 case tok::star: return 14;
410 case tok::minus: return 13;
412 case tok::greatergreater: return 12;
415 case tok::greaterequal:
416 case tok::greater: return 11;
417 case tok::exclaimequal:
418 case tok::equalequal: return 10;
419 case tok::amp: return 9;
420 case tok::caret: return 8;
421 case tok::pipe: return 7;
422 case tok::ampamp: return 6;
423 case tok::pipepipe: return 5;
424 case tok::question: return 4;
425 case tok::comma: return 3;
426 case tok::colon: return 2;
427 case tok::r_paren: return 0;// Lowest priority, end of expr.
428 case tok::eod: return 0;// Lowest priority, end of directive.
433 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
434 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
436 /// If ValueLive is false, then this value is being evaluated in a context where
437 /// the result is not used. As such, avoid diagnostics that relate to
438 /// evaluation, such as division by zero warnings.
439 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
440 Token &PeekTok, bool ValueLive,
442 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
443 // If this token isn't valid, report the error.
444 if (PeekPrec == ~0U) {
445 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
451 // If this token has a lower precedence than we are allowed to parse, return
452 // it so that higher levels of the recursion can parse it.
453 if (PeekPrec < MinPrec)
456 tok::TokenKind Operator = PeekTok.getKind();
458 // If this is a short-circuiting operator, see if the RHS of the operator is
459 // dead. Note that this cannot just clobber ValueLive. Consider
460 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
461 // this example, the RHS of the && being dead does not make the rest of the
464 if (Operator == tok::ampamp && LHS.Val == 0)
465 RHSIsLive = false; // RHS of "0 && x" is dead.
466 else if (Operator == tok::pipepipe && LHS.Val != 0)
467 RHSIsLive = false; // RHS of "1 || x" is dead.
468 else if (Operator == tok::question && LHS.Val == 0)
469 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
471 RHSIsLive = ValueLive;
473 // Consume the operator, remembering the operator's location for reporting.
474 SourceLocation OpLoc = PeekTok.getLocation();
475 PP.LexNonComment(PeekTok);
477 PPValue RHS(LHS.getBitWidth());
478 // Parse the RHS of the operator.
480 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
482 // Remember the precedence of this operator and get the precedence of the
483 // operator immediately to the right of the RHS.
484 unsigned ThisPrec = PeekPrec;
485 PeekPrec = getPrecedence(PeekTok.getKind());
487 // If this token isn't valid, report the error.
488 if (PeekPrec == ~0U) {
489 PP.Diag(PeekTok.getLocation(), diag::err_pp_expr_bad_token_binop)
494 // Decide whether to include the next binop in this subexpression. For
495 // example, when parsing x+y*z and looking at '*', we want to recursively
496 // handle y*z as a single subexpression. We do this because the precedence
497 // of * is higher than that of +. The only strange case we have to handle
498 // here is for the ?: operator, where the precedence is actually lower than
499 // the LHS of the '?'. The grammar rule is:
501 // conditional-expression ::=
502 // logical-OR-expression ? expression : conditional-expression
503 // where 'expression' is actually comma-expression.
505 if (Operator == tok::question)
506 // The RHS of "?" should be maximally consumed as an expression.
507 RHSPrec = getPrecedence(tok::comma);
508 else // All others should munch while higher precedence.
509 RHSPrec = ThisPrec+1;
511 if (PeekPrec >= RHSPrec) {
512 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive, PP))
514 PeekPrec = getPrecedence(PeekTok.getKind());
516 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
518 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
519 // either operand is unsigned.
520 llvm::APSInt Res(LHS.getBitWidth());
522 case tok::question: // No UAC for x and y in "x ? y : z".
523 case tok::lessless: // Shift amount doesn't UAC with shift value.
524 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
525 case tok::comma: // Comma operands are not subject to UACs.
526 case tok::pipepipe: // Logical || does not do UACs.
527 case tok::ampamp: // Logical && does not do UACs.
530 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
531 // If this just promoted something from signed to unsigned, and if the
532 // value was negative, warn about it.
533 if (ValueLive && Res.isUnsigned()) {
534 if (!LHS.isUnsigned() && LHS.Val.isNegative())
535 PP.Diag(OpLoc, diag::warn_pp_convert_lhs_to_positive)
536 << LHS.Val.toString(10, true) + " to " +
537 LHS.Val.toString(10, false)
538 << LHS.getRange() << RHS.getRange();
539 if (!RHS.isUnsigned() && RHS.Val.isNegative())
540 PP.Diag(OpLoc, diag::warn_pp_convert_rhs_to_positive)
541 << RHS.Val.toString(10, true) + " to " +
542 RHS.Val.toString(10, false)
543 << LHS.getRange() << RHS.getRange();
545 LHS.Val.setIsUnsigned(Res.isUnsigned());
546 RHS.Val.setIsUnsigned(Res.isUnsigned());
549 bool Overflow = false;
551 default: llvm_unreachable("Unknown operator token!");
554 Res = LHS.Val % RHS.Val;
555 else if (ValueLive) {
556 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
557 << LHS.getRange() << RHS.getRange();
563 if (LHS.Val.isSigned())
564 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
566 Res = LHS.Val / RHS.Val;
567 } else if (ValueLive) {
568 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
569 << LHS.getRange() << RHS.getRange();
576 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
578 Res = LHS.Val * RHS.Val;
580 case tok::lessless: {
581 // Determine whether overflow is about to happen.
582 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
583 if (LHS.isUnsigned()) {
584 Overflow = ShAmt >= LHS.Val.getBitWidth();
586 ShAmt = LHS.Val.getBitWidth()-1;
587 Res = LHS.Val << ShAmt;
589 Res = llvm::APSInt(LHS.Val.sshl_ov(ShAmt, Overflow), false);
593 case tok::greatergreater: {
594 // Determine whether overflow is about to happen.
595 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
596 if (ShAmt >= LHS.getBitWidth())
597 Overflow = true, ShAmt = LHS.getBitWidth()-1;
598 Res = LHS.Val >> ShAmt;
602 if (LHS.isUnsigned())
603 Res = LHS.Val + RHS.Val;
605 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
608 if (LHS.isUnsigned())
609 Res = LHS.Val - RHS.Val;
611 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
614 Res = LHS.Val <= RHS.Val;
615 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
618 Res = LHS.Val < RHS.Val;
619 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
621 case tok::greaterequal:
622 Res = LHS.Val >= RHS.Val;
623 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
626 Res = LHS.Val > RHS.Val;
627 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
629 case tok::exclaimequal:
630 Res = LHS.Val != RHS.Val;
631 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
633 case tok::equalequal:
634 Res = LHS.Val == RHS.Val;
635 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
638 Res = LHS.Val & RHS.Val;
641 Res = LHS.Val ^ RHS.Val;
644 Res = LHS.Val | RHS.Val;
647 Res = (LHS.Val != 0 && RHS.Val != 0);
648 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
651 Res = (LHS.Val != 0 || RHS.Val != 0);
652 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
655 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
656 // if not being evaluated.
657 if (!PP.getLangOpts().C99 || ValueLive)
658 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
659 << LHS.getRange() << RHS.getRange();
660 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
662 case tok::question: {
663 // Parse the : part of the expression.
664 if (PeekTok.isNot(tok::colon)) {
665 PP.Diag(PeekTok.getLocation(), diag::err_expected_colon)
666 << LHS.getRange(), RHS.getRange();
667 PP.Diag(OpLoc, diag::note_matching) << "?";
671 PP.LexNonComment(PeekTok);
673 // Evaluate the value after the :.
674 bool AfterColonLive = ValueLive && LHS.Val == 0;
675 PPValue AfterColonVal(LHS.getBitWidth());
677 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
680 // Parse anything after the : with the same precedence as ?. We allow
681 // things of equal precedence because ?: is right associative.
682 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
683 PeekTok, AfterColonLive, PP))
686 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
687 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
688 RHS.setEnd(AfterColonVal.getRange().getEnd());
690 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
691 // either operand is unsigned.
692 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
694 // Figure out the precedence of the token after the : part.
695 PeekPrec = getPrecedence(PeekTok.getKind());
699 // Don't allow :'s to float around without being part of ?: exprs.
700 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
701 << LHS.getRange() << RHS.getRange();
705 // If this operator is live and overflowed, report the issue.
706 if (Overflow && ValueLive)
707 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
708 << LHS.getRange() << RHS.getRange();
710 // Put the result back into 'LHS' for our next iteration.
712 LHS.setEnd(RHS.getRange().getEnd());
716 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
717 /// may occur after a #if or #elif directive. If the expression is equivalent
718 /// to "!defined(X)" return X in IfNDefMacro.
720 EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
721 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
722 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
723 // in which case a directive is undefined behavior. We want macros to be able
724 // to recursively expand in order to get more gcc-list behavior, so we force
725 // DisableMacroExpansion to false and restore it when we're done parsing the
727 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
728 DisableMacroExpansion = false;
730 // Peek ahead one token.
734 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
735 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
737 PPValue ResVal(BitWidth);
739 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
740 // Parse error, skip the rest of the macro line.
741 if (Tok.isNot(tok::eod))
742 DiscardUntilEndOfDirective();
744 // Restore 'DisableMacroExpansion'.
745 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
749 // If we are at the end of the expression after just parsing a value, there
750 // must be no (unparenthesized) binary operators involved, so we can exit
752 if (Tok.is(tok::eod)) {
753 // If the expression we parsed was of the form !defined(macro), return the
754 // macro in IfNDefMacro.
755 if (DT.State == DefinedTracker::NotDefinedMacro)
756 IfNDefMacro = DT.TheMacro;
758 // Restore 'DisableMacroExpansion'.
759 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
760 return ResVal.Val != 0;
763 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
764 // operator and the stuff after it.
765 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
767 // Parse error, skip the rest of the macro line.
768 if (Tok.isNot(tok::eod))
769 DiscardUntilEndOfDirective();
771 // Restore 'DisableMacroExpansion'.
772 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
776 // If we aren't at the tok::eod token, something bad happened, like an extra
778 if (Tok.isNot(tok::eod)) {
779 Diag(Tok, diag::err_pp_expected_eol);
780 DiscardUntilEndOfDirective();
783 // Restore 'DisableMacroExpansion'.
784 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
785 return ResVal.Val != 0;