1 //===--- PPExpressions.cpp - Preprocessor Expression Evaluation -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Preprocessor::EvaluateDirectiveExpression method,
10 // which parses and evaluates integer constant expressions for #if directives.
12 //===----------------------------------------------------------------------===//
14 // FIXME: implement testing for #assert's.
16 //===----------------------------------------------------------------------===//
18 #include "clang/Basic/IdentifierTable.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TargetInfo.h"
22 #include "clang/Basic/TokenKinds.h"
23 #include "clang/Lex/CodeCompletionHandler.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "clang/Lex/MacroInfo.h"
27 #include "clang/Lex/PPCallbacks.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Lex/Token.h"
30 #include "llvm/ADT/APSInt.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/SaveAndRestore.h"
39 using namespace clang;
43 /// PPValue - Represents the value of a subexpression of a preprocessor
44 /// conditional and the source range covered by it.
52 // Default ctor - Construct an 'invalid' PPValue.
53 PPValue(unsigned BitWidth) : Val(BitWidth) {}
55 // If this value was produced by directly evaluating an identifier, produce
57 IdentifierInfo *getIdentifier() const { return II; }
58 void setIdentifier(IdentifierInfo *II) { this->II = II; }
60 unsigned getBitWidth() const { return Val.getBitWidth(); }
61 bool isUnsigned() const { return Val.isUnsigned(); }
63 SourceRange getRange() const { return Range; }
65 void setRange(SourceLocation L) { Range.setBegin(L); Range.setEnd(L); }
66 void setRange(SourceLocation B, SourceLocation E) {
67 Range.setBegin(B); Range.setEnd(E);
69 void setBegin(SourceLocation L) { Range.setBegin(L); }
70 void setEnd(SourceLocation L) { Range.setEnd(L); }
73 } // end anonymous namespace
75 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
76 Token &PeekTok, bool ValueLive,
77 bool &IncludedUndefinedIds,
80 /// DefinedTracker - This struct is used while parsing expressions to keep track
81 /// of whether !defined(X) has been seen.
83 /// With this simple scheme, we handle the basic forms:
84 /// !defined(X) and !defined X
85 /// but we also trivially handle (silly) stuff like:
86 /// !!!defined(X) and +!defined(X) and !+!+!defined(X) and !(defined(X)).
87 struct DefinedTracker {
88 /// Each time a Value is evaluated, it returns information about whether the
89 /// parsed value is of the form defined(X), !defined(X) or is something else.
91 DefinedMacro, // defined(X)
92 NotDefinedMacro, // !defined(X)
93 Unknown // Something else.
95 /// TheMacro - When the state is DefinedMacro or NotDefinedMacro, this
96 /// indicates the macro that was checked.
97 IdentifierInfo *TheMacro;
98 bool IncludedUndefinedIds = false;
101 /// EvaluateDefined - Process a 'defined(sym)' expression.
102 static bool EvaluateDefined(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
103 bool ValueLive, Preprocessor &PP) {
104 SourceLocation beginLoc(PeekTok.getLocation());
105 Result.setBegin(beginLoc);
107 // Get the next token, don't expand it.
108 PP.LexUnexpandedNonComment(PeekTok);
110 // Two options, it can either be a pp-identifier or a (.
111 SourceLocation LParenLoc;
112 if (PeekTok.is(tok::l_paren)) {
113 // Found a paren, remember we saw it and skip it.
114 LParenLoc = PeekTok.getLocation();
115 PP.LexUnexpandedNonComment(PeekTok);
118 if (PeekTok.is(tok::code_completion)) {
119 if (PP.getCodeCompletionHandler())
120 PP.getCodeCompletionHandler()->CodeCompleteMacroName(false);
121 PP.setCodeCompletionReached();
122 PP.LexUnexpandedNonComment(PeekTok);
125 // If we don't have a pp-identifier now, this is an error.
126 if (PP.CheckMacroName(PeekTok, MU_Other))
129 // Otherwise, we got an identifier, is it defined to something?
130 IdentifierInfo *II = PeekTok.getIdentifierInfo();
131 MacroDefinition Macro = PP.getMacroDefinition(II);
132 Result.Val = !!Macro;
133 Result.Val.setIsUnsigned(false); // Result is signed intmax_t.
134 DT.IncludedUndefinedIds = !Macro;
136 // If there is a macro, mark it used.
137 if (Result.Val != 0 && ValueLive)
138 PP.markMacroAsUsed(Macro.getMacroInfo());
140 // Save macro token for callback.
141 Token macroToken(PeekTok);
143 // If we are in parens, ensure we have a trailing ).
144 if (LParenLoc.isValid()) {
145 // Consume identifier.
146 Result.setEnd(PeekTok.getLocation());
147 PP.LexUnexpandedNonComment(PeekTok);
149 if (PeekTok.isNot(tok::r_paren)) {
150 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_after)
151 << "'defined'" << tok::r_paren;
152 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
156 PP.LexNonComment(PeekTok);
157 Result.setEnd(PeekTok.getLocation());
159 // Consume identifier.
160 Result.setEnd(PeekTok.getLocation());
161 PP.LexNonComment(PeekTok);
165 // Prior to evaluation, macro invocations in the list of preprocessing
166 // tokens that will become the controlling constant expression are replaced
167 // (except for those macro names modified by the 'defined' unary operator),
168 // just as in normal text. If the token 'defined' is generated as a result
169 // of this replacement process or use of the 'defined' unary operator does
170 // not match one of the two specified forms prior to macro replacement, the
171 // behavior is undefined.
172 // This isn't an idle threat, consider this program:
174 // #define BAR defined(FOO)
180 // clang and gcc will pick the #if branch while Visual Studio will take the
181 // #else branch. Emit a warning about this undefined behavior.
182 if (beginLoc.isMacroID()) {
183 bool IsFunctionTypeMacro =
184 PP.getSourceManager()
185 .getSLocEntry(PP.getSourceManager().getFileID(beginLoc))
187 .isFunctionMacroExpansion();
188 // For object-type macros, it's easy to replace
189 // #define FOO defined(BAR)
196 // and doing so makes sense since compilers handle this differently in
197 // practice (see example further up). But for function-type macros,
198 // there is no good way to write
199 // # define FOO(x) (defined(M_ ## x) && M_ ## x)
200 // in a different way, and compilers seem to agree on how to behave here.
201 // So warn by default on object-type macros, but only warn in -pedantic
202 // mode on function-type macros.
203 if (IsFunctionTypeMacro)
204 PP.Diag(beginLoc, diag::warn_defined_in_function_type_macro);
206 PP.Diag(beginLoc, diag::warn_defined_in_object_type_macro);
209 // Invoke the 'defined' callback.
210 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
211 Callbacks->Defined(macroToken, Macro,
212 SourceRange(beginLoc, PeekTok.getLocation()));
215 // Success, remember that we saw defined(X).
216 DT.State = DefinedTracker::DefinedMacro;
221 /// EvaluateValue - Evaluate the token PeekTok (and any others needed) and
222 /// return the computed value in Result. Return true if there was an error
223 /// parsing. This function also returns information about the form of the
224 /// expression in DT. See above for information on what DT means.
226 /// If ValueLive is false, then this value is being evaluated in a context where
227 /// the result is not used. As such, avoid diagnostics that relate to
229 static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT,
230 bool ValueLive, Preprocessor &PP) {
231 DT.State = DefinedTracker::Unknown;
233 Result.setIdentifier(nullptr);
235 if (PeekTok.is(tok::code_completion)) {
236 if (PP.getCodeCompletionHandler())
237 PP.getCodeCompletionHandler()->CodeCompletePreprocessorExpression();
238 PP.setCodeCompletionReached();
239 PP.LexNonComment(PeekTok);
242 switch (PeekTok.getKind()) {
244 // If this token's spelling is a pp-identifier, check to see if it is
245 // 'defined' or if it is a macro. Note that we check here because many
246 // keywords are pp-identifiers, so we can't check the kind.
247 if (IdentifierInfo *II = PeekTok.getIdentifierInfo()) {
248 // Handle "defined X" and "defined(X)".
249 if (II->isStr("defined"))
250 return EvaluateDefined(Result, PeekTok, DT, ValueLive, PP);
252 if (!II->isCPlusPlusOperatorKeyword()) {
253 // If this identifier isn't 'defined' or one of the special
254 // preprocessor keywords and it wasn't macro expanded, it turns
257 PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II;
259 const DiagnosticsEngine &DiagEngine = PP.getDiagnostics();
260 // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics.
261 if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier,
262 PeekTok.getLocation())) {
263 const std::vector<std::string> UndefPrefixes =
264 DiagEngine.getDiagnosticOptions().UndefPrefixes;
265 const StringRef IdentifierName = II->getName();
266 if (llvm::any_of(UndefPrefixes,
267 [&IdentifierName](const std::string &Prefix) {
268 return IdentifierName.startswith(Prefix);
270 PP.Diag(PeekTok, diag::warn_pp_undef_prefix)
271 << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II;
275 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
276 Result.setIdentifier(II);
277 Result.setRange(PeekTok.getLocation());
278 DT.IncludedUndefinedIds = true;
279 PP.LexNonComment(PeekTok);
283 PP.Diag(PeekTok, diag::err_pp_expr_bad_token_start_expr);
287 // If there is no expression, report and exit.
288 PP.Diag(PeekTok, diag::err_pp_expected_value_in_expr);
290 case tok::numeric_constant: {
291 SmallString<64> IntegerBuffer;
292 bool NumberInvalid = false;
293 StringRef Spelling = PP.getSpelling(PeekTok, IntegerBuffer,
296 return true; // a diagnostic was already reported
298 NumericLiteralParser Literal(Spelling, PeekTok.getLocation(),
299 PP.getSourceManager(), PP.getLangOpts(),
300 PP.getTargetInfo(), PP.getDiagnostics());
301 if (Literal.hadError)
302 return true; // a diagnostic was already reported.
304 if (Literal.isFloatingLiteral() || Literal.isImaginary) {
305 PP.Diag(PeekTok, diag::err_pp_illegal_floating_literal);
308 assert(Literal.isIntegerLiteral() && "Unknown ppnumber");
310 // Complain about, and drop, any ud-suffix.
311 if (Literal.hasUDSuffix())
312 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*integer*/1;
314 // 'long long' is a C99 or C++11 feature.
315 if (!PP.getLangOpts().C99 && Literal.isLongLong) {
316 if (PP.getLangOpts().CPlusPlus)
318 PP.getLangOpts().CPlusPlus11 ?
319 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
321 PP.Diag(PeekTok, diag::ext_c99_longlong);
324 // Parse the integer literal into Result.
325 if (Literal.GetIntegerValue(Result.Val)) {
326 // Overflow parsing integer literal.
328 PP.Diag(PeekTok, diag::err_integer_literal_too_large)
330 Result.Val.setIsUnsigned(true);
332 // Set the signedness of the result to match whether there was a U suffix
334 Result.Val.setIsUnsigned(Literal.isUnsigned);
336 // Detect overflow based on whether the value is signed. If signed
337 // and if the value is too large, emit a warning "integer constant is so
338 // large that it is unsigned" e.g. on 12345678901234567890 where intmax_t
340 if (!Literal.isUnsigned && Result.Val.isNegative()) {
341 // Octal, hexadecimal, and binary literals are implicitly unsigned if
342 // the value does not fit into a signed integer type.
343 if (ValueLive && Literal.getRadix() == 10)
344 PP.Diag(PeekTok, diag::ext_integer_literal_too_large_for_signed);
345 Result.Val.setIsUnsigned(true);
349 // Consume the token.
350 Result.setRange(PeekTok.getLocation());
351 PP.LexNonComment(PeekTok);
354 case tok::char_constant: // 'x'
355 case tok::wide_char_constant: // L'x'
356 case tok::utf8_char_constant: // u8'x'
357 case tok::utf16_char_constant: // u'x'
358 case tok::utf32_char_constant: { // U'x'
359 // Complain about, and drop, any ud-suffix.
360 if (PeekTok.hasUDSuffix())
361 PP.Diag(PeekTok, diag::err_pp_invalid_udl) << /*character*/0;
363 SmallString<32> CharBuffer;
364 bool CharInvalid = false;
365 StringRef ThisTok = PP.getSpelling(PeekTok, CharBuffer, &CharInvalid);
369 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(),
370 PeekTok.getLocation(), PP, PeekTok.getKind());
371 if (Literal.hadError())
372 return true; // A diagnostic was already emitted.
374 // Character literals are always int or wchar_t, expand to intmax_t.
375 const TargetInfo &TI = PP.getTargetInfo();
377 if (Literal.isMultiChar())
378 NumBits = TI.getIntWidth();
379 else if (Literal.isWide())
380 NumBits = TI.getWCharWidth();
381 else if (Literal.isUTF16())
382 NumBits = TI.getChar16Width();
383 else if (Literal.isUTF32())
384 NumBits = TI.getChar32Width();
385 else // char or char8_t
386 NumBits = TI.getCharWidth();
389 llvm::APSInt Val(NumBits);
391 Val = Literal.getValue();
392 // Set the signedness. UTF-16 and UTF-32 are always unsigned
393 if (Literal.isWide())
394 Val.setIsUnsigned(!TargetInfo::isTypeSigned(TI.getWCharType()));
395 else if (!Literal.isUTF16() && !Literal.isUTF32())
396 Val.setIsUnsigned(!PP.getLangOpts().CharIsSigned);
398 if (Result.Val.getBitWidth() > Val.getBitWidth()) {
399 Result.Val = Val.extend(Result.Val.getBitWidth());
401 assert(Result.Val.getBitWidth() == Val.getBitWidth() &&
402 "intmax_t smaller than char/wchar_t?");
406 // Consume the token.
407 Result.setRange(PeekTok.getLocation());
408 PP.LexNonComment(PeekTok);
412 SourceLocation Start = PeekTok.getLocation();
413 PP.LexNonComment(PeekTok); // Eat the (.
414 // Parse the value and if there are any binary operators involved, parse
416 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
418 // If this is a silly value like (X), which doesn't need parens, check for
420 if (PeekTok.is(tok::r_paren)) {
421 // Just use DT unmodified as our result.
423 // Otherwise, we have something like (x+y), and we consumed '(x'.
424 if (EvaluateDirectiveSubExpr(Result, 1, PeekTok, ValueLive,
425 DT.IncludedUndefinedIds, PP))
428 if (PeekTok.isNot(tok::r_paren)) {
429 PP.Diag(PeekTok.getLocation(), diag::err_pp_expected_rparen)
430 << Result.getRange();
431 PP.Diag(Start, diag::note_matching) << tok::l_paren;
434 DT.State = DefinedTracker::Unknown;
436 Result.setRange(Start, PeekTok.getLocation());
437 Result.setIdentifier(nullptr);
438 PP.LexNonComment(PeekTok); // Eat the ).
442 SourceLocation Start = PeekTok.getLocation();
443 // Unary plus doesn't modify the value.
444 PP.LexNonComment(PeekTok);
445 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
446 Result.setBegin(Start);
447 Result.setIdentifier(nullptr);
451 SourceLocation Loc = PeekTok.getLocation();
452 PP.LexNonComment(PeekTok);
453 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
454 Result.setBegin(Loc);
455 Result.setIdentifier(nullptr);
457 // C99 6.5.3.3p3: The sign of the result matches the sign of the operand.
458 Result.Val = -Result.Val;
460 // -MININT is the only thing that overflows. Unsigned never overflows.
461 bool Overflow = !Result.isUnsigned() && Result.Val.isMinSignedValue();
463 // If this operator is live and overflowed, report the issue.
464 if (Overflow && ValueLive)
465 PP.Diag(Loc, diag::warn_pp_expr_overflow) << Result.getRange();
467 DT.State = DefinedTracker::Unknown;
472 SourceLocation Start = PeekTok.getLocation();
473 PP.LexNonComment(PeekTok);
474 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
475 Result.setBegin(Start);
476 Result.setIdentifier(nullptr);
478 // C99 6.5.3.3p4: The sign of the result matches the sign of the operand.
479 Result.Val = ~Result.Val;
480 DT.State = DefinedTracker::Unknown;
485 SourceLocation Start = PeekTok.getLocation();
486 PP.LexNonComment(PeekTok);
487 if (EvaluateValue(Result, PeekTok, DT, ValueLive, PP)) return true;
488 Result.setBegin(Start);
489 Result.Val = !Result.Val;
490 // C99 6.5.3.3p5: The sign of the result is 'int', aka it is signed.
491 Result.Val.setIsUnsigned(false);
492 Result.setIdentifier(nullptr);
494 if (DT.State == DefinedTracker::DefinedMacro)
495 DT.State = DefinedTracker::NotDefinedMacro;
496 else if (DT.State == DefinedTracker::NotDefinedMacro)
497 DT.State = DefinedTracker::DefinedMacro;
502 Result.Val = PeekTok.getKind() == tok::kw_true;
503 Result.Val.setIsUnsigned(false); // "0" is signed intmax_t 0.
504 Result.setIdentifier(PeekTok.getIdentifierInfo());
505 Result.setRange(PeekTok.getLocation());
506 PP.LexNonComment(PeekTok);
509 // FIXME: Handle #assert
513 /// getPrecedence - Return the precedence of the specified binary operator
514 /// token. This returns:
515 /// ~0 - Invalid token.
516 /// 14 -> 3 - various operators.
518 static unsigned getPrecedence(tok::TokenKind Kind) {
523 case tok::star: return 14;
525 case tok::minus: return 13;
527 case tok::greatergreater: return 12;
530 case tok::greaterequal:
531 case tok::greater: return 11;
532 case tok::exclaimequal:
533 case tok::equalequal: return 10;
534 case tok::amp: return 9;
535 case tok::caret: return 8;
536 case tok::pipe: return 7;
537 case tok::ampamp: return 6;
538 case tok::pipepipe: return 5;
539 case tok::question: return 4;
540 case tok::comma: return 3;
541 case tok::colon: return 2;
542 case tok::r_paren: return 0;// Lowest priority, end of expr.
543 case tok::eod: return 0;// Lowest priority, end of directive.
547 static void diagnoseUnexpectedOperator(Preprocessor &PP, PPValue &LHS,
549 if (Tok.is(tok::l_paren) && LHS.getIdentifier())
550 PP.Diag(LHS.getRange().getBegin(), diag::err_pp_expr_bad_token_lparen)
551 << LHS.getIdentifier();
553 PP.Diag(Tok.getLocation(), diag::err_pp_expr_bad_token_binop)
557 /// EvaluateDirectiveSubExpr - Evaluate the subexpression whose first token is
558 /// PeekTok, and whose precedence is PeekPrec. This returns the result in LHS.
560 /// If ValueLive is false, then this value is being evaluated in a context where
561 /// the result is not used. As such, avoid diagnostics that relate to
562 /// evaluation, such as division by zero warnings.
563 static bool EvaluateDirectiveSubExpr(PPValue &LHS, unsigned MinPrec,
564 Token &PeekTok, bool ValueLive,
565 bool &IncludedUndefinedIds,
567 unsigned PeekPrec = getPrecedence(PeekTok.getKind());
568 // If this token isn't valid, report the error.
569 if (PeekPrec == ~0U) {
570 diagnoseUnexpectedOperator(PP, LHS, PeekTok);
575 // If this token has a lower precedence than we are allowed to parse, return
576 // it so that higher levels of the recursion can parse it.
577 if (PeekPrec < MinPrec)
580 tok::TokenKind Operator = PeekTok.getKind();
582 // If this is a short-circuiting operator, see if the RHS of the operator is
583 // dead. Note that this cannot just clobber ValueLive. Consider
584 // "0 && 1 ? 4 : 1 / 0", which is parsed as "(0 && 1) ? 4 : (1 / 0)". In
585 // this example, the RHS of the && being dead does not make the rest of the
588 if (Operator == tok::ampamp && LHS.Val == 0)
589 RHSIsLive = false; // RHS of "0 && x" is dead.
590 else if (Operator == tok::pipepipe && LHS.Val != 0)
591 RHSIsLive = false; // RHS of "1 || x" is dead.
592 else if (Operator == tok::question && LHS.Val == 0)
593 RHSIsLive = false; // RHS (x) of "0 ? x : y" is dead.
595 RHSIsLive = ValueLive;
597 // Consume the operator, remembering the operator's location for reporting.
598 SourceLocation OpLoc = PeekTok.getLocation();
599 PP.LexNonComment(PeekTok);
601 PPValue RHS(LHS.getBitWidth());
602 // Parse the RHS of the operator.
604 if (EvaluateValue(RHS, PeekTok, DT, RHSIsLive, PP)) return true;
605 IncludedUndefinedIds = DT.IncludedUndefinedIds;
607 // Remember the precedence of this operator and get the precedence of the
608 // operator immediately to the right of the RHS.
609 unsigned ThisPrec = PeekPrec;
610 PeekPrec = getPrecedence(PeekTok.getKind());
612 // If this token isn't valid, report the error.
613 if (PeekPrec == ~0U) {
614 diagnoseUnexpectedOperator(PP, RHS, PeekTok);
618 // Decide whether to include the next binop in this subexpression. For
619 // example, when parsing x+y*z and looking at '*', we want to recursively
620 // handle y*z as a single subexpression. We do this because the precedence
621 // of * is higher than that of +. The only strange case we have to handle
622 // here is for the ?: operator, where the precedence is actually lower than
623 // the LHS of the '?'. The grammar rule is:
625 // conditional-expression ::=
626 // logical-OR-expression ? expression : conditional-expression
627 // where 'expression' is actually comma-expression.
629 if (Operator == tok::question)
630 // The RHS of "?" should be maximally consumed as an expression.
631 RHSPrec = getPrecedence(tok::comma);
632 else // All others should munch while higher precedence.
633 RHSPrec = ThisPrec+1;
635 if (PeekPrec >= RHSPrec) {
636 if (EvaluateDirectiveSubExpr(RHS, RHSPrec, PeekTok, RHSIsLive,
637 IncludedUndefinedIds, PP))
639 PeekPrec = getPrecedence(PeekTok.getKind());
641 assert(PeekPrec <= ThisPrec && "Recursion didn't work!");
643 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
644 // either operand is unsigned.
645 llvm::APSInt Res(LHS.getBitWidth());
647 case tok::question: // No UAC for x and y in "x ? y : z".
648 case tok::lessless: // Shift amount doesn't UAC with shift value.
649 case tok::greatergreater: // Shift amount doesn't UAC with shift value.
650 case tok::comma: // Comma operands are not subject to UACs.
651 case tok::pipepipe: // Logical || does not do UACs.
652 case tok::ampamp: // Logical && does not do UACs.
655 Res.setIsUnsigned(LHS.isUnsigned()|RHS.isUnsigned());
656 // If this just promoted something from signed to unsigned, and if the
657 // value was negative, warn about it.
658 if (ValueLive && Res.isUnsigned()) {
659 if (!LHS.isUnsigned() && LHS.Val.isNegative())
660 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 0
661 << LHS.Val.toString(10, true) + " to " +
662 LHS.Val.toString(10, false)
663 << LHS.getRange() << RHS.getRange();
664 if (!RHS.isUnsigned() && RHS.Val.isNegative())
665 PP.Diag(OpLoc, diag::warn_pp_convert_to_positive) << 1
666 << RHS.Val.toString(10, true) + " to " +
667 RHS.Val.toString(10, false)
668 << LHS.getRange() << RHS.getRange();
670 LHS.Val.setIsUnsigned(Res.isUnsigned());
671 RHS.Val.setIsUnsigned(Res.isUnsigned());
674 bool Overflow = false;
676 default: llvm_unreachable("Unknown operator token!");
679 Res = LHS.Val % RHS.Val;
680 else if (ValueLive) {
681 PP.Diag(OpLoc, diag::err_pp_remainder_by_zero)
682 << LHS.getRange() << RHS.getRange();
688 if (LHS.Val.isSigned())
689 Res = llvm::APSInt(LHS.Val.sdiv_ov(RHS.Val, Overflow), false);
691 Res = LHS.Val / RHS.Val;
692 } else if (ValueLive) {
693 PP.Diag(OpLoc, diag::err_pp_division_by_zero)
694 << LHS.getRange() << RHS.getRange();
701 Res = llvm::APSInt(LHS.Val.smul_ov(RHS.Val, Overflow), false);
703 Res = LHS.Val * RHS.Val;
705 case tok::lessless: {
706 // Determine whether overflow is about to happen.
707 if (LHS.isUnsigned())
708 Res = LHS.Val.ushl_ov(RHS.Val, Overflow);
710 Res = llvm::APSInt(LHS.Val.sshl_ov(RHS.Val, Overflow), false);
713 case tok::greatergreater: {
714 // Determine whether overflow is about to happen.
715 unsigned ShAmt = static_cast<unsigned>(RHS.Val.getLimitedValue());
716 if (ShAmt >= LHS.getBitWidth()) {
718 ShAmt = LHS.getBitWidth()-1;
720 Res = LHS.Val >> ShAmt;
724 if (LHS.isUnsigned())
725 Res = LHS.Val + RHS.Val;
727 Res = llvm::APSInt(LHS.Val.sadd_ov(RHS.Val, Overflow), false);
730 if (LHS.isUnsigned())
731 Res = LHS.Val - RHS.Val;
733 Res = llvm::APSInt(LHS.Val.ssub_ov(RHS.Val, Overflow), false);
736 Res = LHS.Val <= RHS.Val;
737 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
740 Res = LHS.Val < RHS.Val;
741 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
743 case tok::greaterequal:
744 Res = LHS.Val >= RHS.Val;
745 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
748 Res = LHS.Val > RHS.Val;
749 Res.setIsUnsigned(false); // C99 6.5.8p6, result is always int (signed)
751 case tok::exclaimequal:
752 Res = LHS.Val != RHS.Val;
753 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
755 case tok::equalequal:
756 Res = LHS.Val == RHS.Val;
757 Res.setIsUnsigned(false); // C99 6.5.9p3, result is always int (signed)
760 Res = LHS.Val & RHS.Val;
763 Res = LHS.Val ^ RHS.Val;
766 Res = LHS.Val | RHS.Val;
769 Res = (LHS.Val != 0 && RHS.Val != 0);
770 Res.setIsUnsigned(false); // C99 6.5.13p3, result is always int (signed)
773 Res = (LHS.Val != 0 || RHS.Val != 0);
774 Res.setIsUnsigned(false); // C99 6.5.14p3, result is always int (signed)
777 // Comma is invalid in pp expressions in c89/c++ mode, but is valid in C99
778 // if not being evaluated.
779 if (!PP.getLangOpts().C99 || ValueLive)
780 PP.Diag(OpLoc, diag::ext_pp_comma_expr)
781 << LHS.getRange() << RHS.getRange();
782 Res = RHS.Val; // LHS = LHS,RHS -> RHS.
784 case tok::question: {
785 // Parse the : part of the expression.
786 if (PeekTok.isNot(tok::colon)) {
787 PP.Diag(PeekTok.getLocation(), diag::err_expected)
788 << tok::colon << LHS.getRange() << RHS.getRange();
789 PP.Diag(OpLoc, diag::note_matching) << tok::question;
793 PP.LexNonComment(PeekTok);
795 // Evaluate the value after the :.
796 bool AfterColonLive = ValueLive && LHS.Val == 0;
797 PPValue AfterColonVal(LHS.getBitWidth());
799 if (EvaluateValue(AfterColonVal, PeekTok, DT, AfterColonLive, PP))
802 // Parse anything after the : with the same precedence as ?. We allow
803 // things of equal precedence because ?: is right associative.
804 if (EvaluateDirectiveSubExpr(AfterColonVal, ThisPrec,
805 PeekTok, AfterColonLive,
806 IncludedUndefinedIds, PP))
809 // Now that we have the condition, the LHS and the RHS of the :, evaluate.
810 Res = LHS.Val != 0 ? RHS.Val : AfterColonVal.Val;
811 RHS.setEnd(AfterColonVal.getRange().getEnd());
813 // Usual arithmetic conversions (C99 6.3.1.8p1): result is unsigned if
814 // either operand is unsigned.
815 Res.setIsUnsigned(RHS.isUnsigned() | AfterColonVal.isUnsigned());
817 // Figure out the precedence of the token after the : part.
818 PeekPrec = getPrecedence(PeekTok.getKind());
822 // Don't allow :'s to float around without being part of ?: exprs.
823 PP.Diag(OpLoc, diag::err_pp_colon_without_question)
824 << LHS.getRange() << RHS.getRange();
828 // If this operator is live and overflowed, report the issue.
829 if (Overflow && ValueLive)
830 PP.Diag(OpLoc, diag::warn_pp_expr_overflow)
831 << LHS.getRange() << RHS.getRange();
833 // Put the result back into 'LHS' for our next iteration.
835 LHS.setEnd(RHS.getRange().getEnd());
836 RHS.setIdentifier(nullptr);
840 /// EvaluateDirectiveExpression - Evaluate an integer constant expression that
841 /// may occur after a #if or #elif directive. If the expression is equivalent
842 /// to "!defined(X)" return X in IfNDefMacro.
843 Preprocessor::DirectiveEvalResult
844 Preprocessor::EvaluateDirectiveExpression(IdentifierInfo *&IfNDefMacro) {
845 SaveAndRestore<bool> PPDir(ParsingIfOrElifDirective, true);
846 // Save the current state of 'DisableMacroExpansion' and reset it to false. If
847 // 'DisableMacroExpansion' is true, then we must be in a macro argument list
848 // in which case a directive is undefined behavior. We want macros to be able
849 // to recursively expand in order to get more gcc-list behavior, so we force
850 // DisableMacroExpansion to false and restore it when we're done parsing the
852 bool DisableMacroExpansionAtStartOfDirective = DisableMacroExpansion;
853 DisableMacroExpansion = false;
855 // Peek ahead one token.
859 // C99 6.10.1p3 - All expressions are evaluated as intmax_t or uintmax_t.
860 unsigned BitWidth = getTargetInfo().getIntMaxTWidth();
862 PPValue ResVal(BitWidth);
864 SourceLocation ExprStartLoc = SourceMgr.getExpansionLoc(Tok.getLocation());
865 if (EvaluateValue(ResVal, Tok, DT, true, *this)) {
866 // Parse error, skip the rest of the macro line.
867 SourceRange ConditionRange = ExprStartLoc;
868 if (Tok.isNot(tok::eod))
869 ConditionRange = DiscardUntilEndOfDirective();
871 // Restore 'DisableMacroExpansion'.
872 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
874 // We cannot trust the source range from the value because there was a
875 // parse error. Track the range manually -- the end of the directive is the
876 // end of the condition range.
878 DT.IncludedUndefinedIds,
879 {ExprStartLoc, ConditionRange.getEnd()}};
882 // If we are at the end of the expression after just parsing a value, there
883 // must be no (unparenthesized) binary operators involved, so we can exit
885 if (Tok.is(tok::eod)) {
886 // If the expression we parsed was of the form !defined(macro), return the
887 // macro in IfNDefMacro.
888 if (DT.State == DefinedTracker::NotDefinedMacro)
889 IfNDefMacro = DT.TheMacro;
891 // Restore 'DisableMacroExpansion'.
892 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
893 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};
896 // Otherwise, we must have a binary operator (e.g. "#if 1 < 2"), so parse the
897 // operator and the stuff after it.
898 if (EvaluateDirectiveSubExpr(ResVal, getPrecedence(tok::question),
899 Tok, true, DT.IncludedUndefinedIds, *this)) {
900 // Parse error, skip the rest of the macro line.
901 if (Tok.isNot(tok::eod))
902 DiscardUntilEndOfDirective();
904 // Restore 'DisableMacroExpansion'.
905 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
906 return {false, DT.IncludedUndefinedIds, ResVal.getRange()};
909 // If we aren't at the tok::eod token, something bad happened, like an extra
911 if (Tok.isNot(tok::eod)) {
912 Diag(Tok, diag::err_pp_expected_eol);
913 DiscardUntilEndOfDirective();
916 // Restore 'DisableMacroExpansion'.
917 DisableMacroExpansion = DisableMacroExpansionAtStartOfDirective;
918 return {ResVal.Val != 0, DT.IncludedUndefinedIds, ResVal.getRange()};